hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
int64
1
368k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
134k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
135
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
131594a073dcc9bd91cf95eed8205d2d44098694
514
sql
SQL
src/db/setup.sql
amoradi/notes_service
323ce45405b77dc6dd2c9672912be69f0c7f63f7
[ "MIT" ]
null
null
null
src/db/setup.sql
amoradi/notes_service
323ce45405b77dc6dd2c9672912be69f0c7f63f7
[ "MIT" ]
null
null
null
src/db/setup.sql
amoradi/notes_service
323ce45405b77dc6dd2c9672912be69f0c7f63f7
[ "MIT" ]
null
null
null
/* Holds all SQL statements needed to model the app, in case it's ever needed for later use. NOTE: varchar 100 used for consistency */ CREATE TABLE IF NOT EXISTS authors ( email varchar(100) NOT NULL UNIQUE, name varchar(100) NOT NULL PRIMARY KEY, api_key varchar(100) NOT NULL /* hashed and salted */ ); CREATE TABLE IF NOT EXISTS notes ( author varchar(100) NOT NULL REFERENCES author(name) ON DELETE CASCADE ON UPDATE CASCADE, content text NOT NULL, /* markdown / html */ idx SERIAL );
24.47619
91
0.715953
64b0c396a5c553df85154699f014501e10803dd6
3,390
sql
SQL
sql/bol_eshop_order_status.sql
rashedshaon/importpark
9ad40f2adbe6c726513b386ad5a337d64fac2444
[ "RSA-MD" ]
null
null
null
sql/bol_eshop_order_status.sql
rashedshaon/importpark
9ad40f2adbe6c726513b386ad5a337d64fac2444
[ "RSA-MD" ]
null
null
null
sql/bol_eshop_order_status.sql
rashedshaon/importpark
9ad40f2adbe6c726513b386ad5a337d64fac2444
[ "RSA-MD" ]
null
null
null
/* Navicat MySQL Data Transfer Source Server : LOCALHOST Source Server Version : 100138 Source Host : localhost:3306 Source Database : importpark Target Server Type : MYSQL Target Server Version : 100138 File Encoding : 65001 Date: 2022-05-01 13:54:52 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for bol_eshop_order_status -- ---------------------------- DROP TABLE IF EXISTS `bol_eshop_order_status`; CREATE TABLE `bol_eshop_order_status` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `code` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `color` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `sort_order` int(11) DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- ---------------------------- -- Records of bol_eshop_order_status -- ---------------------------- INSERT INTO `bol_eshop_order_status` VALUES ('1', 'Pending', 'pending', '#7f8c8d', null, '2022-02-21 16:30:25', '2022-02-21 16:30:25'); INSERT INTO `bol_eshop_order_status` VALUES ('2', 'Delivered', 'delivered', '#27ae60', null, '2022-02-21 16:30:47', '2022-02-21 16:30:47'); INSERT INTO `bol_eshop_order_status` VALUES ('3', 'Cancel', 'cancel', '#e74c3c', null, '2022-02-21 16:30:59', '2022-02-21 16:30:59'); -- ---------------------------- -- Table structure for bol_eshop_payment_methods -- ---------------------------- DROP TABLE IF EXISTS `bol_eshop_payment_methods`; CREATE TABLE `bol_eshop_payment_methods` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `code` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `description` text COLLATE utf8_unicode_ci, `is_active` tinyint(1) NOT NULL, `sort_order` int(11) DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- ---------------------------- -- Records of bol_eshop_payment_methods -- ---------------------------- INSERT INTO `bol_eshop_payment_methods` VALUES ('1', 'Cash on delivery', 'cash-delivery', '', '1', null, '2022-02-21 16:31:19', '2022-02-21 16:31:26'); -- ---------------------------- -- Table structure for bol_eshop_shipping_methods -- ---------------------------- DROP TABLE IF EXISTS `bol_eshop_shipping_methods`; CREATE TABLE `bol_eshop_shipping_methods` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `code` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `price` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `description` text COLLATE utf8_unicode_ci, `is_active` tinyint(1) NOT NULL, `sort_order` int(11) DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- ---------------------------- -- Records of bol_eshop_shipping_methods -- ---------------------------- INSERT INTO `bol_eshop_shipping_methods` VALUES ('1', 'eCourier', 'ecourier', '60', '', '1', null, '2022-02-21 16:31:48', '2022-02-21 19:49:22');
41.341463
151
0.660472
19b34fdda495687a2525b74793ffd45a42f3a249
2,245
lua
Lua
src/Corona/main.lua
agramonte/com.coronalabs-plugin.gpgs.v2
38b2a3736c1be72743a8cd235c3eafb4fc8d1fcb
[ "MIT" ]
null
null
null
src/Corona/main.lua
agramonte/com.coronalabs-plugin.gpgs.v2
38b2a3736c1be72743a8cd235c3eafb4fc8d1fcb
[ "MIT" ]
1
2021-09-15T23:07:57.000Z
2021-09-15T23:07:57.000Z
src/Corona/main.lua
agramonte/com.coronalabs-plugin.gpgs.v2
38b2a3736c1be72743a8cd235c3eafb4fc8d1fcb
[ "MIT" ]
2
2021-08-22T18:36:22.000Z
2021-09-21T23:27:04.000Z
display.setStatusBar(display.HiddenStatusBar) display.setDefault('background', 1) local widget = require('widget') io.output():setvbuf('no') --require('libs.remoteconsole').enable('192.168.0.108', system.getInfo('model') == 'Moto G' and 21000 or 22000) math.randomseed(os.time()) local h = 24 local settings = { isLegacy = false, -- If true, use legacy gameNetwork.* API when available tabBarHeight = h * 3 } -- Set up custom virtual Lua module package.loaded.settings = settings local tabs = {} tabs.auth = require('tabs.auth') tabs.achievements = require('tabs.achievements') tabs.leaderboards = require('tabs.leaderboards') tabs.extra = require('tabs.extra') tabs.events = require('tabs.events') tabs.players = require('tabs.players') tabs.quests = require('tabs.quests') tabs.snapshots = require('tabs.snapshots') tabs.multiplayer = require('tabs.multiplayer') tabs.videos = require('tabs.videos') -- Hide all tab groups except one local function showTab(name) for k, v in pairs(tabs) do v.isVisible = k == name end end showTab('auth') -- Configure the tab buttons to appear within the tabbar local tabButtons = { { {label = 'Auth', onPress = function() showTab('auth') end, selected = true}, {label = 'Achievements', onPress = function() showTab('achievements') end}, {label = 'Leaderboards', onPress = function() showTab('leaderboards') end}, {label = 'Extra', onPress = function() showTab('extra') end} },{ {label = 'Events', onPress = function() showTab('events') end}, {label = 'Players', onPress = function() showTab('players') end}, {label = 'Quests', onPress = function() showTab('quests') end}, {label = 'Requests', onPress = function() showTab('requests') end} },{ {label = 'Snapshots', onPress = function() showTab('snapshots') end}, {label = 'Multiplayer', onPress = function() showTab('multiplayer') end}, {label = 'Videos', onPress = function() showTab('videos') end} } } for i = 1, #tabButtons do widget.newTabBar({ left = display.screenOriginX, top = display.screenOriginY + display.actualContentHeight - h * (#tabButtons - i + 1), width = display.actualContentWidth, height = h, buttons = tabButtons[i] }) end
34.015152
119
0.676169
dccd08b637f99175fc4496c18ff440dff292c300
1,329
kt
Kotlin
app/src/test/java/com/char0dey/calculator/presentation/MainViewModelTest.kt
char0dey/calculator
ac477c8cd9f10e796144423bf6e74e6ab452175c
[ "Apache-2.0" ]
null
null
null
app/src/test/java/com/char0dey/calculator/presentation/MainViewModelTest.kt
char0dey/calculator
ac477c8cd9f10e796144423bf6e74e6ab452175c
[ "Apache-2.0" ]
null
null
null
app/src/test/java/com/char0dey/calculator/presentation/MainViewModelTest.kt
char0dey/calculator
ac477c8cd9f10e796144423bf6e74e6ab452175c
[ "Apache-2.0" ]
null
null
null
package com.char0dey.calculator.presentation import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.Observer import com.char0dey.calculator.data.MainRepository import com.char0dey.calculator.data.Part import com.char0dey.calculator.domain.MainInteractor import org.junit.Assert.assertEquals import org.junit.Test class MainViewModelTest { @Test fun test() { val success = TestCommunication() val viewModel = MainViewModel( success, TestCommunication(), MainInteractor.Base( MainRepository.Base( Part.Base(), Part.Base() ) ) ) assertEquals("", success.text) viewModel.handle("12") assertEquals("12", success.text) viewModel.plus() assertEquals("12 + ", success.text) viewModel.handle("34") assertEquals("12 + 34", success.text) viewModel.calculate() assertEquals("12\n + \n34\n\n = 46", success.text) } private inner class TestCommunication : MainCommunication { var text = "" override fun observe(lifecycleOwner: LifecycleOwner, observer: Observer<String>) { } override fun map(value: String) { text = value } } }
23.315789
90
0.604966
8e5eeb23e7d6d5cf708d4b53946b2a960bf86056
560
sql
SQL
g3/Session 4/Skripts and workshop/Session 4 - Demo 02 String functions.sql
sedc-codecademy/skwd8-07-dbdevdesign
e760febf3b01e8228aa24d6853a8f23de0343e77
[ "MIT" ]
1
2021-11-10T19:08:49.000Z
2021-11-10T19:08:49.000Z
g3/Session 4/Skripts and workshop/Session 4 - Demo 02 String functions.sql
sedc-codecademy/skwd8-07-dbdevdesign
e760febf3b01e8228aa24d6853a8f23de0343e77
[ "MIT" ]
null
null
null
g3/Session 4/Skripts and workshop/Session 4 - Demo 02 String functions.sql
sedc-codecademy/skwd8-07-dbdevdesign
e760febf3b01e8228aa24d6853a8f23de0343e77
[ "MIT" ]
2
2020-08-07T19:32:54.000Z
2020-08-08T08:07:23.000Z
-- String Functions select FirstName , LastName , replace(FirstName,'ks', 'X') as Replace_ks_X , Substring(FirstName, 4, 2) as Substring_4_2 , Left(FirstName, 3) as Left_3 , Right(FirstName, 2) as Right_2 , Len(FirstName) as LenColumn , Concat(FirstName, N' + ', LastName) as Concat_Name from Employee where FirstName = 'Aleksandar' and LastName = 'Stojanovski' go select lastname,STRING_AGG(firstname,',') WITHIN GROUP (ORDER BY firstname) firstname_list from dbo.Employee where FirstName = 'Aleksandar' and LastName = 'Stojanovski' group by LastName
22.4
90
0.753571
053ffb9d40cdf05f104fda019a6ee35c61ede9d7
562
podspec
Ruby
EventTracker.podspec
birwin93/EventTracker
12bcb90d496e1f0aaf3252a56505392646cfce59
[ "MIT" ]
6
2016-11-15T17:59:09.000Z
2018-02-12T20:16:53.000Z
EventTracker.podspec
birwin93/EventTracker
12bcb90d496e1f0aaf3252a56505392646cfce59
[ "MIT" ]
null
null
null
EventTracker.podspec
birwin93/EventTracker
12bcb90d496e1f0aaf3252a56505392646cfce59
[ "MIT" ]
null
null
null
Pod::Spec.new do |spec| spec.name = "EventTracker" spec.version = "0.1.2" spec.summary = "Framework to log events" spec.homepage = "https://github.com/birwin93/EventTracker" spec.license = { type: 'MIT', file: 'LICENSE' } spec.authors = { "Billy Irwin" => 'birwin93@gmail.com' } spec.social_media_url = "http://twitter.com/billy_the_kid" spec.platform = :ios, "9.0" spec.requires_arc = true spec.source = { git: "https://github.com/birwin93/EventTracker.git", tag: "#{spec.version}" } spec.source_files = "EventTracker/**/*.{h,swift}" end
37.466667
95
0.672598
d0089e8e71f8a0965b74c614762d897cfcb64878
401
css
CSS
components/blocksEdit/profile.css
dave4506/impressive
8de960a6efd85d40db10aa1791b42faf03db0ae9
[ "MIT" ]
null
null
null
components/blocksEdit/profile.css
dave4506/impressive
8de960a6efd85d40db10aa1791b42faf03db0ae9
[ "MIT" ]
null
null
null
components/blocksEdit/profile.css
dave4506/impressive
8de960a6efd85d40db10aa1791b42faf03db0ae9
[ "MIT" ]
null
null
null
.block-profile { } .block-profile-img { width: 10rem; height: 10rem; border-radius: 50%; margin: 1rem; } .block-profile-name { font-family: 'Merriweather', serif; font-size: 3rem; margin:0; padding: 1rem; text-align: center; } .block-profile-description { font-weight: 700; letter-spacing: normal; margin:0; font-size: 1.1rem; padding: 0.4rem; text-align: center; }
14.321429
37
0.653367
e667cd7db4ba7955484fd31cacbaf261579209d3
902
dart
Dart
lib/conversation/data/repository/conversation_repository.dart
gyakhoe/flutter_chat
1b38d44c5c21d72e7fac0099eaae1e1e636c7077
[ "MIT" ]
4
2022-01-11T23:27:33.000Z
2022-03-23T18:03:16.000Z
lib/conversation/data/repository/conversation_repository.dart
gyakhoe/flutter_chat
1b38d44c5c21d72e7fac0099eaae1e1e636c7077
[ "MIT" ]
null
null
null
lib/conversation/data/repository/conversation_repository.dart
gyakhoe/flutter_chat
1b38d44c5c21d72e7fac0099eaae1e1e636c7077
[ "MIT" ]
1
2022-01-29T03:57:47.000Z
2022-01-29T03:57:47.000Z
import 'package:flutter_chat/conversation/conversation.dart'; class ConversationRepository { final ConversationFirebaseProvider conversationFirebaseProvider; ConversationRepository({ required this.conversationFirebaseProvider, }); Future<Conversation?> getConversation({ required String senderUID, required String receiverUID, }) async { final convesationMap = await conversationFirebaseProvider.getConversationId( senderUID: senderUID, receiverUID: receiverUID, ); if (convesationMap == null) { return null; } else { return Conversation.fromMap(convesationMap); } } Future<String> createConversation({ required Conversation conversation, }) async { final conversationId = await conversationFirebaseProvider.createConversation( conversation: conversation.toMap(), ); return conversationId; } }
25.771429
80
0.728381
be702f490f12732866ceec5026966e82d153e2a4
1,347
kt
Kotlin
plugin-bazel-event-service/src/main/kotlin/bazel/messages/handlers/AbortedHandler.kt
Privitar/teamcity-bazel-plugin
0e03c37df11aa71d353ca818a7d8d6fde8202860
[ "Apache-2.0" ]
13
2018-11-15T12:13:16.000Z
2022-03-31T06:28:12.000Z
plugin-bazel-event-service/src/main/kotlin/bazel/messages/handlers/AbortedHandler.kt
Privitar/teamcity-bazel-plugin
0e03c37df11aa71d353ca818a7d8d6fde8202860
[ "Apache-2.0" ]
17
2019-02-07T20:07:08.000Z
2021-03-04T06:15:22.000Z
plugin-bazel-event-service/src/main/kotlin/bazel/messages/handlers/AbortedHandler.kt
Privitar/teamcity-bazel-plugin
0e03c37df11aa71d353ca818a7d8d6fde8202860
[ "Apache-2.0" ]
7
2018-12-29T04:53:39.000Z
2022-03-19T09:19:56.000Z
package bazel.messages.handlers import bazel.HandlerPriority import bazel.bazel.events.Aborted import bazel.bazel.events.BazelEvent import bazel.messages.Color import bazel.messages.ServiceMessageContext import bazel.messages.apply class AbortedHandler : EventHandler { override val priority: HandlerPriority get() = HandlerPriority.Low override fun handle(ctx: ServiceMessageContext) = if (ctx.event.payload is BazelEvent && ctx.event.payload.content is Aborted) { val event = ctx.event.payload.content ctx.hierarchy.tryAbortNode(ctx, event.id)?.let { if (it.description.isNotEmpty()) { ctx.onNext(ctx.messageFactory. createMessage( ctx.buildMessage(false) .append(it.description) .append(" aborted.".apply(Color.Error)) .append(" ${event.reason.description}") .append(if (event.description.isNotBlank()) ": ${event.description}" else ".") .toString())) } } true } else ctx.handlerIterator.next().handle(ctx) }
42.09375
118
0.532294
4e2280a10c696add63d79b827d8c94fb0966594b
321
asm
Assembly
programs/oeis/317/A317657.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/317/A317657.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/317/A317657.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A317657: Numbers congruent to {15, 75, 95} mod 100. ; 15,75,95,115,175,195,215,275,295,315,375,395,415,475,495,515,575,595,615,675,695,715,775,795,815,875,895,915,975,995,1015,1075,1095,1115,1175,1195,1215,1275,1295,1315,1375,1395,1415,1475,1495,1515 mov $1,$0 add $0,2 div $0,3 mul $0,2 add $0,$1 mul $0,20 add $0,15
29.181818
198
0.700935
1fa3b07edf8b49fa46775a180e1ba6931f925fac
2,330
html
HTML
_layouts/post.html
Sincky/Sincky.github.io
42f87e9ff539d4c58c642a89d627a71abf0d4d9d
[ "MIT" ]
null
null
null
_layouts/post.html
Sincky/Sincky.github.io
42f87e9ff539d4c58c642a89d627a71abf0d4d9d
[ "MIT" ]
null
null
null
_layouts/post.html
Sincky/Sincky.github.io
42f87e9ff539d4c58c642a89d627a71abf0d4d9d
[ "MIT" ]
null
null
null
--- layout: default --- <!-- 判断是否插入首页图片 --> {% if page.image.feature %} <div class="post-image-feature"> <img class="feature-image" src= {% if page.image.feature contains 'https' or page.image.feature contains 'http' %} "{{ page.image.feature }}" {% else %} "{{ site.url }}/img/{{ page.image.feature }}" {% endif %} alt="{{ page.title }} feature image"> {% if page.image.credit %} <span class="image-credit">Photo Credit: <a href="{{ page.image.creditlink }}">{{ page.image.credit }}</a></span> {% endif %} </div> {% endif %} <!-- 添加日期和阅读 --> <div id="post"> <header class="post-header"> <span class="post-meta"> <span class="post-date"> {{ page.date | date: "%Y-%m-%d" | upcase }} </span> • {% include read_time.html %} </span> <h1 title="{{ page.title }}">{{ page.title }}</h1> </header> <!-- 引入google code pretiffy高亮样式 --> <link href="/js/google-code-prettify/themes/github-v2.css" rel="stylesheet" type="text/css" /> <!-- 添加博文 --> <article class="post-content"> {{ content }} </article> </div> <!-- 引入google code pretiffy --> <script src="/js/jquery.min.js"></script> <script src="/js/google-code-prettify/prettify.js"></script> <script type="text/javascript"> $(function(){ $("pre").addClass("prettyprint linenums"); prettyPrint(); }); </script> <!-- 添加博文分割线 --> <hr class="post-list__divider" /> {% include new-old.html %} <!-- 多说评论框 start --> {% if page.comments == true %} <div class="ds-thread" data-thread-key="{{ site.url }}" data-title="{{ page.title }}" data-url="{{ site.url }}"></div> <!-- 多说评论框 end --> <!-- 多说公共JS代码 start (一个网页只需插入一次) --> <script type="text/javascript"> var duoshuoQuery = {short_name:"{{ site.owner.duoshuo }}"}; (function() { var ds = document.createElement('script'); ds.type = 'text/javascript';ds.async = true; ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js'; ds.charset = 'UTF-8'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ds); })(); </script> <!-- 多说公共JS代码 end --> {% endif %}
30.657895
121
0.551502
6c28ea9b0be480dc267351392e50d2c10929a1b2
6,599
go
Go
daemon/vtep/fakes/netAdapter.go
IvanHristov98/silk
eda18cff3827b5019f36a7a31121ab0d6221d3f8
[ "Apache-2.0" ]
13
2017-11-04T20:37:45.000Z
2021-06-14T13:28:06.000Z
daemon/vtep/fakes/netAdapter.go
IvanHristov98/silk
eda18cff3827b5019f36a7a31121ab0d6221d3f8
[ "Apache-2.0" ]
11
2018-05-21T08:46:54.000Z
2022-03-28T15:12:05.000Z
daemon/vtep/fakes/netAdapter.go
IvanHristov98/silk
eda18cff3827b5019f36a7a31121ab0d6221d3f8
[ "Apache-2.0" ]
8
2017-11-16T12:53:40.000Z
2022-01-07T13:51:41.000Z
// Code generated by counterfeiter. DO NOT EDIT. package fakes import ( "net" "sync" ) type NetAdapter struct { InterfacesStub func() ([]net.Interface, error) interfacesMutex sync.RWMutex interfacesArgsForCall []struct{} interfacesReturns struct { result1 []net.Interface result2 error } interfacesReturnsOnCall map[int]struct { result1 []net.Interface result2 error } InterfaceAddrsStub func(net.Interface) ([]net.Addr, error) interfaceAddrsMutex sync.RWMutex interfaceAddrsArgsForCall []struct { arg1 net.Interface } interfaceAddrsReturns struct { result1 []net.Addr result2 error } interfaceAddrsReturnsOnCall map[int]struct { result1 []net.Addr result2 error } InterfaceByNameStub func(name string) (*net.Interface, error) interfaceByNameMutex sync.RWMutex interfaceByNameArgsForCall []struct { name string } interfaceByNameReturns struct { result1 *net.Interface result2 error } interfaceByNameReturnsOnCall map[int]struct { result1 *net.Interface result2 error } invocations map[string][][]interface{} invocationsMutex sync.RWMutex } func (fake *NetAdapter) Interfaces() ([]net.Interface, error) { fake.interfacesMutex.Lock() ret, specificReturn := fake.interfacesReturnsOnCall[len(fake.interfacesArgsForCall)] fake.interfacesArgsForCall = append(fake.interfacesArgsForCall, struct{}{}) fake.recordInvocation("Interfaces", []interface{}{}) fake.interfacesMutex.Unlock() if fake.InterfacesStub != nil { return fake.InterfacesStub() } if specificReturn { return ret.result1, ret.result2 } return fake.interfacesReturns.result1, fake.interfacesReturns.result2 } func (fake *NetAdapter) InterfacesCallCount() int { fake.interfacesMutex.RLock() defer fake.interfacesMutex.RUnlock() return len(fake.interfacesArgsForCall) } func (fake *NetAdapter) InterfacesReturns(result1 []net.Interface, result2 error) { fake.InterfacesStub = nil fake.interfacesReturns = struct { result1 []net.Interface result2 error }{result1, result2} } func (fake *NetAdapter) InterfacesReturnsOnCall(i int, result1 []net.Interface, result2 error) { fake.InterfacesStub = nil if fake.interfacesReturnsOnCall == nil { fake.interfacesReturnsOnCall = make(map[int]struct { result1 []net.Interface result2 error }) } fake.interfacesReturnsOnCall[i] = struct { result1 []net.Interface result2 error }{result1, result2} } func (fake *NetAdapter) InterfaceAddrs(arg1 net.Interface) ([]net.Addr, error) { fake.interfaceAddrsMutex.Lock() ret, specificReturn := fake.interfaceAddrsReturnsOnCall[len(fake.interfaceAddrsArgsForCall)] fake.interfaceAddrsArgsForCall = append(fake.interfaceAddrsArgsForCall, struct { arg1 net.Interface }{arg1}) fake.recordInvocation("InterfaceAddrs", []interface{}{arg1}) fake.interfaceAddrsMutex.Unlock() if fake.InterfaceAddrsStub != nil { return fake.InterfaceAddrsStub(arg1) } if specificReturn { return ret.result1, ret.result2 } return fake.interfaceAddrsReturns.result1, fake.interfaceAddrsReturns.result2 } func (fake *NetAdapter) InterfaceAddrsCallCount() int { fake.interfaceAddrsMutex.RLock() defer fake.interfaceAddrsMutex.RUnlock() return len(fake.interfaceAddrsArgsForCall) } func (fake *NetAdapter) InterfaceAddrsArgsForCall(i int) net.Interface { fake.interfaceAddrsMutex.RLock() defer fake.interfaceAddrsMutex.RUnlock() return fake.interfaceAddrsArgsForCall[i].arg1 } func (fake *NetAdapter) InterfaceAddrsReturns(result1 []net.Addr, result2 error) { fake.InterfaceAddrsStub = nil fake.interfaceAddrsReturns = struct { result1 []net.Addr result2 error }{result1, result2} } func (fake *NetAdapter) InterfaceAddrsReturnsOnCall(i int, result1 []net.Addr, result2 error) { fake.InterfaceAddrsStub = nil if fake.interfaceAddrsReturnsOnCall == nil { fake.interfaceAddrsReturnsOnCall = make(map[int]struct { result1 []net.Addr result2 error }) } fake.interfaceAddrsReturnsOnCall[i] = struct { result1 []net.Addr result2 error }{result1, result2} } func (fake *NetAdapter) InterfaceByName(name string) (*net.Interface, error) { fake.interfaceByNameMutex.Lock() ret, specificReturn := fake.interfaceByNameReturnsOnCall[len(fake.interfaceByNameArgsForCall)] fake.interfaceByNameArgsForCall = append(fake.interfaceByNameArgsForCall, struct { name string }{name}) fake.recordInvocation("InterfaceByName", []interface{}{name}) fake.interfaceByNameMutex.Unlock() if fake.InterfaceByNameStub != nil { return fake.InterfaceByNameStub(name) } if specificReturn { return ret.result1, ret.result2 } return fake.interfaceByNameReturns.result1, fake.interfaceByNameReturns.result2 } func (fake *NetAdapter) InterfaceByNameCallCount() int { fake.interfaceByNameMutex.RLock() defer fake.interfaceByNameMutex.RUnlock() return len(fake.interfaceByNameArgsForCall) } func (fake *NetAdapter) InterfaceByNameArgsForCall(i int) string { fake.interfaceByNameMutex.RLock() defer fake.interfaceByNameMutex.RUnlock() return fake.interfaceByNameArgsForCall[i].name } func (fake *NetAdapter) InterfaceByNameReturns(result1 *net.Interface, result2 error) { fake.InterfaceByNameStub = nil fake.interfaceByNameReturns = struct { result1 *net.Interface result2 error }{result1, result2} } func (fake *NetAdapter) InterfaceByNameReturnsOnCall(i int, result1 *net.Interface, result2 error) { fake.InterfaceByNameStub = nil if fake.interfaceByNameReturnsOnCall == nil { fake.interfaceByNameReturnsOnCall = make(map[int]struct { result1 *net.Interface result2 error }) } fake.interfaceByNameReturnsOnCall[i] = struct { result1 *net.Interface result2 error }{result1, result2} } func (fake *NetAdapter) Invocations() map[string][][]interface{} { fake.invocationsMutex.RLock() defer fake.invocationsMutex.RUnlock() fake.interfacesMutex.RLock() defer fake.interfacesMutex.RUnlock() fake.interfaceAddrsMutex.RLock() defer fake.interfaceAddrsMutex.RUnlock() fake.interfaceByNameMutex.RLock() defer fake.interfaceByNameMutex.RUnlock() copiedInvocations := map[string][][]interface{}{} for key, value := range fake.invocations { copiedInvocations[key] = value } return copiedInvocations } func (fake *NetAdapter) recordInvocation(key string, args []interface{}) { fake.invocationsMutex.Lock() defer fake.invocationsMutex.Unlock() if fake.invocations == nil { fake.invocations = map[string][][]interface{}{} } if fake.invocations[key] == nil { fake.invocations[key] = [][]interface{}{} } fake.invocations[key] = append(fake.invocations[key], args) }
29.591928
100
0.764661
7b7763e9dc62645bf4bdbac655aa043c764872a2
1,434
dart
Dart
unpub_web/lib/src/routes.dart
yeyu1271/unpub
a8c4be7b60f823b225363fb0e6491660890bfa92
[ "MIT" ]
278
2019-05-10T04:26:30.000Z
2022-03-30T00:14:36.000Z
unpub_web/lib/src/routes.dart
yeyu1271/unpub
a8c4be7b60f823b225363fb0e6491660890bfa92
[ "MIT" ]
55
2019-07-03T07:00:46.000Z
2022-03-29T11:40:18.000Z
unpub_web/lib/src/routes.dart
MobiliteDev/unpub
c675efba5c5c424e60ce61cc8c3902bea951610a
[ "MIT" ]
80
2019-08-05T08:29:18.000Z
2022-03-18T09:39:26.000Z
import 'package:angular_router/angular_router.dart'; import 'home_component.template.dart' as home_template; import 'list_component.template.dart' as list_template; import 'detail_component.template.dart' as detail_template; // import 'not_found_component.template.dart' as not_found_template; class RoutePaths { static final home = RoutePath(path: ''); static final list = RoutePath(path: 'packages'); static final detail = RoutePath(path: 'packages/:name'); static final detailVersion = RoutePath(path: 'packages/:name/versions/:version'); } class Routes { static final home = RouteDefinition( routePath: RoutePaths.home, component: home_template.HomeComponentNgFactory, ); static final list = RouteDefinition( routePath: RoutePaths.list, component: list_template.ListComponentNgFactory, ); static final detail = RouteDefinition( routePath: RoutePaths.detail, component: detail_template.DetailComponentNgFactory, ); static final detailVersion = RouteDefinition( routePath: RoutePaths.detailVersion, component: detail_template.DetailComponentNgFactory, ); static final all = <RouteDefinition>[ home, list, detail, // RouteDefinition.redirect( // path: '', // redirectTo: RoutePaths.heroes.toUrl(), // ), // RouteDefinition( // path: '.*', // component: not_found_template.NotFoundComponentNgFactory, // ), ]; }
29.875
68
0.72106
bbcfe520f9f90147e668e541c78d7b0218ee81c3
220
sql
SQL
Oracle SQL/Higher Than 75 Marks.sql
fukakai/HackerRank-Solutions
cf4ae5a982e60667eb1ec57d0a2ae8720585b5c9
[ "MIT" ]
null
null
null
Oracle SQL/Higher Than 75 Marks.sql
fukakai/HackerRank-Solutions
cf4ae5a982e60667eb1ec57d0a2ae8720585b5c9
[ "MIT" ]
null
null
null
Oracle SQL/Higher Than 75 Marks.sql
fukakai/HackerRank-Solutions
cf4ae5a982e60667eb1ec57d0a2ae8720585b5c9
[ "MIT" ]
null
null
null
/* Author: Romain DALICHAMP Github: https://github.com/fukakai Portfolio: http://romain.dalichamp.fr Contact: romain.dalichamp@free.fr */ select NAME from STUDENTS where MARKS > 75 order by SUBSTR(NAME,-3,3), ID ASC;
24.444444
38
0.745455
92a42d55f9aa9c14044d3e0b4088a5622fe1fbe5
181
kt
Kotlin
app/src/main/java/com/kk/hub/repository/dao/UserDao.kt
perrrfeck/KKhub
9a954acf1fdc8658286fc91de4edb809e4d87291
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/kk/hub/repository/dao/UserDao.kt
perrrfeck/KKhub
9a954acf1fdc8658286fc91de4edb809e4d87291
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/kk/hub/repository/dao/UserDao.kt
perrrfeck/KKhub
9a954acf1fdc8658286fc91de4edb809e4d87291
[ "Apache-2.0" ]
null
null
null
package com.kk.hub.repository.dao import android.app.Application /** * Created by kk on 2019/11/4 09:47 */ class UserDao constructor(private val application: Application) { }
16.454545
65
0.740331
74cc9f28a4ada34c7818ea6dbd08f599a442a70d
3,178
js
JavaScript
packages/nexpa/src/plugins/modals.js
arash16/nexpa
35b0dd30286e7c26174667f47eaab6c4dce05e36
[ "Apache-2.0" ]
1
2017-05-16T12:41:03.000Z
2017-05-16T12:41:03.000Z
packages/nexpa/src/plugins/modals.js
arash16/nexpa
35b0dd30286e7c26174667f47eaab6c4dce05e36
[ "Apache-2.0" ]
null
null
null
packages/nexpa/src/plugins/modals.js
arash16/nexpa
35b0dd30286e7c26174667f47eaab6c4dce05e36
[ "Apache-2.0" ]
null
null
null
var activeModals = nx.state([]), openModalsCount = nx(0); registerGlobalElement(<div class="modals-container"> <div class={ "modal-backdrop fade " + (openModalsCount() ? 'in' : 'invisible')}></div> {activeModals} </div>); spa.modal = function (title, body, buttons) { var result = nx(), fading = nx(false), visible = nx(false), header = !isString(title) ? title : <h3 class="modal-title">{title}</h3>, footerButtons = (buttons || [l('OK')]).map(function (btn, ind, arr) { var type = btn.type || (ind == arr.length - 1 ? 'primary' : 'default'), content = btn.value || btn, classes = 'btn btn-sm btn-' + type + (btn.class ? ' ' + btn.class : ''); return <button type="button" class={classes} onclick={() => closeDialog(content, ind)}>{content}</button>; }), styles = nx(function () { return { display: visible() || fading() ? 'table' : 'none' }; }), classes = nx(2, step => 'modal fade' + (visible() && step ? ' in' : '')), modalElem = <div style={styles} class={classes} onclick={closeNull} tabindex="-1" role="dialog" aria-hidden="false"> <div class="modal-dialog"> <div class="modal-content" onclick={stopPropagation}> <div class="modal-header"> <button type="button" class="close" aria-hidden="true" onclick={closeNull}>×</button> {header} </div> <div class="modal-body">{body}</div> <div class="modal-footer">{footerButtons}</div> </div> </div> </div>; function closeNull() { closeDialog(null); } function openDialog(onComplete) { if (visible.peek()) return; if (disposed) { disposed = false; activeModals(activeModals().concat(modalElem)); } else if (closingTimer) clearTimeout(closingTimer); openModalsCount(openModalsCount.peek() + 1); closingTimer = undefined; visible(true); fading(false); result(undefined); if (isFunc(onComplete)) onCompleteHandler = onComplete; return result; } function closeDialog(optionChosen, ind) { if (closingTimer) return; fading(true); visible(false); closingTimer = setTimeout(dispose, 400); result(optionChosen); if (isFunc(onCompleteHandler)) onCompleteHandler(optionChosen, ind); openModalsCount(openModalsCount.peek() - 1); } function dispose() { closingTimer = undefined; if (disposed) return; disposed = true; visible(false); fading(false); var am = activeModals(), ind = am.indexOf(modalElem); if (ind >= 0) { am = am.slice(); am.splice(ind, 1); activeModals(am); } } var disposed = true, onCompleteHandler, closingTimer; return { show: openDialog }; };
33.104167
118
0.521712
964b234751ee397fef50672e3faf739e90c9c3cf
4,329
php
PHP
app/Http/Controllers/Api/BankController.php
aboayube/financialpp
f0d0d6e4d381c841edc275188820c2d483139fb9
[ "MIT" ]
null
null
null
app/Http/Controllers/Api/BankController.php
aboayube/financialpp
f0d0d6e4d381c841edc275188820c2d483139fb9
[ "MIT" ]
null
null
null
app/Http/Controllers/Api/BankController.php
aboayube/financialpp
f0d0d6e4d381c841edc275188820c2d483139fb9
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers\Api; use Illuminate\Support\Str; use App\Http\Controllers\Controller; use Intervention\Image\Facades\Image; use App\Http\Resources\CatoriesResource; use App\Models\Bank; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class BankController extends Controller { public function index($lang) { $this->set_Language($lang); $banks = Bank::orderBy('id', 'DESC')->paginate(10); if ($banks->count() > 0) { return response()->json(['error' => false, 'data' => CatoriesResource::collection($banks), 'status' => 200]); } else { return response()->json(['error' => true, 'message' => 'No bank found', 'status' => 200],); } } public function create(Request $request) { $validation = Validator::make($request->all(), [ 'name' => 'required', 'name_en' => 'required', 'image' => 'required', ]); if ($validation->fails()) { return response()->json(['errors' => true, 'message' => $validation->errors()], 200); } /* if ($image = $request->file('image')) { $filename = Str::slug($request->post('image')) . '.' . $image->getClientOriginalExtension(); $path = public_path('assets/banks/' . $filename); Image::make($image->getRealPath())->resize(300, 300, function ($constraint) { $constraint->aspectRatio(); })->save($path, 100); $dataImage = $filename; } */ $cats = auth()->user()->banks()->create([ 'name' => $request->post('name'), 'name_en' => $request->post('name_en'), 'image' => $request->post('image'), 'status' => $request->post('status') ]); if ($cats) { return response()->json(['errors' => 'false', 'message' => 'created successfully category', 'status' => 201], 200); } } public function edit($id) { $cat = Bank::find($id); if ($cat) { return response()->json([ 'errors' => 'false', 'message' => 'get data successfully category', 'data' => new CatoriesResource($cat), 'status' => 201 ], 201); } else { return response()->json(['error' => true, 'message' => 'not there data', "status" => 404]); } } public function update(Request $request, $id) { $cat = Bank::find($id); if ($cat) { $validation = Validator::make($request->all(), [ 'name' => 'required', 'name_en' => 'required', 'image' => 'required', ]); if ($validation->fails()) { return response()->json(['errors' => true, 'message' => $validation->errors(), 'status' => 200]); } /* $dataImage = $cat->image; if ($image = $request->file('image')) { $filename = Str::slug($request->post('image')) . '.' . $image->getClientOriginalExtension(); $path = public_path('assets/banks/' . $filename); Image::make($image->getRealPath())->resize(300, 300, function ($constraint) { $constraint->aspectRatio(); })->save($path, 100); $dataImage = $filename; } */ $cat->update([ 'name' => $request->name, 'name_en' => $request->name_en, 'image' => $request->image, ]); return response()->json([ 'errors' => 'false', 'data' => new CatoriesResource($cat), 'status' => 201 ]); } return response()->json(['errors' => true, 'message' => "somthing was error ", 'status' => 404],); } public function delete($id) { $cat = Bank::find($id); if ($cat) { $cat->delete(); return response()->json([ 'errors' => 'false', 'message' => 'delete successfully bank', 'status' => 200, ], 200); } return response()->json(['errors' => true, 'message' => "there is errors ", 'status' => 404]); } }
34.632
127
0.480711
6e63d1643bf63dccbd0c7fb28cf8eb105198ef6b
980
kt
Kotlin
feature-wallet-api/src/main/java/jp/co/soramitsu/feature_wallet_api/data/mappers/TokenTypeMappers.kt
soramitsu/fearless-Android
ce2d28cd14a57c20f4d1757a89e23d2709c63072
[ "Apache-2.0" ]
59
2020-08-01T11:18:37.000Z
2022-03-26T15:49:30.000Z
feature-wallet-api/src/main/java/jp/co/soramitsu/feature_wallet_api/data/mappers/TokenTypeMappers.kt
soramitsu/fearless-Android
ce2d28cd14a57c20f4d1757a89e23d2709c63072
[ "Apache-2.0" ]
37
2020-08-08T09:46:04.000Z
2022-03-17T06:27:21.000Z
feature-wallet-api/src/main/java/jp/co/soramitsu/feature_wallet_api/data/mappers/TokenTypeMappers.kt
soramitsu/fearless-Android
ce2d28cd14a57c20f4d1757a89e23d2709c63072
[ "Apache-2.0" ]
16
2020-09-19T07:48:27.000Z
2022-03-16T12:56:51.000Z
package jp.co.soramitsu.feature_wallet_api.data.mappers import jp.co.soramitsu.core.model.Node import jp.co.soramitsu.core_db.model.TokenLocal import jp.co.soramitsu.feature_wallet_api.domain.model.Token fun mapTokenTypeToTokenTypeLocal(type: Token.Type): TokenLocal.Type { return when (type) { Token.Type.DOT -> TokenLocal.Type.DOT Token.Type.KSM -> TokenLocal.Type.KSM Token.Type.WND -> TokenLocal.Type.WND Token.Type.ROC -> TokenLocal.Type.ROC } } fun mapTokenTypeLocalToTokenType(type: TokenLocal.Type): Token.Type { return when (type) { TokenLocal.Type.DOT -> Token.Type.DOT TokenLocal.Type.KSM -> Token.Type.KSM TokenLocal.Type.WND -> Token.Type.WND TokenLocal.Type.ROC -> Token.Type.ROC } } fun tokenTypeLocalFromNetworkType(networkType: Node.NetworkType): TokenLocal.Type { val tokenType = Token.Type.fromNetworkType(networkType) return mapTokenTypeToTokenTypeLocal(tokenType) }
32.666667
83
0.727551
cb5e28eb4020f0d7d7a22ce0e470f7769dde05a1
236
h
C
BaseViewController/BaseNavigationController.h
PublicProjectMember/PublicProject
0cd6e0740affed48680f1c12b4dc999a952da97f
[ "MIT" ]
null
null
null
BaseViewController/BaseNavigationController.h
PublicProjectMember/PublicProject
0cd6e0740affed48680f1c12b4dc999a952da97f
[ "MIT" ]
null
null
null
BaseViewController/BaseNavigationController.h
PublicProjectMember/PublicProject
0cd6e0740affed48680f1c12b4dc999a952da97f
[ "MIT" ]
null
null
null
// // // UIComponent // // Created by Bob on 14-5-12. // Copyright (c) 2014年 guobo. All rights reserved. // #import <UIKit/UIKit.h> @interface BaseNavigationController : UINavigationController<UINavigationControllerDelegate> @end
16.857143
92
0.728814
b82cb33d94af03485aeb3ca688b3dd77433d522f
2,454
rs
Rust
cmd/miner_client/src/test.rs
fakecoinbase/starcoinorgslashstarcoin
100a01fb1c967d1b4dd0dc1b9d5787d45c9ba399
[ "Apache-2.0" ]
1
2020-08-03T06:26:04.000Z
2020-08-03T06:26:04.000Z
cmd/miner_client/src/test.rs
fakecoinbase/starcoinorgslashstarcoin
100a01fb1c967d1b4dd0dc1b9d5787d45c9ba399
[ "Apache-2.0" ]
34
2020-07-26T16:13:41.000Z
2022-02-06T18:15:25.000Z
cmd/miner_client/src/test.rs
fakecoinbase/starcoinorgslashstarcoin
100a01fb1c967d1b4dd0dc1b9d5787d45c9ba399
[ "Apache-2.0" ]
null
null
null
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::miner::MinerClientActor; use crate::stratum::{parse_response, process_request}; use actix::Actor; use actix_rt::System; use bus::BusActor; use config::MinerConfig; use config::NodeConfig; use consensus::argon::ArgonConsensus; use futures_timer::Delay; use logger::prelude::*; use sc_stratum::{PushWorkHandler, Stratum}; use starcoin_miner::{ miner::{MineCtx, Miner}, stratum::StratumManager, }; use std::sync::Arc; use std::time::Duration; use types::block::{Block, BlockBody, BlockHeader, BlockTemplate}; use types::U256; #[test] fn test_stratum_client() { ::logger::init_for_test(); let mut system = System::new("test"); system.block_on(async { let mut miner_config = MinerConfig::default(); miner_config.consensus_strategy = config::ConsensusStrategy::Argon(4); let conf = Arc::new(NodeConfig::random_for_test()); let mut miner = Miner::<ArgonConsensus>::new(BusActor::launch(), conf); let stratum = { let dispatcher = Arc::new(StratumManager::new(miner.clone())); Stratum::start(&miner_config.stratum_server, dispatcher, None).unwrap() }; Delay::new(Duration::from_millis(3000)).await; info!("started stratum server"); let mine_ctx = { let header = BlockHeader::random(); let body = BlockBody::default(); let block = Block::new(header, body); let block_template = BlockTemplate::from_block(block); let difficulty: U256 = 1.into(); MineCtx::new(block_template, difficulty) }; let _addr = MinerClientActor::new(miner_config).start(); miner.set_mint_job(mine_ctx); for _ in 1..10 { stratum.push_work_all(miner.get_mint_job()).unwrap(); Delay::new(Duration::from_millis(2000)).await; } }); } #[test] fn test_json() { let json_str = r#" {"jsonrpc":"2.0","result":true,"id":0} "#; let result = parse_response::<bool>(json_str); assert!(result.is_ok(), "parse response error: {:?}", result.err()); let json_str = r#" { "id": 19, "method": "mining.notify", "params": ["e419ff9f57cc615f1b9ee900097f6ce34ad5eaff61eda78414efa1c3fa9e8200","1"] } "#; let result = process_request(json_str); assert!(result.is_ok(), "process request fail:{:?}", result.err()); }
35.057143
127
0.640994
647dedd17e31a77ceaf735f34441bd1c24021a97
3,697
rs
Rust
src/util.rs
aschampion/heraclitus
ef89e91614e29afe29d4f4e7db43f3a9c92535d5
[ "Apache-2.0", "MIT" ]
null
null
null
src/util.rs
aschampion/heraclitus
ef89e91614e29afe29d4f4e7db43f3a9c92535d5
[ "Apache-2.0", "MIT" ]
null
null
null
src/util.rs
aschampion/heraclitus
ef89e91614e29afe29d4f4e7db43f3a9c92535d5
[ "Apache-2.0", "MIT" ]
null
null
null
pub mod petgraph { use heraclitus_core::petgraph; use petgraph::prelude::*; use petgraph::Direction; use petgraph::visit::{ Data, GraphBase, GraphRef, IntoEdgesDirected, IntoNeighborsDirected, Visitable, VisitMap, }; use crate::Error; /// Perform a topological sort of a node's induced stream in a directed graph. /// /// Based on petgraph's `toposort` function. Can not return petgraph cycle /// errors because they are private. pub fn induced_stream_toposort<G, F>( g: G, sources: &[<G as GraphBase>::NodeId], direction: Direction, edge_filter: F, ) -> Result<Vec<<G as GraphBase>::NodeId>, Error> where G: IntoEdgesDirected + IntoNeighborsDirected + Visitable, F: Fn(&<G as Data>::EdgeWeight) -> bool, { with_dfs(g, |dfs| { dfs.reset(g); let mut finished = g.visit_map(); let mut finish_stack = Vec::new(); for i in sources { if dfs.discovered.is_visited(i) { continue; } dfs.stack.push(*i); while let Some(&nx) = dfs.stack.last() { if dfs.discovered.visit(nx) { // First time visiting `nx`: Push neighbors, don't pop `nx` for succ in g.edges_directed(nx, direction) .filter_map(|edgeref| { if edge_filter(edgeref.weight()) { Some(match direction { Direction::Incoming => edgeref.source(), Direction::Outgoing => edgeref.target(), }) } else { None } }) { if succ == nx { // self cycle return Err(Error::TODO("cycle")); } if !dfs.discovered.is_visited(&succ) { dfs.stack.push(succ); } } } else { dfs.stack.pop(); if finished.visit(nx) { // Second time: All reachable nodes must have been finished finish_stack.push(nx); } } } } finish_stack.reverse(); // TODO: Doesn't work with induced stream because reverses whole // graph. Not needed for now anyway since all our graphs are known // to be DAGs. // dfs.reset(g); // for &i in &finish_stack { // dfs.move_to(i); // let mut cycle = false; // while let Some(j) = dfs.next(Reversed(g)) { // if cycle { // return Err(Error::TODO("cycle2")); // } // cycle = true; // } // } Ok(finish_stack) }) } /// Create a Dfs if it's needed fn with_dfs<G, F, R>( g: G, f: F ) -> R where G: GraphRef + Visitable, F: FnOnce(&mut Dfs<G::NodeId, G::Map>) -> R { let mut local_visitor = Dfs::empty(g); let dfs = &mut local_visitor; f(dfs) } }
34.877358
87
0.404111
f95c4cc8950b89f08b423c5b3afea812ffd9d968
394
dart
Dart
lib/simulator.dart
knowgoio/knowgo-vehicle-simulator
68265e5e0e78e99add11b517e2a649edf17dca07
[ "MIT" ]
19
2021-03-22T12:32:07.000Z
2022-03-16T00:00:51.000Z
lib/simulator.dart
knowgoio/knowgo-vehicle-simulator
68265e5e0e78e99add11b517e2a649edf17dca07
[ "MIT" ]
4
2021-05-23T14:59:08.000Z
2022-03-18T15:26:34.000Z
lib/simulator.dart
knowgoio/knowgo-vehicle-simulator
68265e5e0e78e99add11b517e2a649edf17dca07
[ "MIT" ]
2
2021-06-01T20:55:59.000Z
2021-12-03T15:50:01.000Z
export 'simulator/event_injector.dart'; export 'simulator/vehicle_data_calculators.dart'; export 'simulator/vehicle_data_generator.dart'; export 'simulator/vehicle_event_loop.dart'; export 'simulator/vehicle_exve_model.dart'; export 'simulator/vehicle_notifications.dart'; export 'simulator/vehicle_simulator_base.dart'; export 'simulator/vehicle_state.dart'; export 'simulator/webhooks.dart';
39.4
49
0.840102
c32fe9769ed24823f7db7ecf8f8177e0832582e7
522
swift
Swift
Bootcamp/Constants.swift
rjmendus/Infinity-Workshop-iOS
eeda575e7efaac849314443e2cb6a9b9e7124573
[ "MIT" ]
null
null
null
Bootcamp/Constants.swift
rjmendus/Infinity-Workshop-iOS
eeda575e7efaac849314443e2cb6a9b9e7124573
[ "MIT" ]
null
null
null
Bootcamp/Constants.swift
rjmendus/Infinity-Workshop-iOS
eeda575e7efaac849314443e2cb6a9b9e7124573
[ "MIT" ]
null
null
null
// // Constants.swift // Bootcamp // // Created by Rajat Jaic Mendus on 11/5/18. // Copyright © 2018 IODevelopers. All rights reserved. // import Foundation struct Constants { static let loginAPI = "https://9nfmj2dq1f.execute-api.ap-south-1.amazonaws.com/Development/login" static let viewOrderAPI = "https://9nfmj2dq1f.execute-api.ap-south-1.amazonaws.com/Development/orders/get-all" static let addOrderAPI = "https://9nfmj2dq1f.execute-api.ap-south-1.amazonaws.com/Development/orders/add-order" }
30.705882
115
0.733716
fd5ed79fdd2ca551ce6d3ec42723bdfba016c123
52,682
c
C
thirdparty/dill/dill/arm8.c
Carreau/ADIOS2
731e93f62bd1e25e88adcc8c44c055c41dcf4ee5
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
thirdparty/dill/dill/arm8.c
Carreau/ADIOS2
731e93f62bd1e25e88adcc8c44c055c41dcf4ee5
[ "ECL-2.0", "Apache-2.0" ]
4
2017-06-12T13:41:45.000Z
2017-12-13T17:01:40.000Z
thirdparty/dill/dill/arm8.c
Carreau/ADIOS2
731e93f62bd1e25e88adcc8c44c055c41dcf4ee5
[ "ECL-2.0", "Apache-2.0" ]
3
2017-08-16T17:06:04.000Z
2017-08-17T14:29:38.000Z
#include "dill.h" #include "dill_internal.h" #include "arm8.h" #include "config.h" #include <stdio.h> #ifdef HAVE_MALLOC_H #include <malloc.h> #endif #undef NDEBUG #include <assert.h> #include <stdlib.h> #include <string.h> #define INSN_OUT(s, insn) do {\ if (s->p->cur_ip >= s->p->code_limit) {\ extend_dill_stream(s);\ }\ *(int*)s->p->cur_ip = (unsigned int)insn;\ if (s->dill_debug) dump_cur_dill_insn(s);\ s->p->cur_ip = (void*)(((long)s->p->cur_ip)+4);\ } while (0)\ #define COND(x) ((unsigned)((x)&0xf) << 28) #define CLASS(x) (((x)&0x7) << 25) #define OPCODE(x) (((x)&0xf) << 21) /* opcode field */ #define p(x) (((x)&0x1) << 23) #define D(x) (((x)&0x1) << 22) #define q(x) (((x)&0x1) << 21) #define r(x) (((x)&0x1) << 20) #define S(x) (((x)&0x1) << 20) /* update cond codes? */ #define FN(x) (((x)&0xf) << 16) /* Fn field */ #define FD(x) (((x)&0xf) << 12) /* Fn field */ #define cp_num(x) (((x)&0xf) << 8) /* cpu */ #define N(x) (((x)&0x1) << 7) #define s(x) (((x)&0x1) << 6) #define M(x) (((x)&0x1) << 5) #define RN(x) (((x)&0xf) << 16) /* Rn field */ #define RD(x) (((x)&0xf) << 12) /* Rd field */ #define RM(x) (((x)&0xf) << 0) /* Rm field */ #define SHIFTI(x,t) ((((x)&0x1f) << 7) | ((t)&0x3)<<5) #define SHIFTR(r,t) ((((r)&0xf) << 8) | ((t)&0x3)<<5| 1<<4) #define IMM(x,r) (((x)&0xff) | ((((32-(r))>>1)&0xf)<< 8) | (1<<25)) /* simm8 field */ #define IM 0x2000 #define P(x) (((x)&0x1)<<19) #define arm8_savei(s, imm) arm8_dproci(s, SUB, 0, _sp, _sp, ar_size); #define arm8_andi(s, dest, src, imm) arm8_dproci(s, AND, 0, dest, src, imm) #define arm8_movi(s, dest, src) arm8_dproc(s, MOV, 0, dest, 0, src) #define arm8_movf(s, dest, src) arm8_fproc2(s, 0, 0, 0, dest, src) #define arm8_movd(s, dest, src) arm8_fproc2(s, 0, 1, 0, dest, src) #define arm8_lshi(s, dest, src,imm) arm8_dproci(s, MOV, LLshift, dest, src, imm) #define arm8_rshi(s,dest,src,imm) arm8_dproci(s, MOV, LRshift, dest, src, imm) #define arm8_rshai(s,dest,src,imm) arm8_dproci(s, MOV, ARshift, dest, src, imm) #define arm8_nop(s) arm8_movi(s, _r0, _r0) #define arm8_raw_push(s, reg) INSN_OUT(s, COND(AL)|CLASS(2)|1<<24|1<<21|0xd<<16|reg<<12|4) #define arm8_raw_pop(s, reg) INSN_OUT(s, COND(AL)|CLASS(2)|1<<23|1<<20|0xd<<16|reg<<12|4) #define IREG 0 #define FREG 1 #define roundup(a,b) ((a + (b-1)) & (-b)) static void arm8_pldsti(dill_stream s, int type, int ls, int dest, int src, long offset); static void arm8_pldst(dill_stream s, int type, int ls, int dest, int src1, int src2); static void int_arm8_bswap(dill_stream s, int type, int reg); extern void arm8_bswap(dill_stream s, int type, int data2, int dest, int src) { switch(type) { case DILL_L: case DILL_UL: case DILL_I: case DILL_U: INSN_OUT(s, COND(AL)| 0b011010111111<<16|RD(dest)|RM(src)|0xf<<8|3<<4); break; case DILL_US: case DILL_S: INSN_OUT(s, COND(AL)| 0b011010111111<<16|RD(dest)|RM(src)|0xf<<8|0xb<<4); break; case DILL_C: case DILL_UC: /* nothing to do */ break; case DILL_F: INSN_OUT(s, COND(AL)| CLASS(7)|OPCODE(0)|1<<20|FN(src>>1)|N(src)|RD(_r0)|cp_num(0xa)|1<<4);/*fmrs*/ int_arm8_bswap(s, DILL_L, _r0); INSN_OUT(s, COND(AL)| CLASS(7)|OPCODE(0)|0<<20|FN(dest>>1)|N(dest)|RD(_r0)|cp_num(0xa)|1<<4);/*fmsr*/ break; case DILL_D: INSN_OUT(s, COND(AL)| CLASS(6)|OPCODE(2)|r(1)|FN(_r1)|RD(_r0)|cp_num(0xb)|1<<4|(src>>1)|(src&1)<<5);/*fmrrd*/ int_arm8_bswap(s, DILL_L, _r0); int_arm8_bswap(s, DILL_L, _r1); INSN_OUT(s, COND(AL)| CLASS(6)|OPCODE(2)|FN(_r0)|RD(_r1)|cp_num(0xb)|1<<4|(dest>>1)|(dest&1)<<5);/*fmdrr*/ break; } } static void int_arm8_bswap(dill_stream s, int type, int reg) { arm8_bswap(s, type, 0, reg, reg); } extern void arm8_pbsloadi(dill_stream s, int type, int junk, int dest, int src, long offset) { arm8_pldsti(s, type, 1, dest, src, offset); int_arm8_bswap(s, type, dest); } extern void arm8_pbsload(dill_stream s, int type, int junk, int dest, int src1, int src2) { arm8_pldst(s, type, 1, dest, src1, src2); int_arm8_bswap(s, type, dest); } static struct basic_type_info { char size; char align; char reg_type; } type_info[] = { { 1, 1, IREG}, /* C */ { 1, 1, IREG}, /* UC */ { 2, 2, IREG}, /* S */ { 2, 2, IREG}, /* US */ { 4, 4, IREG}, /* I */ { 4, 4, IREG}, /* U */ { sizeof(long), sizeof(long), IREG}, /* UL */ { sizeof(long), sizeof(long), IREG}, /* L */ { sizeof(char*), sizeof(char*), IREG}, /* P */ { sizeof(float), sizeof(float), FREG}, /* F */ { sizeof(double), 4, FREG}, /* D */ { 0, 8, IREG}, /* V */ { -1, 8, IREG}, /* B */ { 4, 8, IREG}, /* EC */ }; int arm8_type_align[] = { 1, /* C */ 1, /* UC */ 2, /* S */ 2, /* US */ 4, /* I */ 4, /* U */ sizeof(unsigned long), /* UL */ sizeof(long), /* L */ sizeof(char*), /* P */ 4, /* F */ 4, /* D */ 1, /* V */ 4, /* B */ sizeof(long), /* EC */ }; int arm8_type_size[] = { 1, /* C */ 1, /* UC */ 2, /* S */ 2, /* US */ 4, /* I */ 4, /* U */ sizeof(unsigned long), /* UL */ sizeof(long), /* L */ sizeof(char*), /* P */ 4, /* F */ 8, /* D */ 1, /* V */ 8, /* B */ sizeof(char*), /* EC */ }; extern void arm8_dproc(s, op, shift_code, dest, src1, src2) dill_stream s; int op; int shift_code; int dest; int src1; int src2; { int shift = 0; if (shift_code != 0) { shift_code &= 0x3; shift = SHIFTR(src2, shift_code); src2 = src1; src1 = 0; } INSN_OUT(s, COND(AL)|CLASS(0x0)|OPCODE(op)|S(0)|RN(src1)|RD(dest)|RM(src2)|shift); } extern void arm8_dproc2(s, op, fop, dest, src) dill_stream s; int op; int fop; int dest; int src; { if (op == RSB) { arm8_dproci(s, RSB, 0, dest, src, 0); } else if (op == CMN) { /* !a */ INSN_OUT(s, COND(AL)|CLASS(0x0)|OPCODE(CMP)|S(1)|RN(src)|RD(src)|IMM(0,0)); INSN_OUT(s, COND(NE)|CLASS(0x0)|OPCODE(MOV)|S(0)|RN(0)|RD(dest)|IMM(0, 0)); INSN_OUT(s, COND(EQ)|CLASS(0x0)|OPCODE(MOV)|S(0)|RN(0)|RD(dest)|IMM(1, 0)); } else { INSN_OUT(s, COND(AL)|CLASS(0x0)|OPCODE(op)|S(0)|RN(src)|RD(dest)|RM(src)); } } extern void arm8_negf(s, op,fd, dest, src) dill_stream s; int op; int fd; int dest; int src; { arm8_fproc2(s, op, fd, 0, dest, src); } extern void arm8_fproc2(s, op,fd, n, dest, src) dill_stream s; int op; int fd; int n; int dest; int src; { INSN_OUT(s, COND(AL)|CLASS(0x7)|p(1)|D(dest&1)|q(1)|r(1)|FN(op)|N(n)|FD(dest>>1)|(0xa+fd)<<8|s(1)|M(src&1)|((src>>1)&0xf)); } extern int arm8_local(dill_stream s, int type) { arm8_mach_info ami = (arm8_mach_info) s->p->mach_info; ami->act_rec_size += roundup(type_info[type].size, ami->stack_align); return (-ami->act_rec_size) - 14 * 4 /* int regs to save */ - 8 * 3 * 4 /* float regs to save */; } extern int arm8_localb(dill_stream s, int size) { arm8_mach_info ami = (arm8_mach_info) s->p->mach_info; if (size < 0) size = 0; ami->act_rec_size = roundup(ami->act_rec_size, size); ami->act_rec_size += roundup(size, ami->stack_align); return (-ami->act_rec_size) - 14 * 4 /* int regs to save */ - 8 * 3 * 4 /* float regs to save */; } extern int arm8_local_op(dill_stream s, int flag, int val) { int size = val; if (flag == 0) { size = type_info[val].size; } if (size < 0) size = 0; return arm8_localb(s, size); } static int is_temp(int ireg) { return (ireg <= _r4); /* higher regs are saved by the callee */ } static int is_ftemp(int freg) { return (freg <= _f4); /* higher regs are saved by the callee */ } extern void arm8_save_restore_op(dill_stream s, int save_restore, int type, int reg) { arm8_mach_info ami = (arm8_mach_info) s->p->mach_info; if (save_restore == 0) { /* save */ switch (type) { case DILL_D: case DILL_F: if (is_ftemp(reg)) { arm8_pstorei(s, type, 0, reg, _fp, - 13*4 - reg * 12); } break; default: if (is_temp(reg)) { arm8_pstorei(s, type, 0, reg, _sp, ami->gp_save_offset + (reg - _r0) * ami->stack_align); } break; } } else { /* restore */ switch (type) { case DILL_D: case DILL_F: if (is_ftemp(reg)) { arm8_ploadi(s, type, 0, reg, _fp, -13*4 - reg * 12); } break; default: if (is_temp(reg)) { arm8_ploadi(s, type, 0, reg, _sp, ami->gp_save_offset + (reg - _r0) * ami->stack_align); } break; } } } static void arm8_movi2f(dill_stream s, int dest, int src) { arm8_mach_info ami = (arm8_mach_info) s->p->mach_info; arm8_pstorei(s, DILL_I, 0, src, _fp, ami->conversion_word); arm8_ploadi(s, DILL_F, 0, dest, _fp, ami->conversion_word); } static void arm8_movf2i(dill_stream s, int dest, int src) { arm8_mach_info ami = (arm8_mach_info) s->p->mach_info; arm8_pstorei(s, DILL_F, 0, src, _fp, ami->conversion_word); arm8_ploadi(s, DILL_I, 0, dest, _fp, ami->conversion_word); } static void arm8_movd2i(dill_stream s, int dest, int src) { arm8_mach_info ami = (arm8_mach_info) s->p->mach_info; arm8_pstorei(s, DILL_D, 0, src, _fp, ami->conversion_word); if (ami->stack_align == 8) { arm8_ploadi(s, DILL_L, 0, dest, _fp, ami->conversion_word); } else { arm8_ploadi(s, DILL_I, 0, dest, _fp, ami->conversion_word); arm8_ploadi(s, DILL_I, 0, dest+1, _fp, ami->conversion_word+4); } } static void arm8_movi2d(dill_stream s, int dest, int src) { arm8_mach_info ami = (arm8_mach_info) s->p->mach_info; if (ami->stack_align == 8) { arm8_pstorei(s, DILL_L, 0, src, _fp, ami->conversion_word); } else { arm8_pstorei(s, DILL_I, 0, src, _fp, ami->conversion_word); arm8_pstorei(s, DILL_I, 0, src+1, _fp, ami->conversion_word+4); } arm8_ploadi(s, DILL_D, 0, dest, _fp, ami->conversion_word); } extern void arm8_fproc(s, arm8_op, fd, dest, src1, src2) dill_stream s; int arm8_op; int fd; int dest; int src1; int src2; { INSN_OUT(s, COND(AL)|CLASS(0x7)|D(dest&0x1)|p(arm8_op>>3)|q(arm8_op>>2)|r(arm8_op>>1)|s(arm8_op)|(arm8_op&0x1)<<15|((src1>>1)&0xf)<<16|((dest>>1)&0xf)<<12|(0xa+(fd))<<8|(src1&1)<<7|(src2>>1)&0xf|(src2&0x1)<<5); } extern void arm8_dproci(s, op, shift_code, dest, src1, imm) dill_stream s; int op; int shift_code; int dest; int src1; long imm; { int shift = 0; int setcc = 0; if (op == CMP) setcc = 1; if (shift_code != 0) { /* must already be a mov op */ shift_code &= 0x3; shift = SHIFTI(imm, shift_code); INSN_OUT(s, COND(AL)|CLASS(0x0)|OPCODE(op)|S(0)|RN(src1)|RD(dest)|shift|RM(src1)); return; } if ((imm >= 0) && (imm < 256)) { /* arith format */ INSN_OUT(s, COND(AL)|CLASS(0x0)|OPCODE(op)|S(setcc)|RN(src1)|RD(dest)|IMM(imm, 0)); } else { arm8_set(s, _v1, imm); INSN_OUT(s, COND(AL)|CLASS(0x0)|OPCODE(op)|S(setcc)|RN(src1)|RD(dest)|RM(_v1)); } } /* * ARM stack frame organization * * pushed args * ------------ SP value at entry FP value * callee-saved int regs * pushed with stmdb space for 14 * callee-saved float regs space for 8 * * ------------ SP value after STMDB * local variables * ------------ final SP value */ extern void arm8_proc_start(dill_stream s, char *subr_name, int arg_count, arg_info_list args, dill_reg *arglist) { int i; arm8_mach_info ami = (arm8_mach_info) s->p->mach_info; int cur_arg_offset = 0; int next_core_register = _r0; int next_float_register = _f0; /* emit start insns */ INSN_OUT(s, 0xFF000000); INSN_OUT(s, 0xFF000000); INSN_OUT(s, 0xFF000000); arm8_movi(s, _r12, _sp); /* stmdb sp!, {r11, r12, lr, pc} */ INSN_OUT(s, COND(AL)|CLASS(4)|1<<24/*p*/|RN(_sp)|1<<_r11|1<<_r12|1<<_link|1<<_pc); arm8_dproci(s, SUB, 0, _sp, _sp, 14*4 ); /* instead of write back */ arm8_nop(s); /* placeholder for float save */ arm8_dproci(s, SUB, 0, _r11, _r12, 4); ami->save_insn_offset = (long)s->p->cur_ip - (long)s->p->code_base; arm8_nop(s); /* room for largest stack adjust insn, 5 nops */ arm8_nop(s); arm8_nop(s); arm8_nop(s); arm8_nop(s); ami->conversion_word = arm8_local(s, DILL_D); ami->conversion_word = arm8_local(s, DILL_D); ami->conversion_word = arm8_local(s, DILL_D); /* load params from regs */ for (i = 0; i < arg_count; i++) { int item_size = 1; switch (args[i].type) { case DILL_D: if (ami->hard_float) { if (next_float_register % 2) { /* double is only even regs, skip one */ next_float_register++; } } else { if (next_core_register % 2) { /* double is only even regs, skip one */ next_core_register++; cur_arg_offset += 4; } } item_size = 2; case DILL_F: /* falling through */ if (ami->hard_float) { if (next_float_register <= _f31) { args[i].is_register = 1; args[i].in_reg = next_float_register; args[i].out_reg = next_float_register; } else { args[i].is_register = 0; } next_float_register += ((args[i].type == DILL_D) ? 2 : 1); break; } /* if soft float, fall through, with item size at 2 for D */ default: if (next_core_register < _r4) { args[i].is_register = 1; args[i].in_reg = next_core_register; args[i].out_reg = next_core_register; } else { args[i].is_register = 0; } next_core_register+=item_size; break; } args[i].offset = cur_arg_offset; cur_arg_offset += roundup(type_info[(int)args[i].type].size, ami->stack_align); } for (i = 0; i < arg_count; i++) { int tmp_reg; // printf("Handling arg %d, is_reg %d\n", i, args[i].is_register); if (args[i].is_register) { /* only some moved into registers */ if (!dill_raw_getreg(s, &tmp_reg, args[i].type, DILL_VAR)) { /* not enough regs for this, store it to the stack */ int real_offset = - args[i].offset - 4*4; if (arglist != NULL) arglist[i] = -1; arm8_pstorei(s, DILL_I, 0, args[i].in_reg, _fp, real_offset); args[i].in_reg = -1; args[i].out_reg = -1; args[i].offset = real_offset; args[i].is_register = 0; continue; } if (args[i].is_register) { if ((args[i].type != DILL_F) && (args[i].type != DILL_D)) { arm8_movi(s, tmp_reg, args[i].in_reg); } else if (args[i].type == DILL_F) { /* must be float */ if (ami->hard_float) { arm8_movf(s, tmp_reg, args[i].in_reg); } else { int src = args[i].in_reg; int dest = tmp_reg; INSN_OUT(s, COND(AL)| CLASS(7)|OPCODE(0)|0<<20|FN(dest>>1)|N(dest)|RD(src)|cp_num(0xa)|1<<4);/*fmsr*/ } } else { if (ami->hard_float) { arm8_movd(s, tmp_reg, args[i].in_reg); } else { INSN_OUT(s, COND(AL)| CLASS(6)|OPCODE(2)|FN(args[i].in_reg+1)|RD(args[i].in_reg)|cp_num(0xb)|1<<4|(tmp_reg>>1)|(tmp_reg&1)<<5);/*fmdrr*/ } } } else { /* general offset from fp*/ int real_offset = args[i].offset - 3*4; arm8_ploadi(s, args[i].type, 0, tmp_reg, _fp, real_offset); } if (arglist != NULL) arglist[i] = tmp_reg; args[i].in_reg = tmp_reg; args[i].is_register = 1; } else { if (!ami->hard_float && ((args[i].type == DILL_F) || (args[i].type == DILL_D))) { int tmp_reg; dill_raw_getreg(s, &tmp_reg, args[i].type, DILL_VAR); /* general offset from fp*/ int real_offset = args[i].offset - 3*4; arm8_ploadi(s, args[i].type, 0, tmp_reg, _fp, real_offset); if (arglist != NULL) arglist[i] = tmp_reg; args[i].in_reg = tmp_reg; args[i].is_register = 1; } else { /* leave it on the stack */ int real_offset = args[i].offset - 3*4; if (arglist != NULL) arglist[i] = -1; args[i].in_reg = -1; args[i].out_reg = -1; args[i].offset = real_offset; } } } } extern void arm8_ploadi(dill_stream s, int type, int junk, int dest, int src, long offset) { arm8_pldsti(s, type, 1, dest, src, offset); } extern void arm8_pload(dill_stream s, int type, int junk, int dest, int src1, int src2) { arm8_pldst(s, type, 1, dest, src1, src2); } /* byte and whole word version */ #define ARM8_LDSTI(s,u,b,ls,rn,rd,offset) INSN_OUT(s, COND(AL)|CLASS(2)|(1<<24)|((u&1)<<23)|((b&1)<<22)|(ls&1)<<20|RN(rn)|RD(rd)|(0x7ff&offset)) /* halfword version */ #define ARM8_LDSTHI(s,u,ls,rn,rd,sh,offset) INSN_OUT(s, COND(AL)|CLASS(0)|(1<<24)|((u&1)<<23)|(1<<22)|(ls&1)<<20|RN(rn)|RD(rd)|(1<<7)|((sh&0x3)<<5)|(1<<4)|(0xf&offset)|((offset&0xf0)<<4)) /* float version */ #define ARM8_LDSTFI(s,u,fd,ls,rn,rd,offset) INSN_OUT(s, COND(AL)|CLASS(6)|(1<<24)|((u&1)<<23)|(ls&1)<<20|RN(rn)|D(rd&1)|RD(rd>>1)|((0xa+(fd))<<8)|(0xff&(offset>>2))) extern void arm8_pstorei(dill_stream s, int type, int junk, int dest, int src, long offset) { arm8_pldsti(s, type, 0, dest, src, offset); } static void arm8_pldsti(dill_stream s, int type, int ls, int dest, int src, long offset) { int u = 1; int max_offset; switch (type) { case DILL_S: case DILL_US: case DILL_D: case DILL_F: max_offset = 256; break; default: max_offset = 2048; break; } if (((long)offset) >= max_offset || ((long)offset) < -max_offset) { arm8_set(s, _v1, offset); arm8_pldst(s, type, ls, dest, src, _v1); return; } if (offset < 0) { u = 0; offset = -offset; } switch (type) { case DILL_F: ARM8_LDSTFI(s, u, 0, ls, src, dest, offset); break; case DILL_D: ARM8_LDSTFI(s, u, 1, ls, src, dest, offset); break; case DILL_C: case DILL_UC: ARM8_LDSTI(s, u, 1, ls, src, dest, offset); break; case DILL_I: case DILL_U: case DILL_L: case DILL_UL: case DILL_P: ARM8_LDSTI(s, u, 0, ls, src, dest, offset); break; case DILL_S: if (ls == 1) { /* this is a load */ ARM8_LDSTHI(s,u,ls,src,dest,0x3,offset); break; } /* fall through */ case DILL_US: ARM8_LDSTHI(s,u,ls,src,dest,0x1,offset); break; default: break; } } #define ARM8_LDST(s,u,b,ls,rn,rd,rm) INSN_OUT(s, COND(AL)|CLASS(3)|(1<<24)|((u&1)<<23)|((b&1)<<22)|(ls&1)<<20|RN(rn)|RD(rd)|(0xf&rm)) #define ARM8_LDSTH(s,u,ls,rn,rd,sh,rm) INSN_OUT(s, COND(AL)|CLASS(0)|(1<<24)|((u&1)<<23)|(ls&1)<<20|RN(rn)|RD(rd)|(1<<7)|((sh&0x3)<<5)|(1<<4)|(0xf&rm)) extern void arm8_pstore(dill_stream s, int type, int junk, int dest, int src1, int src2) { arm8_pldst(s, type, 0, dest, src1, src2); } static void arm8_pldst(dill_stream s, int type, int ls, int dest, int src1, int src2) { switch (type) { case DILL_F: arm8_dproc(s, ADD, 0, _v1, src1, src2); ARM8_LDSTFI(s, 0, 0, ls, _v1, dest, 0); break; case DILL_D: arm8_dproc(s, ADD, 0, _v1, src1, src2); ARM8_LDSTFI(s, 0, 1, ls, _v1, dest, 0); break; case DILL_L: case DILL_UL: case DILL_P: case DILL_I: case DILL_U: case DILL_EC: ARM8_LDST(s,1,0,ls,src1,dest,src2); break; case DILL_S: if (ls == 1) { /* this is a load */ ARM8_LDSTH(s,1,ls,src1,dest,0x3,src2); break; } /* fall through */ case DILL_US: ARM8_LDSTH(s,1,ls,src1,dest,0x1,src2); break; case DILL_C: case DILL_UC: ARM8_LDST(s,1,1,ls,src1,dest,src2); break; default: break; } } extern int arm8_hidden_modi(int a, int b); extern long arm8_hidden_mod(long a, long b); extern unsigned long arm8_hidden_umod(unsigned long a, unsigned long b); extern unsigned int arm8_hidden_umodi(unsigned int a, unsigned int b); extern double arm8_hidden_ultod(unsigned long a); extern float arm8_hidden_ultof(unsigned long a); extern unsigned long arm8_hidden_dtoul(double a); extern unsigned int arm8_hidden_dtou(double a); extern unsigned long arm8_hidden_ftoul(float a); extern unsigned int arm8_hidden_ftou(float a); extern unsigned long arm8_hidden_udiv(unsigned long a, unsigned long b); extern long arm8_hidden_div(long a, long b); #define FIX_SRC2_POSTFIX \ if (tmp_src2 != -1) {\ arm8_raw_pop(s, tmp_src2);\ } #define FIX_SRC2_PREFIX \ int tmp_src2 = -1;\ /* \ * DILL lets us use ret_reg in operators in some circumstances, so src1 \ * or src2 might be ret_reg. This is a problem if it's src2 and we do \ * a call.\ */\ if (src2 == _a1) {\ tmp_src2 = _a4; /* arbitrary */\ if (src1 == tmp_src2) tmp_src2 = _a3;\ arm8_raw_push(s, tmp_src2);\ dill_movl(s, tmp_src2, _a1);\ src2 = tmp_src2;\ } extern void arm8_mod(dill_stream s, int sign, int type_long, int dest, int src1, int src2) { int return_reg; FIX_SRC2_PREFIX; if (sign == 1) { /* signed case */ if (type_long) { return_reg = dill_scalll(s, (void*)arm8_hidden_mod, "arm8_hidden_mod", "%l%l", src1, src2); dill_movl(s, dest, return_reg); } else { return_reg = dill_scalli(s, (void*)arm8_hidden_modi, "arm8_hidden_modi", "%i%i", src1, src2); dill_movi(s, dest, return_reg); } } else { /* unsigned case */ if (type_long) { return_reg = dill_scalll(s, (void*)arm8_hidden_umod, "arm8_hidden_umod", "%l%l", src1, src2); dill_movul(s, dest, return_reg); } else { return_reg = dill_scallu(s, (void*)arm8_hidden_umodi, "arm8_hidden_umodi", "%u%u", src1, src2); dill_movu(s, dest, return_reg); } } FIX_SRC2_POSTFIX; } extern void arm8_modi(dill_stream s, int data1, int data2, int dest, int src1, long imm) { arm8_set(s, _v1, imm); arm8_mod(s, data1, data2, dest, src1, _v1); } extern void arm8_div(dill_stream s, int unsign, int junk, int dest, int src1, int src2) { int return_reg; void *routine = (void*) &arm8_hidden_div; if (unsign) routine = (void*) &arm8_hidden_udiv; FIX_SRC2_PREFIX; return_reg = dill_scalll(s, routine, "routine", "%l%l", src1, src2); FIX_SRC2_POSTFIX; dill_movl(s, dest, return_reg); } #define MUL(s,A,S,Rd,Rs,Rm) INSN_OUT(s, COND(AL)|(A&1)<<21|(S&1)<<20|RN(Rd)|RD(0)|(Rs&0xf)<<8|0x90|(Rm&0xf)) extern void arm8_mul(dill_stream s, int unsign, int junk, int dest, int src1, int src2) { MUL(s, 0, 0, dest, src1, src2); } extern void arm8_muli(dill_stream s, int unsign, int junk, int dest, int src, long imm) { arm8_set(s, _v1, imm); MUL(s, 0, 0, dest, src, _v1); } extern void arm8_divi(dill_stream s, int unsign, int junk, int dest, int src, long imm) { arm8_set(s, _v1, imm); arm8_div(s, unsign, junk, dest, src, _v1); } extern void arm8_mov(dill_stream s, int type, int junk, int dest, int src) { if (src == dest) return; switch(type) { case DILL_D: arm8_movd(s, dest, src); break; case DILL_F: arm8_movf(s, dest, src); break; default: arm8_movi(s, dest, src); } } static void arm8_saverestore_floats(dill_stream s, int saverestore) { int i; for (i=1; i <8; i++) { if (dill_mustsave(&s->p->tmp_f, i)) { arm8_save_restore_op(s, saverestore, DILL_D, i); } } } #define CONV(x,y) ((x*100)+y) extern void arm8_convert(dill_stream s, int from_type, int to_type, int dest, int src) { from_type &= 0xf; to_type &= 0xf; switch(CONV(from_type, to_type)) { case CONV(DILL_I, DILL_L): case CONV(DILL_I, DILL_U): case CONV(DILL_I,DILL_UL): case CONV(DILL_UL,DILL_I): case CONV(DILL_UL,DILL_U): case CONV(DILL_L,DILL_U): case CONV(DILL_U,DILL_UL): case CONV(DILL_U,DILL_L): case CONV(DILL_L,DILL_I): case CONV(DILL_UL,DILL_L): case CONV(DILL_L,DILL_UL): case CONV(DILL_P,DILL_UL): case CONV(DILL_UL,DILL_P): case CONV(DILL_U,DILL_I): if(src == dest) return; arm8_movi(s, dest,src); break; case CONV(DILL_F,DILL_D): arm8_fproc2(s, 0b0111, 0, 1, dest, src); /* fcvtds */ break; case CONV(DILL_F,DILL_L): case CONV(DILL_F,DILL_I): case CONV(DILL_F,DILL_S): case CONV(DILL_F,DILL_C): arm8_fproc2(s, 0b1101, 0, 1, src, src); /* ftosis */ INSN_OUT(s, COND(AL)| CLASS(7)|OPCODE(0)|1<<20|FN(src>>1)|N(src)|RD(dest)|cp_num(0xa)|1<<4);/*fmrs*/ break; case CONV(DILL_F,DILL_U): case CONV(DILL_F,DILL_US): case CONV(DILL_F,DILL_UC): { int ret; arm8_saverestore_floats(s, 0); ret = dill_scallu(s, (void*)arm8_hidden_ftou, "arm8_hidden_ftou", "%f", src); arm8_saverestore_floats(s, 1); arm8_mov(s, DILL_UL, 0, dest, ret); } break; /* fallthrough */ case CONV(DILL_F,DILL_UL): { int ret; arm8_saverestore_floats(s, 0); ret = dill_scallul(s, (void*)arm8_hidden_ftoul, "arm8_hidden_ftoul", "%f", src); arm8_saverestore_floats(s, 1); arm8_mov(s, DILL_UL, 0, dest, ret); } break; case CONV(DILL_D,DILL_F): arm8_fproc2(s, 0b0111, 1, 1, dest, src); /* fcvtds */ break; case CONV(DILL_D,DILL_L): case CONV(DILL_D,DILL_I): case CONV(DILL_D,DILL_S): case CONV(DILL_D,DILL_C): arm8_fproc2(s, 0b1101, 1, 1, src, src); /* ftosid */ INSN_OUT(s, COND(AL)| CLASS(7)|OPCODE(0)|1<<20|FN(src>>1)|N(src)|RD(dest)|cp_num(0xa)|1<<4);/*fmsr*/ break; case CONV(DILL_D,DILL_U): case CONV(DILL_D,DILL_US): case CONV(DILL_D,DILL_UC): { int ret; arm8_saverestore_floats(s, 0); ret = dill_scallu(s, (void*)arm8_hidden_dtou, "arm8_hidden_dtou", "%d", src); arm8_saverestore_floats(s, 1); arm8_mov(s, DILL_U, 0, dest, ret); } break; case CONV(DILL_D,DILL_UL): { int ret; arm8_saverestore_floats(s, 0); ret = dill_scallul(s, (void*)arm8_hidden_dtoul, "arm8_hidden_dtoul", "%d", src); arm8_saverestore_floats(s, 1); arm8_mov(s, DILL_UL, 0, dest, ret); } break; case CONV(DILL_I,DILL_D): case CONV(DILL_L,DILL_D): case CONV(DILL_C,DILL_D): case CONV(DILL_S,DILL_D): INSN_OUT(s, COND(AL)| CLASS(7)|OPCODE(0)|0<<20|FN(dest>>1)|N(dest)|RD(src)|cp_num(0xa)|1<<4);/*fmsr*/ arm8_fproc2(s, 0x8, 1, 1, dest, dest); /* fsitod */ break; case CONV(DILL_U,DILL_D): case CONV(DILL_UL,DILL_D): case CONV(DILL_UC,DILL_D): case CONV(DILL_US,DILL_D): { int ret; arm8_saverestore_floats(s, 0); ret = dill_scalld(s, (void*)arm8_hidden_ultod, "arm8_hidden_ultod", "%l", src); arm8_saverestore_floats(s, 1); arm8_mov(s, DILL_D, 0, dest, ret); } break; case CONV(DILL_I,DILL_F): case CONV(DILL_L,DILL_F): case CONV(DILL_C,DILL_F): case CONV(DILL_S,DILL_F): INSN_OUT(s, COND(AL)| CLASS(7)|OPCODE(0)|0<<20|FN(dest>>1)|N(dest)|RD(src)|cp_num(0xa)|1<<4);/*fmsr*/ arm8_fproc2(s, 0x8, 0, 1, dest, dest); /* fsitos */ break; case CONV(DILL_U,DILL_F): case CONV(DILL_UL,DILL_F): case CONV(DILL_UC,DILL_F): case CONV(DILL_US,DILL_F): { int ret; arm8_saverestore_floats(s, 0); ret = dill_scallf(s, (void*)arm8_hidden_ultof, "arm8_hidden_ultof", "%l", src); arm8_saverestore_floats(s, 1); arm8_mov(s, DILL_D, 0, dest, ret); } break; case CONV(DILL_C,DILL_UL): case CONV(DILL_C,DILL_L): case CONV(DILL_C,DILL_I): case CONV(DILL_C,DILL_U): case CONV(DILL_C, DILL_S): case CONV(DILL_S, DILL_C): case CONV(DILL_US, DILL_C): arm8_lshi(s, dest, src, 24); arm8_rshai(s, dest, dest, 24); break; case CONV(DILL_I, DILL_C): case CONV(DILL_U, DILL_C): case CONV(DILL_L, DILL_C): case CONV(DILL_UL, DILL_C): case CONV(DILL_C, DILL_UC): case CONV(DILL_I, DILL_UC): case CONV(DILL_S, DILL_UC): case CONV(DILL_U, DILL_UC): case CONV(DILL_L, DILL_UC): case CONV(DILL_UL, DILL_UC): case CONV(DILL_US, DILL_UC): arm8_andi(s, dest, src, 0xff); break; case CONV(DILL_S,DILL_L): case CONV(DILL_S,DILL_UL): case CONV(DILL_S,DILL_I): case CONV(DILL_S,DILL_U): case CONV(DILL_S,DILL_US): case CONV(DILL_US,DILL_S): arm8_lshi(s, dest, src, 16); arm8_rshai(s, dest, dest, 16); break; case CONV(DILL_C, DILL_US): /* signext24 - lsh24, rsha24, trunc 16 */ arm8_lshi(s, dest, src, 24); arm8_rshai(s, dest, dest, 24); arm8_andi(s, dest, dest, 0xffff); break; case CONV(DILL_US,DILL_I): case CONV(DILL_US,DILL_L): case CONV(DILL_US,DILL_U): case CONV(DILL_US,DILL_UL): case CONV(DILL_I,DILL_S): case CONV(DILL_U,DILL_S): case CONV(DILL_L,DILL_S): case CONV(DILL_UL,DILL_S): case CONV(DILL_I,DILL_US): case CONV(DILL_U,DILL_US): case CONV(DILL_L,DILL_US): case CONV(DILL_UL,DILL_US): arm8_lshi(s, dest, src, 16); arm8_rshi(s, dest, dest, 16); break; default: printf("Unknown case in arm convert %d\n", CONV(from_type,to_type)); } } static signed char op_conds[] = { EQ, /* dill_beq_code */ /* signed */ GE, /* dill_bge_code */ GT, /* dill_bgt_code */ LE, /* dill_ble_code */ LT, /* dill_blt_code */ NE, /* dill_bne_code */ EQ, /* dill_beq_code */ /* unsigned */ CS, /* dill_bge_code */ HI, /* dill_bgt_code */ LS, /* dill_ble_code */ CC, /* dill_blt_code */ NE, /* dill_bne_code */ }; #define CMF 0x4 extern void arm8_branch(dill_stream s, int op, int type, int src1, int src2, int label) { switch(type) { case DILL_D: case DILL_F: arm8_fproc2(s, 0b0100, (type == DILL_D), 0, src1, src2); /* fcmps */ INSN_OUT(s, COND(AL)|0b111011110001<<16|0b1111101000010000); /* fmstat */ dill_mark_branch_location(s, label); INSN_OUT(s, COND(op_conds[op])|CLASS(0x5)|/*disp */0);/* b*/ break; break; case DILL_U: case DILL_UL: op += 6; /* second set of codes */ /* fall through */ default: INSN_OUT(s, COND(AL)|CLASS(0x0)|OPCODE(CMP)|S(1)|RN(src1)|RD(0)|RM(src2)); dill_mark_branch_location(s, label); INSN_OUT(s, COND(op_conds[op])|CLASS(0x5)|/*disp */0);/* b*/ } /* arm8_nop(s);*/ } extern void arm8_compare(dill_stream s, int op, int type, int dest, int src1, int src2) { int setcc = 0; if (op == CMP) setcc = 1; arm8_set(s, dest, 0); switch(type) { case DILL_D: case DILL_F: arm8_fproc2(s, 0b0100, (type == DILL_D), 0, src1, src2); /* fcmps */ INSN_OUT(s, COND(AL)|0b111011110001<<16|0b1111101000010000); /* fmstat */ INSN_OUT(s, COND(op_conds[op])|CLASS(0x0)|OPCODE(MOV)|S(setcc)|RN(src1)|RD(dest)|IMM(1, 0)); break; case DILL_U: case DILL_UL: op += 6; /* second set of codes */ /* fall through */ default: INSN_OUT(s, COND(AL)|CLASS(0x0)|OPCODE(CMP)|S(1)|RN(src1)|RD(0)|RM(src2)); INSN_OUT(s, COND(op_conds[op])|CLASS(0x0)|OPCODE(MOV)|S(setcc)|RD(dest)|IMM(1, 0)); } /* arm8_nop(s);*/ } extern void arm8_jal(dill_stream s, int return_addr_reg, int target) { } extern void arm8_jump_to_label(dill_stream s, unsigned long label) { dill_mark_branch_location(s, label); INSN_OUT(s, COND(AL)|CLASS(5)|(1<<24)/*link*/); } extern void arm8_jump_to_reg(dill_stream s, unsigned long reg) { arm8_dproc(s, MOV, 0, _link, _pc, _pc); arm8_dproc(s, MOV, 0, _pc, reg, reg); } extern void arm8_jump_to_imm(dill_stream s, void * imm) { } static void internal_push(dill_stream s, int type, int immediate, void *value_ptr) { arm8_mach_info ami = (arm8_mach_info) s->p->mach_info; struct arg_info arg; int real_offset; arg.is_immediate = immediate; switch(type) { case DILL_C: case DILL_S: case DILL_I: case DILL_L: arg.type = DILL_L; break; case DILL_UC: case DILL_US: case DILL_U: case DILL_UL: arg.type = DILL_UL; break; default: arg.type = type; } switch(arg.type) { case DILL_C: case DILL_S: case DILL_I: case DILL_L: case DILL_UC: case DILL_US: case DILL_U: case DILL_UL: case DILL_P: if (ami->next_core_register < _r4) { arg.is_register = 1; arg.in_reg = ami->next_core_register; arg.out_reg = ami->next_core_register; ami->next_core_register++; } else { arg.is_register = 0; } break; case DILL_D: if (ami->varidiac_call || (ami->hard_float == 0)) { if (ami->next_core_register % 2) { /* double is only even regs, skip one */ ami->next_core_register++; ami->cur_arg_offset += 4; } } else { if (ami->next_float_register % 2) { /* double is only even regs, skip one */ ami->next_float_register++; ami->cur_arg_offset += 4; } } /* falling through */ case DILL_F: if (ami->varidiac_call || (ami->hard_float == 0)) { if (ami->next_core_register < _r4) { arg.is_register = 1; arg.in_reg = ami->next_core_register; arg.out_reg = ami->next_core_register; ami->next_core_register++; if (arg.type == DILL_D) ami->next_core_register++;/* two, or split */ } else { arg.is_register = 0; } } else { if (ami->next_float_register < _f16) { arg.is_register = 1; arg.in_reg = ami->next_float_register; arg.out_reg = ami->next_float_register; ami->next_float_register++; } else { arg.is_register = 0; } } break; default: assert(0); } arg.offset = ami->cur_arg_offset; ami->cur_arg_offset += roundup(type_info[(int)arg.type].size, ami->stack_align); real_offset = arg.offset - 4*4; /* first 16 bytes in regs */ if (ami->cur_arg_offset > ami->max_arg_size) { ami->max_arg_size = ami->cur_arg_offset; } if (arg.is_register == 0) { /* store it on the stack only */ if (arg.is_immediate) { if (type != DILL_D) { if (type == DILL_F) { union { float f; int i; } u; u.f = (float) *(double*)value_ptr; arm8_set(s, _v1, u.i); } else { arm8_set(s, _v1, *(long*)value_ptr); } arm8_pstorei(s, arg.type, 0, _v1, _sp, real_offset); } else { arm8_set(s, _v1, *(int*)value_ptr); arm8_pstorei(s, DILL_I, 0, _v1, _sp, real_offset); arm8_set(s, _v1, *(((int*)value_ptr)+1)); arm8_pstorei(s, DILL_I, 0, _v1, _sp, real_offset+4); } } else { arm8_pstorei(s, arg.type, 0, *(int*)value_ptr, _sp, real_offset); } } else { if ((type != DILL_F) && (type != DILL_D)) { if (arg.is_immediate) { arm8_set(s, arg.out_reg, *(long*)value_ptr); } else { arm8_mov(s, type, 0, arg.out_reg, *(int*) value_ptr); } } else { if (ami->varidiac_call || (ami->hard_float == 0)) { union { float f; int i; } a; union { double d; long l; int i[2]; } b; arm8_mach_info ami = (arm8_mach_info) s->p->mach_info; if (arg.is_immediate) { if (type == DILL_F) { a.f = *(double*)value_ptr; arm8_set(s, arg.out_reg, a.i); } else { b.d = *(double*)value_ptr; arm8_set(s, arg.out_reg, b.i[0]); arm8_set(s, arg.out_reg+1, b.i[1]); } } else { switch(type) { case DILL_D: INSN_OUT(s, COND(AL)| 0b11000101<<20|FN(arg.out_reg+1)|RD(arg.out_reg)|cp_num(0xb)|1<<4|(*(int*)value_ptr)>>1);/*fmsrrd*/ break; case DILL_F: INSN_OUT(s, COND(AL)| CLASS(7)|OPCODE(0)|1<<20|FN(*(int*)value_ptr>>1)|N(*(int*)value_ptr)|RD(arg.out_reg)|cp_num(0xa)|1<<4);/*fmrs*/ arm8_movf(s, arg.out_reg, *(int*)value_ptr); break; default: assert(0); } } } else { if (arg.is_immediate) { arm8_setf(s, type, 0, arg.out_reg, *(double*)value_ptr); } else { switch(type) { case DILL_D: arm8_movd(s, arg.out_reg, *(int*)value_ptr); break; case DILL_F: arm8_movf(s, arg.out_reg, *(int*)value_ptr); break; default: assert(0); } } } } } } static void push_init(dill_stream s) { arm8_mach_info ami = (arm8_mach_info) s->p->mach_info; ami->cur_arg_offset = 0; ami->next_core_register = _r0; ami->next_float_register = _f0; ami->varidiac_call = 0; } extern void arm8_push(dill_stream s, int type, int reg) { arm8_mach_info ami = (arm8_mach_info) s->p->mach_info; if ((type == DILL_V) && (reg <= -1)) { push_init(s); if (reg <= -2) { ami->varidiac_call = 1; } } else { internal_push(s, type, 0, &reg); } } extern void arm8_pushi(dill_stream s, int type, long value) { internal_push(s, type, 1, &value); } extern void arm8_pushfi(dill_stream s, int type, double value) { internal_push(s, type, 1, &value); } extern void arm8_pushpi(dill_stream s, int type, void *value) { internal_push(s, type, 1, &value); } extern int arm8_calli(dill_stream s, int type, void *xfer_address, const char *name) { arm8_mach_info ami = (arm8_mach_info) s->p->mach_info; int caller_side_ret_reg = _a1; (void) name; /* save temporary registers */ #ifdef HOST_ARM8 dill_mark_call_location(s, name, xfer_address); INSN_OUT(s, COND(AL)|CLASS(5)|(1<<24)/*link*/); #else /* killing r12 here */ arm8_set(s, _r12, (long) xfer_address); /* blx (register) */ INSN_OUT(s, 0xe12fff30|RM(_r12)); #endif /* restore temporary registers */ if ((type == DILL_D) || (type == DILL_F)) { if (ami->hard_float == 0) { /* move _r0 to _f0 */ if (type == DILL_F) { int src = _r0; int dest = _f0; INSN_OUT(s, COND(AL)| CLASS(7)|OPCODE(0)|0<<20|FN(dest>>1)|N(dest)|RD(src)|cp_num(0xa)|1<<4);/*fmsr*/ } else { INSN_OUT(s, COND(AL)| CLASS(6)|OPCODE(2)|FN(_r1)|RD(_r0)|cp_num(0xb)|1<<4|(_f0>>1)|(_f0&1)<<5);/*fmdrr*/ } } caller_side_ret_reg = _f0; } push_init(s); return caller_side_ret_reg; } extern int arm8_callr(dill_stream s, int type, int src) { int caller_side_ret_reg = _a1; arm8_dproc(s, MOV, 0, _link, _pc, _pc); arm8_dproc(s, MOV, 0, _pc, src, src); /* restore temporary registers */ if ((type == DILL_D) || (type == DILL_F)) { caller_side_ret_reg = _f0; } push_init(s); return caller_side_ret_reg; } extern void arm8_branchi(dill_stream s, int op, int type, int src, long imm, int label) { switch(type) { case DILL_F: case DILL_D: fprintf(stderr, "Shouldn't happen\n"); break; case DILL_U: case DILL_UL: op += 6; /* second set of codes */ /* fall through */ default: arm8_dproci(s, CMP, 0, 0/*dest*/, src, imm); dill_mark_branch_location(s, label); INSN_OUT(s, COND(op_conds[op])|CLASS(0x5)|/*disp */0);/* b*/ } } extern void arm8_comparei(dill_stream s, int op, int type, int dest, int src, long imm) { int setcc = 0; if (op == CMP) setcc = 1; arm8_set(s, dest, 0); switch(type) { case DILL_F: case DILL_D: fprintf(stderr, "Shouldn't happen\n"); break; case DILL_U: case DILL_UL: op += 6; /* second set of codes */ /* fall through */ default: arm8_dproci(s, CMP, 0, 0/*dest*/, src, imm); INSN_OUT(s, COND(op_conds[op])|CLASS(0x0)|OPCODE(MOV)|S(setcc)|RD(dest)|IMM(1, 0)); } } static void arm8_simple_ret(dill_stream s) { dill_mark_ret_location(s); INSN_OUT(s, COND(AL)|CLASS(4)|1<<24/*p*/|1<<20/*l*/|RN(_r11)|1<<_r11|1<<_sp|1<<_pc); arm8_nop(s); /* ldmea may slide back here if we have to restore floats */ arm8_nop(s); arm8_nop(s); arm8_nop(s); arm8_nop(s); arm8_nop(s); arm8_nop(s); } extern void arm8_ret(dill_stream s, int data1, int data2, int src) { arm8_mach_info ami = (arm8_mach_info) s->p->mach_info; switch (data1) { case DILL_C: case DILL_UC: case DILL_S: case DILL_US: case DILL_I: case DILL_U: case DILL_L: case DILL_UL: case DILL_P: if (src != _a1) arm8_movi(s, _a1, src); break; case DILL_F: if (ami->hard_float) { if (src != _f0) arm8_movf(s, _f0, src); } else { INSN_OUT(s, COND(AL)| CLASS(7)|OPCODE(0)|1<<20|FN(src>>1)|N(src)|RD(_r0)|cp_num(0xa)|1<<4);/*fmrs*/ } break; case DILL_D: if (ami->hard_float) { if (src != _f0) arm8_movd(s, _f0, src); } else { INSN_OUT(s, COND(AL)| CLASS(6)|OPCODE(2)|r(1)|FN(_r1)|RD(_r0)|cp_num(0xb)|1<<4|(src>>1)|(src&1)<<5);/*fmrrd*/ } break; } arm8_simple_ret(s); } extern void arm8_retf(dill_stream s, int data1, int data2, double imm) { union { float f; int i; } a; union { double d; int i[2]; long l; } b; switch(data1) { case DILL_F: a.f = imm; arm8_set(s, _r0, a.i); INSN_OUT(s, COND(AL)| CLASS(7)|OPCODE(0)|0<<20|FN(_f0>>1)|N(_f0)|RD(_r0)|cp_num(0xa)|1<<4);/*fmsr*/ break; case DILL_D: b.d = imm; arm8_set(s, _r0, b.i[0]); arm8_set(s, _r1, b.i[1]); INSN_OUT(s, COND(AL)| CLASS(7)|OPCODE(0)|0<<20|FN(_f0>>1)|N(_f0)|RD(_r0)|cp_num(0xa)|1<<4);/*fmsr*/ break; } } extern void arm8_reti(dill_stream s, int data1, int data2, long imm) { switch (data1) { case DILL_C: case DILL_UC: case DILL_S: case DILL_US: case DILL_I: case DILL_U: case DILL_L: case DILL_UL: case DILL_P: arm8_set(s, _a1, imm); break; case DILL_F: case DILL_D: break;/* no return immediate of floats */ } arm8_simple_ret(s); } static void arm8_data_link(dill_stream s) { /* struct branch_table *t = &s->p->branch_table; int i; for (i=0; i < t->data_mark_count; i++) { int label = t->data_marks[i].label; void *label_addr = t->label_locs[label] + (char*)s->p->code_base; *t->data_marks[i].addr = (long) label_addr; }*/ } static void arm8_branch_link(dill_stream s) { struct branch_table *t = &s->p->branch_table; int i; for(i=0; i< t->branch_count; i++) { int label = t->branch_locs[i].label; int label_offset = t->label_locs[label] - t->branch_locs[i].loc; int *branch_addr = (int*)((char *)s->p->code_base + t->branch_locs[i].loc); /* compensate for arm PC lookahead */ label_offset = label_offset - 8; /* div addr diff by 4 for arm offset value */ label_offset = label_offset >> 2; *branch_addr &= 0xff000000; *branch_addr |= (label_offset & 0xffffff); } } /* * on ARM, we need a procedure linkage table to manage * calls to DLLs in an address range that is typically more than 26 bits * away from malloc'd memory. We emit a PLT that is basically a set_reg, * then jump_through_reg for each routine. Later, during call linkage, * we'll call to the PLT entry rather than directly to the routine. * If creating a package, emit a PLT entry for every routine because we * don't know what the offsets will be when the code is stitched together. */ extern void arm8_PLT_emit(dill_stream s, int package) { call_t *t = &s->p->call_table; int i; for(i=0; i< t->call_count; i++) { int *call_addr = (int*) ((unsigned long)s->p->code_base + t->call_locs[i].loc); long call_offset = (unsigned long)t->call_locs[i].xfer_addr - (unsigned long)call_addr; /* div addr diff by 4 for arm offset value */ call_offset = call_offset >> 2; call_offset = call_offset >> 24; #ifdef HOST_ARM8 if (((call_offset != 0) && (call_offset != -1)) || package) { t->call_locs[i].mach_info = (void*) ((long)s->p->cur_ip - (long)s->p->code_base); arm8_pldsti(s, DILL_P, 1, _v1, _pc, 0); arm8_movi(s, _pc, _v1); arm8_nop(s); /* place where addr will be loaded */ } #endif } } static void arm8_call_link(dill_stream s) { arm8_rt_call_link(s->p->code_base, &s->p->call_table); } /* Clear the instruction cache from `beg' to `end'. This makes an inline system call to SYS_cacheflush. */ #define CLEAR_INSN_CACHE(BEG, END) \ { \ register unsigned long _beg __asm ("a1") = (unsigned long) (BEG); \ register unsigned long _end __asm ("a2") = (unsigned long) (END); \ register unsigned long _flg __asm ("a3") = 0; \ __asm __volatile ("swi 0x9f0002 @ sys_cacheflush" \ : "=r" (_beg) \ : "0" (_beg), "r" (_end), "r" (_flg)); \ } /* * Cache flush code grabbed from a Dec 1999 posting on libc-hacker * mailing list */ extern void __clear_cache(char*, char *); static void arm8_flush(void *base, void *limit) { #if defined(HOST_ARM8) || defined(HOST_ARM7) __clear_cache(base, limit); #endif } static void arm8_emit_save(dill_stream s) { arm8_mach_info ami = (arm8_mach_info) s->p->mach_info; void *save_ip = s->p->cur_ip; int ar_size = ami->act_rec_size + ami->max_arg_size; int float_count = 0; int int_count = 3; /* fp, ip, lr */ int reg; int mask = 0; ret_t *t = &s->p->ret_table; int i; ar_size += 14 * 4 /* int save */ + 8 * 3 * 4 /* float save */; ar_size = roundup(ar_size, 8); switch(ami->max_arg_size) { case 0: case 4: mask |= 1<<_a3; case 8: mask |= 1<<_a3; case 12: mask |= 1<<_a4; default: /* save nothing */ break; } mask |= 1<< _v1; for (reg = _v2; reg <= _v7; reg++) { if (dill_wasused(&s->p->tmp_i, reg)) { mask |= (1<<reg); int_count++; } } for (reg = _f16; reg <= _f30; reg++) { if (dill_wasused(&s->p->tmp_f, reg)) { float_count = reg - _f16 + 2; } } s->p->cur_ip = (char*)s->p->code_base + ami->save_insn_offset - 16; INSN_OUT(s, COND(AL)|CLASS(4)|1<<24/*p*/|RN(_sp)| mask|1<<_r11|1<<_r12|1<<_link|1<<_pc;); s->p->cur_ip = (char*)s->p->code_base + ami->save_insn_offset - 8; if (float_count > 0) { INSN_OUT(s, COND(AL)|CLASS(6)|1<<24|1<<21|RN(_sp)|(_f8)<<12|0b1011<<8|float_count); /*sfm*/ } else { arm8_nop(s); } s->p->cur_ip = (char*)s->p->code_base + ami->save_insn_offset; arm8_savei(s, -ar_size); for(i=0; i< t->ret_count; i++) { s->p->cur_ip = (char*)((char *)s->p->code_base + t->ret_locs[i]); arm8_dproci(s, ADD, 0, _sp, _sp, ar_size); if (float_count > 0) { int offset = 4 * 12 + 14*4 - 4; INSN_OUT(s, COND(AL)|CLASS(6)|1<<23|1<<21|1<<20|RN(_sp)|(_f8)<<12|0b1011<<8|float_count); /*lfm*/ arm8_dproci(s, ADD, 0, _sp, _sp, 4*14); } else { arm8_dproci(s, ADD, 0, _sp, _sp, ar_size + 4*14); } INSN_OUT(s, COND(AL)|CLASS(4)|1<<24/*p*/|1<<20/*l*/|RN(_r11)|1<<_r11|1<<_sp|1<<_pc|mask); } s->p->fp = (char*)s->p->code_base + 12; /* skip 3 swinv */ s->p->cur_ip = save_ip; } extern void arm8_end(s) dill_stream s; { arm8_nop(s); arm8_simple_ret(s); arm8_PLT_emit(s, 0); /* must be done before linking */ arm8_branch_link(s); arm8_call_link(s); arm8_data_link(s); arm8_emit_save(s); arm8_flush(s->p->code_base, s->p->code_limit); } extern void arm8_package_end(s) dill_stream s; { arm8_nop(s); arm8_simple_ret(s); arm8_PLT_emit(s, 1); arm8_branch_link(s); arm8_emit_save(s); } extern void * arm8_clone_code(s, new_base, available_size) dill_stream s; void *new_base; int available_size; { int size = dill_code_size(s); if (available_size < size) { return NULL; } void *old_base = s->p->code_base; void *native_base = s->p->code_base; if (native_base == NULL) native_base = s->p->native.code_base; memcpy(new_base, native_base, size); s->p->code_base = new_base; s->p->cur_ip = new_base + size; s->p->fp = new_base; arm8_branch_link(s); arm8_call_link(s); arm8_data_link(s); arm8_flush(new_base, (void*)((long)new_base + size)); s->p->code_base = old_base; s->p->cur_ip = old_base + size; s->p->fp = old_base; while (*(int*)new_base == 0xFF000000) { /* skip UNIMPs */ new_base = (void*)((long) new_base + 4); } return new_base; } extern void arm8_pset(dill_stream s, int type, int junk, int dest, long imm) { arm8_set(s, dest, imm); } extern void arm8_setp(dill_stream s, int type, int junk, int dest, void* imm) { arm8_pset(s, DILL_L, 0, dest, (long)imm); } extern void arm8_setf(dill_stream s, int type, int junk, int dest, double imm) { union { float f; int i; } a; union { double d; long l; int i[2]; } b; arm8_mach_info ami = (arm8_mach_info) s->p->mach_info; if (type == DILL_F) { a.f = (float) imm; arm8_set(s, _v1, a.i); arm8_movi2f(s, dest, _v1); } else { b.d = imm; arm8_set(s, _v1, b.i[0]); arm8_pstorei(s, DILL_I, 0, _v1, _fp, ami->conversion_word); arm8_set(s, _v1, b.i[1]); arm8_pstorei(s, DILL_I, 0, _v1, _fp, ami->conversion_word+4); arm8_ploadi(s, DILL_D, 0, dest, _fp, ami->conversion_word); } } extern void arm8_set(s, r, val) dill_stream s; int r; long val; { #if defined(HOST_ARM7) /* movw */ INSN_OUT(s, COND(AL)|3<<24|((val>>12)&0xf)<<16| RD(r)| val&0xfff); if ((val & 0xffff0000) != 0) { int imm = (val >> 16) & 0xffff; /* movt */ INSN_OUT(s, COND(AL)|3<<24|4<<20|((imm>>12)&0xf)<<16| RD(r)| imm&0xfff); } #else arm8_dproci(s, MOV, 0, r, 0, val & 0xff); if ((val & 0xff00) != 0) { int imm = (val >> 8) & 0xff; /* or in the byte */ INSN_OUT(s, COND(AL)|CLASS(0x0)|OPCODE(ORR)|S(0)|RN(r)|RD(r)|IMM(imm, 8)); } if ((val & 0xff0000) != 0) { int imm = (val >> 16) & 0xff; /* or in the byte */ INSN_OUT(s, COND(AL)|CLASS(0x0)|OPCODE(ORR)|S(0)|RN(r)|RD(r)|IMM(imm, 16)); } if ((val & 0xff000000) != 0) { int imm = (val >> 24) & 0xff; /* or in the byte */ INSN_OUT(s, COND(AL)|CLASS(0x0)|OPCODE(ORR)|S(0)|RN(r)|RD(r)|IMM(imm, 24)); } #endif } #define bit_R(x) ((unsigned long)1<<x) extern void arm8_reg_init(dill_stream s) { s->p->var_i.init_avail[0] = 0; s->p->var_i.members[0] = s->p->var_i.init_avail[0]; s->p->tmp_i.init_avail[0] = (bit_R(_v2)|bit_R(_v3)|bit_R(_v4)| bit_R(_v5)|bit_R(_v6)|bit_R(_v7)); s->p->tmp_i.members[0] = s->p->tmp_i.init_avail[0] | bit_R(_v1) | (bit_R(_a1)|bit_R(_a2)|bit_R(_a3)|bit_R(_a4)); s->p->var_f.init_avail[0] = 0; s->p->var_f.members[0] = s->p->var_f.init_avail[0]; /* in reality, there are 32 single precision regs, overlapping 16 * double-precision regs. DILL isn't quite smart enough to handle * overlapping registers, so we allocate only the even ones. _f2 if * used as a double-precision corresponds to ARM register D1. */ s->p->tmp_f.init_avail[0] = (bit_R(_f16)|bit_R(_f18)|bit_R(_f20)|bit_R(_f22)| bit_R(_f24)|bit_R(_f26)|bit_R(_f28)|bit_R(_f30)); s->p->tmp_f.members[0] = s->p->tmp_f.init_avail[0]; } extern void* gen_arm8_mach_info(s, v9) dill_stream s; int v9; { arm8_mach_info ami = malloc(sizeof(*ami)); if (s->p->mach_info != NULL) { free(s->p->mach_info); s->p->mach_info = NULL; s->p->native.mach_info = NULL; } arm8_reg_init(s); ami->act_rec_size = 0; ami->conversion_word = 0; ami->gp_save_offset = 0; ami->cur_arg_offset = 0; ami->next_core_register = _r0; ami->next_float_register = _f0; ami->stack_align = 4; ami->stack_constant_offset = 0; ami->fp_save_offset = ami->gp_save_offset + 8 * ami->stack_align; ami->fp_save_end = ami->fp_save_offset + 8 * 8; ami->max_arg_size = 0; ami->hard_float = ARM_HARD_FLOAT; return ami; } #if defined(HAVE_DIS_ASM_H) && !defined(NO_DISASSEMBLER) /* GENERIC BINUTILS DISASSEMBLER */ #include "dis-asm.h" #define MAXLENGTH (1<<23) /* Max length of function that can be disassembled */ extern int arm8_init_disassembly_info(dill_stream s, void * ptr) { struct disassemble_info *i = ptr; #ifdef INIT_DISASSEMBLE_INFO_THREE_ARG INIT_DISASSEMBLE_INFO(*i, stdout,fprintf); i->endian = BFD_ENDIAN_BIG; #else INIT_DISASSEMBLE_INFO(*i, stdout); #endif #ifdef bfd_mach_arm8_5 i->mach = bfd_mach_arm8_5; #elif defined (bfd_mach_arm8_4) i->mach = bfd_mach_arm8_4; #elif defined (bfd_mach_arm8_3) i->mach = bfd_mach_arm8_3; #endif if (s->p->code_base != NULL) { i->buffer = (bfd_byte *)s->p->code_base; i->buffer_vma = (bfd_vma)s->p->code_base; } else { i->buffer = (bfd_byte *)s->p->native.code_base; i->buffer_vma = (bfd_vma)s->p->native.code_base; } i->buffer_length = MAXLENGTH; #ifdef HAVE_PRINT_INSN_ARM return 1; #elif defined(HAVE_PRINT_INSN_LITTLE_ARM) return 1; #else return 0; #endif } extern int arm8_print_insn(dill_stream s, void *info_ptr, void *insn) { #ifdef HAVE_PRINT_INSN_ARM return print_insn_arm((unsigned long) insn, (disassemble_info*)info_ptr); #elif defined(HAVE_PRINT_INSN_LITTLE_ARM) return print_insn_little_arm((unsigned long) insn, (disassemble_info*)info_ptr); #else return 0; #endif } #else extern int arm8_init_disassembly_info(dill_stream s, void * ptr){return 0;} extern int arm8_print_insn(dill_stream s, void *info_ptr, void *insn){return 0;} #endif extern void arm8_print_reg(dill_stream s, int typ, int reg) { switch(typ) { case DILL_C: case DILL_UC: case DILL_S: case DILL_US: case DILL_I: case DILL_U: case DILL_L: case DILL_UL: if (reg == _sp) { printf("sp"); return; } else if (reg == _link) { printf("link"); return; } else if (reg == _pc) { printf("pc"); return; } else if (reg == _fp) { printf("fp"); return; } else if (reg <= _r3) { printf("r%d(a%d)\n", reg, reg +1); return; } else if (reg <= _r10) { printf("r%d(v%d)\n", reg, reg - 3); return; } break; case DILL_F: case DILL_D: printf("F%d", reg); return; } printf("NoReg(%d)", reg); } extern int arm8_count_insn(dill_stream s, int start, int end) { return (end - start)>>2; }
27.771218
212
0.609582
4c302aea8a34a4d5e524622c8e50b3c7be910cda
335
dart
Dart
example/lib/book.dart
Skquark/firestore_entity
d54f09b3fc15a98823d0eff113aff6af8b988982
[ "MIT" ]
1
2020-04-23T23:28:42.000Z
2020-04-23T23:28:42.000Z
example/lib/book.dart
Skquark/firestore_entity
d54f09b3fc15a98823d0eff113aff6af8b988982
[ "MIT" ]
null
null
null
example/lib/book.dart
Skquark/firestore_entity
d54f09b3fc15a98823d0eff113aff6af8b988982
[ "MIT" ]
2
2020-05-21T21:13:41.000Z
2022-01-24T08:15:23.000Z
class Book { String id; String title; Book({this.id, this.title}); factory Book.fromJson(Map<String, dynamic> json) => Book( id: json['id'] as String, title: json['title'] as String, ); Map<String, dynamic> toJson() => <String, dynamic>{ 'id': this.id, 'title': this.title, }; }
20.9375
59
0.552239
bf6c77f9bc855ee8aacee34463e8cc99f31824f5
791
swift
Swift
MeetPaws/MeetPaws/Helpers + Extension/UIView + Extension.swift
princekili/MeetPaws
1e73b70b3ad25798386a4579e34597559617a730
[ "MIT" ]
2
2020-12-01T03:03:21.000Z
2020-12-01T03:03:33.000Z
MeetPaws/MeetPaws/Helpers + Extension/UIView + Extension.swift
princekili/Yogogo
1e73b70b3ad25798386a4579e34597559617a730
[ "MIT" ]
null
null
null
MeetPaws/MeetPaws/Helpers + Extension/UIView + Extension.swift
princekili/Yogogo
1e73b70b3ad25798386a4579e34597559617a730
[ "MIT" ]
null
null
null
// // UIView + Extension.swift // MeetPaws // // Created by prince on 2020/12/2. // import UIKit extension UIView { var width: CGFloat { return frame.size.width } var height: CGFloat { return frame.size.height } var top: CGFloat { return frame.origin.y } var bottom: CGFloat { return frame.origin.y + frame.size.height } var left: CGFloat { return frame.origin.x } var right: CGFloat { return frame.origin.x + frame.size.width } // MARK: - func enableLongPress(sender: Any, select: Selector) { let longPress = UILongPressGestureRecognizer(target: sender, action: select) self.addGestureRecognizer(longPress) } }
17.577778
84
0.571429
91ce668547d4298274e0f6a62de889634c25e065
20,926
swift
Swift
Yihaodar/GLAdd/GLCarConfigViewController.swift
z234009184/Yihaodar
6642c22237af94db5878fa44166acf64df0fc2ac
[ "MIT" ]
3
2018-02-01T13:18:41.000Z
2018-06-12T03:00:42.000Z
Yihaodar/GLAdd/GLCarConfigViewController.swift
z234009184/Yihaodar
6642c22237af94db5878fa44166acf64df0fc2ac
[ "MIT" ]
null
null
null
Yihaodar/GLAdd/GLCarConfigViewController.swift
z234009184/Yihaodar
6642c22237af94db5878fa44166acf64df0fc2ac
[ "MIT" ]
null
null
null
// // GLCarStateViewController.swift // Yihaodar // // Created by 张国梁 on 2018/2/26. // Copyright © 2018年 Yihaodar. All rights reserved. // import Spring class GLCarConfigViewController: UIViewController { @IBOutlet weak var gearboxLabel: UILabel! @IBOutlet weak var drivingTypeLabel: UILabel! @IBOutlet weak var keylessStartupLabel: UILabel! @IBOutlet weak var cruiseControlLabel: UILabel! @IBOutlet weak var navigationLabel: UILabel! @IBOutlet weak var hpylLabel: UILabel! @IBOutlet weak var seatFormatLabel: UILabel! @IBOutlet weak var fuelTypeLabel: UILabel! @IBOutlet weak var skylightLabel: UILabel! @IBOutlet weak var airConditionerLabel: UILabel! @IBOutlet weak var otherLabel: UILabel! @IBOutlet weak var accidentLabel: UILabel! @IBOutlet weak var openOrFoldBtn: UIButton! @IBOutlet var optionViews: [UIView]! @IBOutlet var optionViewsHeight: [NSLayoutConstraint]! override func viewDidLoad() { super.viewDidLoad() openOrFoldBtnClick(openOrFoldBtn) let backItem = UIBarButtonItem() backItem.title = "上一步"; navigationItem.backBarButtonItem = backItem; navigationItem.title = "新建车辆评估" navigationItem.rightBarButtonItem = UIBarButtonItem(title: "下一步", style: .done, target: self, action: #selector(GLCarConfigViewController.nextBtnClick(item:))) } @objc func nextBtnClick(item: UIBarButtonItem) { if gearboxLabel.text == "请选择" || gearboxLabel.text?.isEmpty == true { view.makeToast("请选择变速器") return } if drivingTypeLabel.text == "请选择" || drivingTypeLabel.text?.isEmpty == true { view.makeToast("请选择驱动方式") return } if keylessStartupLabel.text == "请选择" || keylessStartupLabel.text?.isEmpty == true { view.makeToast("请选择有无钥匙启动") return } if cruiseControlLabel.text == "请选择" || cruiseControlLabel.text?.isEmpty == true { view.makeToast("请选择定速巡航") return } if navigationLabel.text == "请选择" || navigationLabel.text?.isEmpty == true { view.makeToast("请选择导航") return } if hpylLabel.text == "请选择" || hpylLabel.text?.isEmpty == true { view.makeToast("请选择后排娱乐") return } if seatFormatLabel.text == "请选择" || seatFormatLabel.text?.isEmpty == true { view.makeToast("请选择座椅形式") return } if fuelTypeLabel.text == "请选择" || fuelTypeLabel.text?.isEmpty == true { view.makeToast("请选择燃油方式") return } if skylightLabel.text == "请选择" || skylightLabel.text?.isEmpty == true { view.makeToast("请选择天窗") return } if airConditionerLabel.text == "请选择" || airConditionerLabel.text?.isEmpty == true { view.makeToast("请选择空调配置") return } /// 存入提交模型中 GLEstimateResultViewController.summitModel.gearbox = gearboxLabel.text ?? "" GLEstimateResultViewController.summitModel.driving_type = drivingTypeLabel.text ?? "" GLEstimateResultViewController.summitModel.keyless_startup = keylessStartupLabel.text ?? "" GLEstimateResultViewController.summitModel.cruise_control = cruiseControlLabel.text ?? "" GLEstimateResultViewController.summitModel.navigation = navigationLabel.text ?? "" GLEstimateResultViewController.summitModel.hpyl = hpylLabel.text ?? "" GLEstimateResultViewController.summitModel.chair_type = seatFormatLabel.text ?? "" GLEstimateResultViewController.summitModel.fuel_type = fuelTypeLabel.text ?? "" GLEstimateResultViewController.summitModel.skylight = skylightLabel.text ?? "" GLEstimateResultViewController.summitModel.air_conditioner = airConditionerLabel.text ?? "" GLEstimateResultViewController.summitModel.other = otherLabel.text != "请选择" ? otherLabel.text! : "" GLEstimateResultViewController.summitModel.accident = accidentLabel.text != "请选择" ? accidentLabel.text! : "" selectedOtherModels?.forEach({ (radioModel) in if radioModel.isTextFied { GLEstimateResultViewController.summitModel.airbag = radioModel.input ?? "" } }) selectedAccidentModels?.forEach({ (radioModel) in if radioModel.isTextFied { GLEstimateResultViewController.summitModel.accident_level = radioModel.input ?? "" } }) let vc = UIStoryboard(name: "GLCreateCarEstimate", bundle: Bundle(for: type(of: self))).instantiateViewController(withIdentifier: "GLCarStateViewController") as! GLCarStateViewController navigationController?.pushViewController(vc, animated: true) } var selectedGearboxModel: GLRadioModel? @IBAction func gearboxAction(_ sender: UIButton) { // 单选 // 加载数据 let path = Bundle.main.path(forResource: "biansuqi", ofType: "plist") guard let filePath = path else { return } let arr = NSArray(contentsOfFile: filePath) as? [Any] // 字典数组 转模型数组 guard var dataArray = [GLRadioModel].deserialize(from: arr) as? [GLRadioModel] else { return } if let selectedGearboxModel = selectedGearboxModel { dataArray = dataArray.map({ (radioModel) -> GLRadioModel in var radioModel = radioModel if selectedGearboxModel.id == radioModel.id { radioModel = selectedGearboxModel } return radioModel }) } let radioVc = GLRadioViewController.jumpRadioVc(title: "选择变速器", dataArray: dataArray, navigationVc: navigationController) radioVc.closeClosure = { [weak self] (radioModel) in self?.selectedGearboxModel = radioModel self?.gearboxLabel.text = radioModel.title } } var selectedDrivingTypeModel: GLRadioModel? @IBAction func drivingTypeAction(_ sender: UIButton) { // 加载数据 let path = Bundle.main.path(forResource: "qudongfangshi", ofType: "plist") guard let filePath = path else { return } let arr = NSArray(contentsOfFile: filePath) as? [Any] // 字典数组 转模型数组 guard var dataArray = [GLRadioModel].deserialize(from: arr) as? [GLRadioModel] else { return } if let selectedDrivingTypeModel = selectedDrivingTypeModel { dataArray = dataArray.map({ (radioModel) -> GLRadioModel in var radioModel = radioModel if selectedDrivingTypeModel.id == radioModel.id { radioModel = selectedDrivingTypeModel } return radioModel }) } let radioVc = GLRadioViewController.jumpRadioVc(title: "选择驱动方式", dataArray: dataArray, navigationVc: navigationController) radioVc.closeClosure = { [weak self] (radioModel) in self?.selectedDrivingTypeModel = radioModel self?.drivingTypeLabel.text = radioModel.title } } var selectedKeylessModel: GLRadioModel? @IBAction func keylessStartupAction(_ sender: UIButton) { // 加载数据 let path = Bundle.main.path(forResource: "youwu", ofType: "plist") guard let filePath = path else { return } let arr = NSArray(contentsOfFile: filePath) as? [Any] // 字典数组 转模型数组 guard var dataArray = [GLRadioModel].deserialize(from: arr) as? [GLRadioModel] else { return } if let selectedKeylessModel = selectedKeylessModel { dataArray = dataArray.map({ (radioModel) -> GLRadioModel in var radioModel = radioModel if selectedKeylessModel.id == radioModel.id { radioModel = selectedKeylessModel } return radioModel }) } let radioVc = GLRadioViewController.jumpRadioVc(title: "选择有无钥匙启动", dataArray: dataArray, navigationVc: navigationController) radioVc.closeClosure = { [weak self] (radioModel) in self?.selectedKeylessModel = radioModel self?.keylessStartupLabel.text = radioModel.title } } var selectedCruiseControlModel: GLRadioModel? @IBAction func cruiseControlAction(_ sender: UIButton) { // 加载数据 let path = Bundle.main.path(forResource: "youwu", ofType: "plist") guard let filePath = path else { return } let arr = NSArray(contentsOfFile: filePath) as? [Any] // 字典数组 转模型数组 guard var dataArray = [GLRadioModel].deserialize(from: arr) as? [GLRadioModel] else { return } if let selectedCruiseControlModel = selectedCruiseControlModel { dataArray = dataArray.map({ (radioModel) -> GLRadioModel in var radioModel = radioModel if selectedCruiseControlModel.id == radioModel.id { radioModel = selectedCruiseControlModel } return radioModel }) } let radioVc = GLRadioViewController.jumpRadioVc(title: "选择定速巡航", dataArray: dataArray, navigationVc: navigationController) radioVc.closeClosure = { [weak self] (radioModel) in self?.selectedCruiseControlModel = radioModel self?.cruiseControlLabel.text = radioModel.title } } var selectedNavigationModel: GLRadioModel? @IBAction func navigationAction(_ sender: UIButton) { // 加载数据 let path = Bundle.main.path(forResource: "youwu", ofType: "plist") guard let filePath = path else { return } let arr = NSArray(contentsOfFile: filePath) as? [Any] // 字典数组 转模型数组 guard var dataArray = [GLRadioModel].deserialize(from: arr) as? [GLRadioModel] else { return } if let selectedNavigationModel = selectedNavigationModel { dataArray = dataArray.map({ (radioModel) -> GLRadioModel in var radioModel = radioModel if selectedNavigationModel.id == radioModel.id { radioModel = selectedNavigationModel } return radioModel }) } let radioVc = GLRadioViewController.jumpRadioVc(title: "选择导航", dataArray: dataArray, navigationVc: navigationController) radioVc.closeClosure = { [weak self] (radioModel) in self?.selectedNavigationModel = radioModel self?.navigationLabel.text = radioModel.title } } var selectedHpylModel: GLRadioModel? @IBAction func hpylAction(_ sender: UIButton) { // 加载数据 let path = Bundle.main.path(forResource: "youwu", ofType: "plist") guard let filePath = path else { return } let arr = NSArray(contentsOfFile: filePath) as? [Any] // 字典数组 转模型数组 guard var dataArray = [GLRadioModel].deserialize(from: arr) as? [GLRadioModel] else { return } if let selectedHpylModel = selectedHpylModel { dataArray = dataArray.map({ (radioModel) -> GLRadioModel in var radioModel = radioModel if selectedHpylModel.id == radioModel.id { radioModel = selectedHpylModel } return radioModel }) } let radioVc = GLRadioViewController.jumpRadioVc(title: "选择后排娱乐", dataArray: dataArray, navigationVc: navigationController) radioVc.closeClosure = { [weak self] (radioModel) in self?.selectedHpylModel = radioModel self?.hpylLabel.text = radioModel.title } } var selectSeatFormatModels: [GLRadioModel]? @IBAction func carSeatFormatAction(_ sender: UIButton) { // 加载数据 let path = Bundle.main.path(forResource: "zuoyixingshi", ofType: "plist") guard let filePath = path else { return } let arr = NSArray(contentsOfFile: filePath) as? [Any] // 字典数组 转模型数组 guard var dataArray = [GLRadioModel].deserialize(from: arr) as? [GLRadioModel] else { return } if let selectSeatFormatModels = selectSeatFormatModels { dataArray = dataArray.map({ (radioModel) -> GLRadioModel in var radioModel = radioModel for value in selectSeatFormatModels { if value.id == radioModel.id { radioModel = value } } return radioModel }) } let multiVc = GLCheckBoxViewController.jumpMultiVc(title: "选择座椅形式", dataArray: dataArray, navigationVc: navigationController) multiVc.closeClosure = { [weak self] (arr) in self?.selectSeatFormatModels = arr self?.seatFormatLabel.text = arr.reduce("", { (result, radioModel) -> String in let title = radioModel.title ?? "" let input = radioModel.input ?? "" let str = result.isEmpty ? "" : "、" return result + str + title + input }) } } var selectedFuelTypeModels: [GLRadioModel]? @IBAction func fuelTypeAction(_ sender: UIButton) { // 加载数据 let path = Bundle.main.path(forResource: "ranyoufangshi", ofType: "plist") guard let filePath = path else { return } let arr = NSArray(contentsOfFile: filePath) as? [Any] // 字典数组 转模型数组 guard var dataArray = [GLRadioModel].deserialize(from: arr) as? [GLRadioModel] else { return } if let selectedFuelTypeModels = selectedFuelTypeModels { dataArray = dataArray.map({ (radioModel) -> GLRadioModel in var radioModel = radioModel for value in selectedFuelTypeModels { if value.id == radioModel.id { radioModel = value } } return radioModel }) } let multiVc = GLCheckBoxViewController.jumpMultiVc(title: "选择燃油方式", dataArray: dataArray, navigationVc: navigationController) multiVc.closeClosure = { [weak self] (arr) in self?.selectedFuelTypeModels = arr self?.fuelTypeLabel.text = arr.reduce("", { (result, radioModel) -> String in let title = radioModel.title ?? "" let input = radioModel.input ?? "" let str = result.isEmpty ? "" : "、" return result + str + title + input }) } } var selectedSkylightModel: GLRadioModel? @IBAction func skylightAction(_ sender: UIButton) { // 加载数据 let path = Bundle.main.path(forResource: "tianchuang", ofType: "plist") guard let filePath = path else { return } let arr = NSArray(contentsOfFile: filePath) as? [Any] // 字典数组 转模型数组 guard var dataArray = [GLRadioModel].deserialize(from: arr) as? [GLRadioModel] else { return } if let selectedSkylightModel = selectedSkylightModel { dataArray = dataArray.map({ (radioModel) -> GLRadioModel in var radioModel = radioModel if selectedSkylightModel.id == radioModel.id { radioModel = selectedSkylightModel } return radioModel }) } let radioVc = GLRadioViewController.jumpRadioVc(title: "选择天窗", dataArray: dataArray, navigationVc: navigationController) radioVc.closeClosure = { [weak self] (radioModel) in self?.selectedSkylightModel = radioModel self?.skylightLabel.text = radioModel.title } } var selectedAirConditionerModels: [GLRadioModel]? @IBAction func airConditionerAction(_ sender: UIButton) { // 加载数据 let path = Bundle.main.path(forResource: "kongtiaopeizhi", ofType: "plist") guard let filePath = path else { return } let arr = NSArray(contentsOfFile: filePath) as? [Any] // 字典数组 转模型数组 guard var dataArray = [GLRadioModel].deserialize(from: arr) as? [GLRadioModel] else { return } if let selectedAirConditionerModels = selectedAirConditionerModels { dataArray = dataArray.map({ (radioModel) -> GLRadioModel in var radioModel = radioModel for value in selectedAirConditionerModels { if value.id == radioModel.id { radioModel = value } } return radioModel }) } let multiVc = GLCheckBoxViewController.jumpMultiVc(title: "选择空调配置", dataArray: dataArray, navigationVc: navigationController) multiVc.closeClosure = { [weak self] (arr) in self?.selectedAirConditionerModels = arr self?.airConditionerLabel.text = arr.reduce("", { (result, radioModel) -> String in let title = radioModel.title ?? "" let input = radioModel.input ?? "" let str = result.isEmpty ? "" : "、" return result + str + title + input }) } } var selectedOtherModels: [GLRadioModel]? @IBAction func otherAction(_ sender: UIButton) { // 加载数据 let path = Bundle.main.path(forResource: "qita", ofType: "plist") guard let filePath = path else { return } let arr = NSArray(contentsOfFile: filePath) as? [Any] // 字典数组 转模型数组 guard var dataArray = [GLRadioModel].deserialize(from: arr) as? [GLRadioModel] else { return } if let selectedOtherModels = selectedOtherModels { dataArray = dataArray.map({ (radioModel) -> GLRadioModel in var radioModel = radioModel for value in selectedOtherModels { if value.id == radioModel.id { radioModel = value } } return radioModel }) } let multiVc = GLCheckBoxViewController.jumpMultiVc(title: "选择其他", dataArray: dataArray, navigationVc: navigationController) multiVc.closeClosure = { [weak self] (arr) in self?.selectedOtherModels = arr self?.otherLabel.text = arr.reduce("", { (result, radioModel) -> String in let title = radioModel.title ?? "" let input = (radioModel.input != nil) ? (radioModel.input)! + "个" : "" let str = result.isEmpty ? "" : "、" return result + str + title + input }) } } var selectedAccidentModels: [GLRadioModel]? @IBAction func accidentAction(_ sender: UIButton) { // 加载数据 let path = Bundle.main.path(forResource: "shigu", ofType: "plist") guard let filePath = path else { return } let arr = NSArray(contentsOfFile: filePath) as? [Any] // 字典数组 转模型数组 guard var dataArray = [GLRadioModel].deserialize(from: arr) as? [GLRadioModel] else { return } if let selectedAccidentModels = selectedAccidentModels { dataArray = dataArray.map({ (radioModel) -> GLRadioModel in var radioModel = radioModel for value in selectedAccidentModels { if value.id == radioModel.id { radioModel = value } } return radioModel }) } let multiVc = GLCheckBoxViewController.jumpMultiVc(title: "选择事故", dataArray: dataArray, navigationVc: navigationController) multiVc.closeClosure = { [weak self] (arr) in self?.selectedAccidentModels = arr self?.accidentLabel.text = arr.reduce("", { (result, radioModel) -> String in let title = radioModel.title ?? "" let input = radioModel.input ?? "" let str = result.isEmpty ? "" : "、" return result + str + title + input }) } } /// 展开/折叠 @IBAction func openOrFoldBtnClick(_ sender: UIButton) { sender.isSelected = !sender.isSelected if sender.isSelected == true { optionViewsHeight.forEach({ (obj) in obj.constant = 70 }) optionViews.forEach({ (obj) in obj.isHidden = false }) } else { optionViewsHeight.forEach({ (obj) in obj.constant = 0 }) optionViews.forEach({ (obj) in obj.isHidden = true }) } UIView.animate(withDuration: 0.25) { self.view.layoutIfNeeded() } } }
42.706122
194
0.593281
da92cb53ff05fa837d57e8c8e2cff7fce6a60d21
1,319
sql
SQL
schema/test/unit/mutations/create_naics_code_mutation_test.sql
bcgov/cas-ciip-portal
dceb5331fa17902b1100e6faccac9d36eeb8b4a5
[ "Apache-2.0" ]
9
2019-10-09T20:57:34.000Z
2020-11-19T15:32:32.000Z
schema/test/unit/mutations/create_naics_code_mutation_test.sql
bcgov/cas-ciip-portal
dceb5331fa17902b1100e6faccac9d36eeb8b4a5
[ "Apache-2.0" ]
1,282
2019-08-21T20:43:34.000Z
2022-03-30T16:46:46.000Z
schema/test/unit/mutations/create_naics_code_mutation_test.sql
bcgov/cas-ciip-portal
dceb5331fa17902b1100e6faccac9d36eeb8b4a5
[ "Apache-2.0" ]
2
2019-10-16T22:27:43.000Z
2021-01-26T20:05:13.000Z
set client_min_messages to warning; create extension if not exists pgtap; reset client_min_messages; begin; select plan(4); -- Function exists select has_function( 'ggircs_portal', 'create_naics_code', array['text', 'text', 'text'], 'Function ggircs_portal.create_naics_code should exist' ); -- Test Setup select test_helper.clean_ggircs_portal_schema(); select ggircs_portal.create_naics_code('1234', 'sector', 'init'); select results_eq( $$ select naics_description from ggircs_portal.naics_code where naics_code='1234'; $$, array['init'::varchar(10000)], 'Custom mutation creates a row if the NAICS code does not already exist' ); -- "Delete" naics code & re-run custom mutation update ggircs_portal.naics_code set deleted_at=now() where naics_code='1234'; select ggircs_portal.create_naics_code('1234', 'sector', 'updated'); select results_eq( $$ select naics_description from ggircs_portal.naics_code where naics_code='1234'; $$, array['updated'::varchar(1000)], 'Custom mutation updates the description when the naics_code already exists' ); select is_empty( $$ select * from ggircs_portal.naics_code where naics_code='1234' and deleted_at is not null; $$, 'Custom mutation sets deleted_at to null when the naics_code already exists' ); select finish(); rollback;
26.918367
95
0.752085
2a1dd1dfd7d8ca7eb6b2161234598b12512979f5
1,459
java
Java
biz.aQute.quantity.library/src/main/java/aQute/quantity/types/util/ElectricalCharge.java
kchobantonov/biz.aQute.osgi.util
7374c0ef286bc7edb5fc41fe35b8b4e412e90bf9
[ "Apache-2.0" ]
null
null
null
biz.aQute.quantity.library/src/main/java/aQute/quantity/types/util/ElectricalCharge.java
kchobantonov/biz.aQute.osgi.util
7374c0ef286bc7edb5fc41fe35b8b4e412e90bf9
[ "Apache-2.0" ]
null
null
null
biz.aQute.quantity.library/src/main/java/aQute/quantity/types/util/ElectricalCharge.java
kchobantonov/biz.aQute.osgi.util
7374c0ef286bc7edb5fc41fe35b8b4e412e90bf9
[ "Apache-2.0" ]
null
null
null
package aQute.quantity.types.util; import aQute.quantity.base.util.DerivedQuantity; import aQute.quantity.base.util.Unit; import aQute.quantity.base.util.UnitInfo; /** * The SI system defines the coulomb in terms of the ampere and second: 1 C = 1 * A × 1 s. * * Since the charge of one electron is known to be about −1.6021766208(98)×10−19 * C,[7] −1 C can also be considered the charge of roughly 6.241509×1018 * electrons (or +1 C the charge of that many positrons or protons), where the * number is the reciprocal of 1.602177×10−19. * */ @UnitInfo(unit = "C", symbol = "Q", dimension = "Electric charge", symbolForDimension = "?") public class ElectricalCharge extends DerivedQuantity<ElectricalCharge> { public static ElectricalCharge ELEMENTARY_CHARGE = new ElectricalCharge(1.602176620898E-19D); private static final long serialVersionUID = 1L; final static Unit unit = new Unit(ElectricalCharge.class, // // Current.DIMe1, // Time.DIMe1 ); ElectricalCharge(double value) { super(value); } public static ElectricalCharge from(double value) { return new ElectricalCharge(value); } @Override protected ElectricalCharge same(double value) { return from(value); } @Override public Unit getUnit() { return unit; } public static ElectricalCharge fromAh(double value) { return new ElectricalCharge(value * 3600); } public double toAh() { return this.value / 3600; } }
26.053571
94
0.712132
f4b2af2257a4c4142473f832120555bc758c1c73
130
go
Go
services/account/service.go
juniortads/kuiper-wallet
9f74dc965f2ee5a16b1ed4af273a7de28d518757
[ "Apache-2.0" ]
7
2021-01-31T22:16:59.000Z
2021-08-22T22:27:43.000Z
services/account/service.go
juniortads/kuiper-wallet
9f74dc965f2ee5a16b1ed4af273a7de28d518757
[ "Apache-2.0" ]
6
2021-01-27T00:46:05.000Z
2021-05-06T23:34:18.000Z
services/account/service.go
juniortads/kuiper-wallet
9f74dc965f2ee5a16b1ed4af273a7de28d518757
[ "Apache-2.0" ]
3
2021-01-27T00:33:58.000Z
2021-05-06T23:42:08.000Z
package account import "context" type Service interface { CreateAccount(ctx context.Context, account Account) (string, error) }
18.571429
68
0.784615
48cccadd22f57f70cce9bee572ca64a85d56d031
12,253
c
C
components/usb/test/usb_host/test_usb_host_async.c
HubertXie/esp-idf
a7032feeaa2f5a600b8e0b37f80fd52538d22145
[ "Apache-2.0" ]
4
2022-03-15T22:43:28.000Z
2022-03-28T01:25:08.000Z
components/usb/test/usb_host/test_usb_host_async.c
HubertXie/esp-idf
a7032feeaa2f5a600b8e0b37f80fd52538d22145
[ "Apache-2.0" ]
null
null
null
components/usb/test/usb_host/test_usb_host_async.c
HubertXie/esp-idf
a7032feeaa2f5a600b8e0b37f80fd52538d22145
[ "Apache-2.0" ]
3
2021-08-07T09:17:31.000Z
2022-03-20T21:54:52.000Z
/* * SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD * * SPDX-License-Identifier: Apache-2.0 */ #include <stdio.h> #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/semphr.h" #include "esp_err.h" #include "esp_intr_alloc.h" #include "test_usb_common.h" #include "test_usb_mock_classes.h" #include "msc_client.h" #include "ctrl_client.h" #include "usb/usb_host.h" #include "unity.h" #include "test_utils.h" #define TEST_MSC_NUM_SECTORS_TOTAL 10 #define TEST_MSC_NUM_SECTORS_PER_XFER 2 #define TEST_MSC_SCSI_TAG 0xDEADBEEF #define TEST_CTRL_NUM_TRANSFERS 30 // --------------------------------------------------- Test Cases ------------------------------------------------------ /* Test USB Host Asynchronous API single client Requires: This test requires an MSC SCSI device to be attached (see the MSC mock class) Purpose: - Test that USB Host Asynchronous API works correctly with a single client - Test that a client can be created - Test that client can operate concurrently in a separate thread - Test that the main thread is able to detect library events (such as USB_HOST_LIB_EVENT_FLAGS_NO_CLIENTS) Procedure: - Install USB Host Library - Create a task to run an MSC client - Start the MSC client task. It will execute a bunch of MSC SCSI sector reads - Wait for the host library event handler to report a USB_HOST_LIB_EVENT_FLAGS_NO_CLIENTS event - Free all devices - Uninstall USB Host Library */ TEST_CASE("Test USB Host async client (single client)", "[usb_host][ignore]") { test_usb_init_phy(); //Initialize the internal USB PHY and USB Controller for testing //Install USB Host usb_host_config_t host_config = { .skip_phy_setup = true, //test_usb_init_phy() will already have setup the internal USB PHY for us .intr_flags = ESP_INTR_FLAG_LEVEL1, }; ESP_ERROR_CHECK(usb_host_install(&host_config)); printf("Installed\n"); //Create task to run client that communicates with MSC SCSI interface msc_client_test_param_t params = { .num_sectors_to_read = TEST_MSC_NUM_SECTORS_TOTAL, .num_sectors_per_xfer = TEST_MSC_NUM_SECTORS_PER_XFER, .msc_scsi_xfer_tag = TEST_MSC_SCSI_TAG, .idVendor = MOCK_MSC_SCSI_DEV_ID_VENDOR, .idProduct = MOCK_MSC_SCSI_DEV_ID_PRODUCT, }; TaskHandle_t task_hdl; xTaskCreatePinnedToCore(msc_client_async_seq_task, "async", 4096, (void *)&params, 2, &task_hdl, 0); //Start the task xTaskNotifyGive(task_hdl); while (1) { //Start handling system events uint32_t event_flags; usb_host_lib_handle_events(portMAX_DELAY, &event_flags); if (event_flags & USB_HOST_LIB_EVENT_FLAGS_NO_CLIENTS) { printf("No more clients\n"); TEST_ASSERT_EQUAL(ESP_ERR_NOT_FINISHED, usb_host_device_free_all()); } if (event_flags & USB_HOST_LIB_EVENT_FLAGS_ALL_FREE) { break; } } //Short delay to allow task to be cleaned up vTaskDelay(10); //Clean up USB Host ESP_ERROR_CHECK(usb_host_uninstall()); test_usb_deinit_phy(); //Deinitialize the internal USB PHY after testing } /* Test USB Host Asynchronous API with multiple clients Requires: This test requires an MSC SCSI device to be attached (see the MSC mock class) Purpose: - Test the USB Host Asynchronous API works correctly with multiple clients - Test that multiple clients can be created - Test that multiple clients can operate concurrently in separate threads - Test that the main thread is able to detect library events (such as USB_HOST_LIB_EVENT_FLAGS_NO_CLIENTS) Procedure: - Install USB Host Library - Create separate tasks to run an MSC client and Ctrl Client - MSC Client will execute a bunch of MSC SCSI sector reads - Ctrl Client will execute a bunch of control transfers - Wait for the host library event handler to report a USB_HOST_LIB_EVENT_FLAGS_NO_CLIENTS event - Free all devices - Uninstall USB Host Library */ TEST_CASE("Test USB Host async client (multi client)", "[usb_host][ignore]") { test_usb_init_phy(); //Initialize the internal USB PHY and USB Controller for testing //Install USB Host usb_host_config_t host_config = { .skip_phy_setup = true, //test_usb_init_phy() will already have setup the internal USB PHY for us .intr_flags = ESP_INTR_FLAG_LEVEL1, }; ESP_ERROR_CHECK(usb_host_install(&host_config)); printf("Installed\n"); //Create task to run the MSC client msc_client_test_param_t msc_params = { .num_sectors_to_read = TEST_MSC_NUM_SECTORS_TOTAL, .num_sectors_per_xfer = TEST_MSC_NUM_SECTORS_PER_XFER, .msc_scsi_xfer_tag = TEST_MSC_SCSI_TAG, .idVendor = MOCK_MSC_SCSI_DEV_ID_VENDOR, .idProduct = MOCK_MSC_SCSI_DEV_ID_PRODUCT, }; TaskHandle_t msc_task_hdl; xTaskCreatePinnedToCore(msc_client_async_seq_task, "msc", 4096, (void *)&msc_params, 2, &msc_task_hdl, 0); //Create task a control transfer client ctrl_client_test_param_t ctrl_params = { .num_ctrl_xfer_to_send = TEST_CTRL_NUM_TRANSFERS, .idVendor = MOCK_MSC_SCSI_DEV_ID_VENDOR, .idProduct = MOCK_MSC_SCSI_DEV_ID_PRODUCT, }; TaskHandle_t ctrl_task_hdl; xTaskCreatePinnedToCore(ctrl_client_async_seq_task, "ctrl", 4096, (void *)&ctrl_params, 2, &ctrl_task_hdl, 0); //Start both tasks xTaskNotifyGive(msc_task_hdl); xTaskNotifyGive(ctrl_task_hdl); while (1) { //Start handling system events uint32_t event_flags; usb_host_lib_handle_events(portMAX_DELAY, &event_flags); if (event_flags & USB_HOST_LIB_EVENT_FLAGS_NO_CLIENTS) { printf("No more clients\n"); TEST_ASSERT_EQUAL(ESP_ERR_NOT_FINISHED, usb_host_device_free_all()); } if (event_flags & USB_HOST_LIB_EVENT_FLAGS_ALL_FREE) { break; } } //Short delay to allow task to be cleaned up vTaskDelay(10); //Clean up USB Host ESP_ERROR_CHECK(usb_host_uninstall()); test_usb_deinit_phy(); //Deinitialize the internal USB PHY after testing } /* Test USB Host Asynchronous API Usage Requires: This test requires an MSC SCSI device to be attached (see the MSC mock class) Purpose: - Test that incorrect usage of USB Host Asynchronous API will returns errors Procedure: - Install USB Host Library - Register two clients and all event handler functions from the same loop - Wait for each client to detect device connection - Check that both clients can open the same device - Check that a client cannot open a non-existent device - Check that only one client can claim a particular interface - Check that a client cannot release an already released interface - Wait for device disconnection - Cleanup */ static uint8_t dev_addr = 0; typedef enum { CLIENT_TEST_STAGE_NONE, CLIENT_TEST_STAGE_CONN, CLIENT_TEST_STAGE_DCONN, } client_test_stage_t; static void test_async_client_cb(const usb_host_client_event_msg_t *event_msg, void *arg) { client_test_stage_t *stage = (client_test_stage_t *)arg; switch (event_msg->event) { case USB_HOST_CLIENT_EVENT_NEW_DEV: if (dev_addr == 0) { dev_addr = event_msg->new_dev.address; } else { TEST_ASSERT_EQUAL(dev_addr, event_msg->new_dev.address); } *stage = CLIENT_TEST_STAGE_CONN; break; case USB_HOST_CLIENT_EVENT_DEV_GONE: *stage = CLIENT_TEST_STAGE_DCONN; break; default: abort(); break; } } TEST_CASE("Test USB Host async API", "[usb_host][ignore]") { test_usb_init_phy(); //Initialize the internal USB PHY and USB Controller for testing //Install USB Host usb_host_config_t host_config = { .skip_phy_setup = true, //test_usb_init_phy() will already have setup the internal USB PHY for us .intr_flags = ESP_INTR_FLAG_LEVEL1, }; ESP_ERROR_CHECK(usb_host_install(&host_config)); printf("Installed\n"); //Register two clients client_test_stage_t client0_stage = CLIENT_TEST_STAGE_NONE; client_test_stage_t client1_stage = CLIENT_TEST_STAGE_NONE; usb_host_client_config_t client_config = { .is_synchronous = false, .max_num_event_msg = 5, .async = { .client_event_callback = test_async_client_cb, .callback_arg = (void *)&client0_stage, }, }; usb_host_client_handle_t client0_hdl; usb_host_client_handle_t client1_hdl; TEST_ASSERT_EQUAL(ESP_OK, usb_host_client_register(&client_config, &client0_hdl)); client_config.async.callback_arg = (void *)&client1_stage; TEST_ASSERT_EQUAL(ESP_OK, usb_host_client_register(&client_config, &client1_hdl)); //Wait until the device connects and the clients receive the event while (!(client0_stage == CLIENT_TEST_STAGE_CONN && client1_stage == CLIENT_TEST_STAGE_CONN)) { usb_host_lib_handle_events(0, NULL); usb_host_client_handle_events(client0_hdl, 0); usb_host_client_handle_events(client1_hdl, 0); vTaskDelay(10); } //Check that both clients can open the device TEST_ASSERT_NOT_EQUAL(0, dev_addr); usb_device_handle_t client0_dev_hdl; usb_device_handle_t client1_dev_hdl; TEST_ASSERT_EQUAL(ESP_OK, usb_host_device_open(client0_hdl, dev_addr, &client0_dev_hdl)); TEST_ASSERT_EQUAL(ESP_OK, usb_host_device_open(client1_hdl, dev_addr, &client1_dev_hdl)); TEST_ASSERT_EQUAL(client0_dev_hdl, client1_dev_hdl); //Check that its the same device //Check that a client cannot open a non-existent device TEST_ASSERT_NOT_EQUAL(ESP_OK, usb_host_device_open(client0_hdl, 0, &client0_dev_hdl)); //Check that the device cannot be opened again by the same client usb_device_handle_t dummy_dev_hdl; TEST_ASSERT_NOT_EQUAL(ESP_OK, usb_host_device_open(client0_hdl, dev_addr, &dummy_dev_hdl)); TEST_ASSERT_NOT_EQUAL(ESP_OK, usb_host_device_open(client1_hdl, dev_addr, &dummy_dev_hdl)); //Check that both clients cannot claim the same interface TEST_ASSERT_EQUAL(ESP_OK, usb_host_interface_claim(client0_hdl, client0_dev_hdl, MOCK_MSC_SCSI_INTF_NUMBER, MOCK_MSC_SCSI_INTF_ALT_SETTING)); TEST_ASSERT_NOT_EQUAL(ESP_OK, usb_host_interface_claim(client1_hdl, client1_dev_hdl, MOCK_MSC_SCSI_INTF_NUMBER, MOCK_MSC_SCSI_INTF_ALT_SETTING)); //Check that client0 cannot claim the same interface multiple times TEST_ASSERT_NOT_EQUAL(ESP_OK, usb_host_interface_claim(client0_hdl, client0_dev_hdl, MOCK_MSC_SCSI_INTF_NUMBER, MOCK_MSC_SCSI_INTF_ALT_SETTING)); //Check that client0 can release the interface TEST_ASSERT_EQUAL(ESP_OK, usb_host_interface_release(client0_hdl, client0_dev_hdl, MOCK_MSC_SCSI_INTF_NUMBER)); //Check that client0 cannot release interface it has not claimed TEST_ASSERT_NOT_EQUAL(ESP_OK, usb_host_interface_release(client0_hdl, client0_dev_hdl, MOCK_MSC_SCSI_INTF_NUMBER)); //Wait until the device disconnects and the clients receive the event test_usb_set_phy_state(false, 0); while (!(client0_stage == CLIENT_TEST_STAGE_DCONN && client1_stage == CLIENT_TEST_STAGE_DCONN)) { usb_host_lib_handle_events(0, NULL); usb_host_client_handle_events(client0_hdl, 0); usb_host_client_handle_events(client1_hdl, 0); vTaskDelay(10); } TEST_ASSERT_EQUAL(ESP_OK, usb_host_device_close(client0_hdl, client0_dev_hdl)); TEST_ASSERT_EQUAL(ESP_OK, usb_host_device_close(client1_hdl, client1_dev_hdl)); //Deregister the clients TEST_ASSERT_EQUAL(ESP_OK, usb_host_client_deregister(client0_hdl)); TEST_ASSERT_EQUAL(ESP_OK, usb_host_client_deregister(client1_hdl)); while (1) { uint32_t event_flags; usb_host_lib_handle_events(0, &event_flags); if (event_flags & USB_HOST_LIB_EVENT_FLAGS_NO_CLIENTS) { break; } vTaskDelay(10); } //Cleanup TEST_ASSERT_EQUAL(ESP_OK, usb_host_uninstall()); test_usb_deinit_phy(); }
39.782468
149
0.719171
4c3c2064796795cd2352ae65431be18da269fefb
1,362
php
PHP
resources/views/pages/add-reservation.blade.php
MrGenQ/Laravel-Apartments
fdce26c4700fcb624ae096c26da7e96fe2208fff
[ "MIT" ]
null
null
null
resources/views/pages/add-reservation.blade.php
MrGenQ/Laravel-Apartments
fdce26c4700fcb624ae096c26da7e96fe2208fff
[ "MIT" ]
null
null
null
resources/views/pages/add-reservation.blade.php
MrGenQ/Laravel-Apartments
fdce26c4700fcb624ae096c26da7e96fe2208fff
[ "MIT" ]
null
null
null
@extends('main') @section('content') <div class="container"> <h2>Add new Apartment</h2> @include('_partials/errors') @include('_partials/success') <form action="/storeReservation" method="post"> @csrf <div class="form-group"> <input type="text" class="form-control" name="first_name" placeholder="Firstname" > </div> <div class="form-group"> <input type="text" class="form-control" name="last_name" placeholder="Lastname"> </div> <div class="form-group"> <input type="email" class="form-control" name="email" placeholder="example@example.com"> </div> <div class="form-group"> <input type="text" class="form-control" name="phone" placeholder="Suggestion use + sign"> </div> <div class="form-group"> <textarea class="form-control" name="message" placeholder="Your message"></textarea> </div> <div class="form-group"> <input type="datetime-local" class="form-controt" name="reserved_at"> </div> <div style="padding: 2em 0 0 0;"> <button type="submit" class="btn btn-success" >Save</button> </div> </form> </div> @endsection
40.058824
105
0.53304
fedc0e9ca4cf39a5da6c66b0a55a8030354e6303
2,994
kt
Kotlin
breeze-logger/src/main/kotlin/logger/impl/ColorfulLogger.kt
DragonKnightOfBreeze/breeze-framework
c418324b41aa517a7eb921589099c54ce7e160a6
[ "MIT" ]
8
2019-11-24T17:14:50.000Z
2021-12-17T03:11:51.000Z
breeze-logger/src/main/kotlin/logger/impl/ColorfulLogger.kt
DragonKnightOfBreeze/Breeze-Framework
e067f9e676fbb2fe2d4b5076e522edea63ce5a0f
[ "MIT" ]
null
null
null
breeze-logger/src/main/kotlin/logger/impl/ColorfulLogger.kt
DragonKnightOfBreeze/Breeze-Framework
e067f9e676fbb2fe2d4b5076e522edea63ce5a0f
[ "MIT" ]
1
2020-05-22T02:48:38.000Z
2020-05-22T02:48:38.000Z
// Copyright (c) 2020-2021 DragonKnightOfBreeze Windea // Breeze is blowing... @file:Suppress("DuplicatedCode") package icu.windea.breezeframework.logger.impl import icu.windea.breezeframework.logger.* import java.io.* import java.text.* import java.util.* /**输出彩色文本的日志器。这些彩色文本可在控制台正常显示。*/ class ColorfulLogger( override val config: LoggerConfig = LoggerConfig(), ) : Logger { constructor(block: LoggerConfig.() -> Unit) : this(LoggerConfig().apply(block)) override fun trace(message: Any?) = log(LogLevel.Trace, message) override fun trace(lazyMessage: () -> Any?) = log(LogLevel.Trace, lazyMessage()) override fun debug(message: Any?) = log(LogLevel.Debug, message) override fun debug(lazyMessage: () -> Any?) = log(LogLevel.Debug, lazyMessage()) override fun info(message: Any?) = log(LogLevel.Info, message) override fun info(lazyMessage: () -> Any?) = log(LogLevel.Info, lazyMessage()) override fun warn(message: Any?) = log(LogLevel.Warn, message) override fun warn(lazyMessage: () -> Any?) = log(LogLevel.Warn, lazyMessage) override fun error(message: Any?) = log(LogLevel.Error, message) override fun error(lazyMessage: () -> Any?) = log(LogLevel.Error, lazyMessage()) override fun fatal(message: Any?) = log(LogLevel.Fatal, message) override fun fatal(lazyMessage: () -> Any?) = log(LogLevel.Fatal, lazyMessage()) private fun log(level: LogLevel, message: Any?) { if(config.minLogLevel > level) return val levelSnippet = if(config.isLevelIncluded) level.text else null val dateSnippet = if(config.isDateIncluded) currentDate.let { "[$it]" } else null val pathSnippet = when { config.isPathIncluded && !config.isPathAbbreviated -> currentClassName config.isPathAbbreviated -> currentClassNameAbbreviation else -> null } val markersSnippet = arrayOf(dateSnippet, levelSnippet, pathSnippet).filterNotNull() .joinToString(" ", "", config.delimiter) val messageSnippet = message.toString() val logSnippet = "$markersSnippet$messageSnippet\n" config.outputPath?.let { File(it).appendText(logSnippet) } val (prefix, suffix) = level.colorCommandPair print(logSnippet.let { "$prefix$it$suffix" }) } private val currentDate get() = SimpleDateFormat(config.dateFormat).format(Date()) private val currentClassName get() = Exception().stackTrace[3].className private val currentClassNameAbbreviation get() = currentClassName.split(".").joinToString(".") { it.take(1) } + currentClassName.substring(currentClassName.lastIndexOf('.') + 2, currentClassName.length) private val LogLevel.colorCommandPair get() = when(this) { LogLevel.Off -> "" to "" LogLevel.Trace -> "\u001B[37m" to "\u001B[0m" //light gray LogLevel.Debug -> "\u001B[32m" to "\u001B[0m" //green LogLevel.Info -> "\u001B[34m" to "\u001B[0m" //blue LogLevel.Warn -> "\u001B[91m" to "\u001B[0m" //light red LogLevel.Error -> "\u001B[31m" to "\u001B[0m" //red LogLevel.Fatal -> "\u001B[31;4m" to "\u001B[0m" //red, underline } }
35.642857
93
0.714429
01fd370aa2741bbcf42c4f1339668c0ef55014bf
335
asm
Assembly
lab_06/output.asm
ak-karimzai/asm
e5433922cbb69cae3c03be86447e0e83fbd8cb0b
[ "Unlicense" ]
null
null
null
lab_06/output.asm
ak-karimzai/asm
e5433922cbb69cae3c03be86447e0e83fbd8cb0b
[ "Unlicense" ]
null
null
null
lab_06/output.asm
ak-karimzai/asm
e5433922cbb69cae3c03be86447e0e83fbd8cb0b
[ "Unlicense" ]
2
2021-06-07T06:29:31.000Z
2021-06-08T16:52:03.000Z
extern new_line:byte public print code_seg segment para public 'code' assume cs:code_seg start: print proc near mov dx, offset new_line mov ah, 09 int 21h mov dx, bx int 21h mov dx, offset new_line int 21h ret print endp code_seg ends end start
16.75
35
0.579104
5862af8639276c456276d4509f45aefee4037001
54
dart
Dart
enquete/lib/domain/helpers/domain_error.dart
CriandoGames/Flutter-Enquete
7714af92e828f8af92d99d3b7fc35e4028d7417d
[ "MIT" ]
1
2021-08-07T16:53:13.000Z
2021-08-07T16:53:13.000Z
enquete/lib/domain/helpers/domain_error.dart
CriandoGames/Flutter-Enquete
7714af92e828f8af92d99d3b7fc35e4028d7417d
[ "MIT" ]
null
null
null
enquete/lib/domain/helpers/domain_error.dart
CriandoGames/Flutter-Enquete
7714af92e828f8af92d99d3b7fc35e4028d7417d
[ "MIT" ]
null
null
null
enum DomainError{ unexpected, invalidCredentials }
13.5
20
0.796296
0e90caf2cd05d84184e857620c634171de7564e4
5,311
swift
Swift
WybroStarter/UIView+Extensions.swift
Wybro/WybroStarter
665e7d2511f11f461fc71dc0d59b7ca247ad17c7
[ "MIT" ]
1
2017-12-27T17:47:49.000Z
2017-12-27T17:47:49.000Z
WybroStarter/UIView+Extensions.swift
Wybro/WybroStarter
665e7d2511f11f461fc71dc0d59b7ca247ad17c7
[ "MIT" ]
null
null
null
WybroStarter/UIView+Extensions.swift
Wybro/WybroStarter
665e7d2511f11f461fc71dc0d59b7ca247ad17c7
[ "MIT" ]
null
null
null
// // UIView+Extensions.swift // WybroStarter // // Created by Connor Wybranowski on 10/21/17. // Copyright © 2017 wybro. All rights reserved. // import Foundation public enum LayoutType { case vertical, horizontal } public extension UIView { /** Prepares the receiver to use Auto Layout (sets `translatesAutoresizingMaskIntoConstraints` to **false**). */ public func usingConstraints() -> UIView { self.translatesAutoresizingMaskIntoConstraints = false return self } /** Adds a provided view to the receiver's subviews using constraints. */ public func addSubviewForLayout(_ view: UIView) { self.addSubview(view.usingConstraints()) } /** Adds the provided views to the receiver's subviews using constraints. */ public func addSubviewsForLayout(_ views: [UIView]) { views.forEach { addSubviewForLayout($0) } } /** Centers the view in the provided superview vertically or horizontally, with optional offset. */ public func center(in superview: UIView, type: LayoutType, offset: CGFloat = 0) -> NSLayoutConstraint { return NSLayoutConstraint(item: self, attribute: (type == .horizontal) ? .centerX : .centerY, relatedBy: .equal, toItem: superview, attribute: (type == .horizontal) ? .centerX : .centerY, multiplier: 1, constant: offset) } /** Centers the view in the provided superview vertically and horizontally, with optional offset. */ public func center(in superview: UIView, xOffset: CGFloat = 0, yOffset: CGFloat = 0) -> [NSLayoutConstraint] { let vertical = center(in: superview, type: .vertical, offset: yOffset) let horizontal = center(in: superview, type: .horizontal, offset: xOffset) return [vertical, horizontal] } /** Fills the view in the provided superview vertically or horizontally, with optional padding on each side. */ public func fill(_ direction: LayoutType, in superview: UIView, padding: CGFloat = 0) -> [NSLayoutConstraint] { let first = NSLayoutConstraint(item: self, attribute: direction == .vertical ? .top : .leading, relatedBy: .equal, toItem: superview, attribute: direction == .vertical ? .top : .leading, multiplier: 1, constant: padding) let second = NSLayoutConstraint(item: self, attribute: direction == .vertical ? .bottom : .trailing, relatedBy: .equal, toItem: superview, attribute: direction == .vertical ? .bottom : .trailing, multiplier: 1, constant: -padding) return [first, second] } /** Fills the view in the provided superview vertically and horizontally, with optional padding on each side. */ public func fill(in superview: UIView, padding: CGFloat = 0) -> [NSLayoutConstraint] { let vertical = self.fill(.vertical, in: superview, padding: padding) let horizontal = self.fill(.horizontal, in: superview, padding: padding) return [vertical, horizontal].flatMap { $0 } } } public extension Array where Element == UIView { /** Centers all views in the provided superview vertically or horizontally, with optional offset. */ public func center(in superview: UIView, type: LayoutType, offset: CGFloat = 0) -> [NSLayoutConstraint] { return self.map { $0.center(in: superview, type: type, offset: offset) } } /** Centers all views in the provided superview vertically and horizontally, with optional offset. */ public func center(in superview: UIView, xOffset: CGFloat = 0, yOffset: CGFloat = 0) -> [NSLayoutConstraint] { return self.map { $0.center(in: superview, xOffset: xOffset, yOffset: yOffset) }.flatMap { $0 } } /** Fills all views in the provided superview vertically or horizontally, with optional padding on each side. */ public func fill(_ direction: LayoutType, in superview: UIView, padding: CGFloat = 0) -> [NSLayoutConstraint] { return self.map { $0.fill(direction, in: superview, padding: padding) }.flatMap { $0 } } /** Fills all views in the provided superview vertically and horizontally, with optional padding on each side. */ public func fill(in superview: UIView, padding: CGFloat = 0) -> [NSLayoutConstraint] { return self.map { $0.fill(in: superview, padding: padding) }.flatMap { $0 } } }
38.485507
115
0.556016
13431ef40e86eaa4de020d6a0720301d8dda0910
230
h
C
Example/ez_updater/EZViewController.h
haroel/ez_updater
bda333d9be05d8f941943eff1fb2a607a74e309c
[ "MIT" ]
1
2021-07-30T03:38:27.000Z
2021-07-30T03:38:27.000Z
Example/ez_updater/EZViewController.h
haroel/ez_updater
bda333d9be05d8f941943eff1fb2a607a74e309c
[ "MIT" ]
null
null
null
Example/ez_updater/EZViewController.h
haroel/ez_updater
bda333d9be05d8f941943eff1fb2a607a74e309c
[ "MIT" ]
null
null
null
// // EZViewController.h // ez_updater // // Created by whzsgame@gmail.com on 10/27/2020. // Copyright (c) 2020 whzsgame@gmail.com. All rights reserved. // @import UIKit; @interface EZViewController : UIViewController @end
16.428571
63
0.713043
3a87741e904fc42f6ea6ff7175584cfa8d823ea0
337
kt
Kotlin
app/src/main/java/pl/dawidfiruzek/kursandroid/utils/api/ReposService.kt
dawidfiruzek/Kurs-Android
aea5e18e07522ca32753a04a6464e6e801bf175c
[ "Apache-2.0" ]
null
null
null
app/src/main/java/pl/dawidfiruzek/kursandroid/utils/api/ReposService.kt
dawidfiruzek/Kurs-Android
aea5e18e07522ca32753a04a6464e6e801bf175c
[ "Apache-2.0" ]
null
null
null
app/src/main/java/pl/dawidfiruzek/kursandroid/utils/api/ReposService.kt
dawidfiruzek/Kurs-Android
aea5e18e07522ca32753a04a6464e6e801bf175c
[ "Apache-2.0" ]
null
null
null
package pl.dawidfiruzek.kursandroid.utils.api import io.reactivex.Observable import pl.dawidfiruzek.kursandroid.data.api.RepositoriesResponse import retrofit2.http.GET import retrofit2.http.Path interface ReposService { @GET("users/{user}/repos") fun repos(@Path("user") user: String): Observable<List<RepositoriesResponse>> }
28.083333
81
0.795252
65264a551191e1547fd7e759779ff58b0d68fe03
4,400
dart
Dart
lib/main.dart
Simperfy/COVID-19-PH-DOH
07eacd137d11dfd6aecce84fb9594afe7fafa05a
[ "MIT" ]
4
2020-08-14T18:00:36.000Z
2021-04-06T16:14:34.000Z
lib/main.dart
Simperfy/COVID-19-PH-DOH
07eacd137d11dfd6aecce84fb9594afe7fafa05a
[ "MIT" ]
3
2020-08-17T15:43:20.000Z
2020-08-18T15:05:54.000Z
lib/main.dart
Simperfy/COVID-19-PH-DOH
07eacd137d11dfd6aecce84fb9594afe7fafa05a
[ "MIT" ]
1
2020-08-14T17:25:03.000Z
2020-08-14T17:25:03.000Z
import 'package:Covid19_PH/services/hospital_database.dart'; import 'package:Covid19_PH/services/record_database.dart'; import 'package:Covid19_PH/services/region_database.dart'; import 'package:Covid19_PH/services/summary_database.dart'; import 'package:Covid19_PH/services/timeline_database.dart'; import 'package:Covid19_PH/ui/view_manager.dart'; import 'package:Covid19_PH/util/size_config.dart'; import 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: LayoutBuilder(builder: (context, constraints) { SizeConfig.init(constraints); return ViewManager(); }), ); } } //Sample use of database Future<void> testDb() async { SummaryDatabase summaryDatabase = SummaryDatabase.instance; HospitalDatabase hospitalDatabase = HospitalDatabase.instance; RegionDatabase regionDatabase = RegionDatabase.instance; RecordDatabase recordDatabase = RecordDatabase.instance; TimelineDatabase timelineDatabase = TimelineDatabase.instance; try { var summary = await summaryDatabase.getSummary(); print('summary : $summary \n'); print('summary data: ${summary.getData()}'); print('\n\n\n'); var regionSummary = await summaryDatabase.getRegionSummary(region: 'ncr'); print('regionSummary : $regionSummary \n'); print('regionSummary data : ${regionSummary.getData()}'); print('\n\n\n'); var topRegions = await regionDatabase.getTopRegions(); print('topRegions : $topRegions \n'); print('topRegions region #1 : ${topRegions.getData().regionList.first}'); print('\n\n\n'); var caseTimeline = await timelineDatabase.getCasesTimeline(); print('caseTimeline : $caseTimeline\n'); print('caseTimeline case #1 : ${caseTimeline.getData().caseList.first}'); print('\n\n\n'); var fetchRecord = await recordDatabase.fetchRecord(pageNumber: 1, limit: 5); print('fetchRecord : $fetchRecord\n'); print('fetchRecord record #1 : ${fetchRecord.getData().recordList.first}'); print('\n\n\n'); var fetchRecordByAge = await recordDatabase.fetchRecordByAge(age: 30); print('fetchRecordByAge : $fetchRecordByAge\n'); if (fetchRecordByAge.getData().recordList.isNotEmpty) { print( 'fetchRecordByAge record #1 : ${fetchRecordByAge.getData().recordList.first}'); } print('\n\n\n'); var fetchRecordByAgeGroup = await recordDatabase.fetchRecordByAgeGroup(minAge: 20, maxAge: 24); print('fetchRecordByAgeGroup : $fetchRecordByAgeGroup\n'); if (fetchRecordByAgeGroup.getData().recordList.isNotEmpty) { print( 'fetchRecordByAgeGroup record #1 : ${fetchRecordByAgeGroup.getData().recordList.first}'); } print('\n\n\n'); var fetchRecordByMonth = await recordDatabase.fetchRecordByMonth(monthNumber: 5); print('fetchRecordByMonth : $fetchRecordByMonth\n'); if (fetchRecordByMonth.getData().recordList.isNotEmpty) { print( 'fetchRecordByMonth record #1: ${fetchRecordByMonth.getData().recordList.first}'); } print('\n\n\n'); var fetchRecordByRegion = await recordDatabase.fetchRecordByRegion(region: 'ncr'); print('fetchRecordByRegion : $fetchRecordByRegion\n'); if (fetchRecordByRegion.getData().recordList.isNotEmpty) { print( 'fetchRecordByRegion record #1: ${fetchRecordByRegion.getData().recordList.first}'); } print('\n\n\n'); var fetchHospitalRecords = await hospitalDatabase.fetchHospitalRecords(); print('fetchHospitalRecords : $fetchHospitalRecords \n'); if (fetchHospitalRecords.getData().hospitalList.isNotEmpty) { print( 'fetchHospitalRecords record #1: ${fetchHospitalRecords.getData().hospitalList.first}'); } // TODO: @DOGGO model updates forgot to (add timelineRegion[cause it's in the other branch]) print('\n\n\n'); var fetchHospitalRecordsSummary = await hospitalDatabase.fetchHospitalRecordsSummary(); print('fetchHospitalRecordsSummary : $fetchHospitalRecordsSummary \n'); if (fetchHospitalRecordsSummary.getData()) { print( 'fetchHospitalRecordsSummary record #1: ${fetchHospitalRecordsSummary.getData().hospitalList.first}'); } } catch (e) { print(e); print('missing data in api'); } }
35.772358
112
0.706136
90fcfd3bc6e9ddd7a032985039348959e97e84a0
417
py
Python
rest_api_service_fastapi/test_debug.py
aishwaryashand/Task1
8c422d600ce44d60d4951e3e567da7e22a1f51fc
[ "Apache-2.0" ]
null
null
null
rest_api_service_fastapi/test_debug.py
aishwaryashand/Task1
8c422d600ce44d60d4951e3e567da7e22a1f51fc
[ "Apache-2.0" ]
null
null
null
rest_api_service_fastapi/test_debug.py
aishwaryashand/Task1
8c422d600ce44d60d4951e3e567da7e22a1f51fc
[ "Apache-2.0" ]
null
null
null
def test_debug(): from app_utils import create_access_token from datetime import timedelta access_token_expires = timedelta(minutes=10) access_token = create_access_token(data={"sub": "cuongld"}, expires_delta=access_token_expires) print(access_token) from app_utils import decode_access_token decoded_access_token = decode_access_token(data=access_token) print(decoded_access_token)
37.909091
99
0.788969
2a1929885f17e944037f34951eaae54e94a30b9e
4,350
java
Java
app/src/main/java/mod/hey/studios/moreblock/MoreblockValidator.java
Ninjacoderhsi/SketchwareCraft
8f1b9254fc04820e2dd3ca89a0aed4eed2e25071
[ "Apache-2.0" ]
1
2022-02-19T12:17:34.000Z
2022-02-19T12:17:34.000Z
app/src/main/java/mod/hey/studios/moreblock/MoreblockValidator.java
Ninjacoderhsi/SketchwareCraft
8f1b9254fc04820e2dd3ca89a0aed4eed2e25071
[ "Apache-2.0" ]
null
null
null
app/src/main/java/mod/hey/studios/moreblock/MoreblockValidator.java
Ninjacoderhsi/SketchwareCraft
8f1b9254fc04820e2dd3ca89a0aed4eed2e25071
[ "Apache-2.0" ]
null
null
null
package mod.hey.studios.moreblock; import android.content.Context; import android.text.Spanned; import com.google.android.material.textfield.TextInputLayout; import java.util.ArrayList; import java.util.regex.Pattern; import a.a.a.MB; import a.a.a.xB; public class MoreblockValidator extends MB { public String[] f; public String[] g; public ArrayList<String> h; public String i; public Pattern j = Pattern.compile("^[a-zA-Z][a-zA-Z0-9_<>,|\\[\\] ]*"); public MoreblockValidator(Context context, TextInputLayout textInputLayout, String[] strArr, String[] strArr2, ArrayList<String> arrayList) { super(context, textInputLayout); f = strArr; g = strArr2; h = arrayList; } public void a(String[] strArr) { g = strArr; } public CharSequence filter(CharSequence charSequence, int i2, int i3, Spanned spanned, int i4, int i5) { return null; } public void onTextChanged(CharSequence charSequence, int i2, int i3, int i4) { boolean z; boolean z2; int length = charSequence.toString().trim().length(); int num = 1; if (length < 1) { b.setErrorEnabled(true); xB b = xB.b(); Object[] objArr = new Object[1]; objArr[0] = num; this.b.setError(b.a(a, 2131625433, objArr)); d = false; } else if (charSequence.toString().trim().length() > 60) { b.setErrorEnabled(true); xB b2 = xB.b(); Object[] objArr2 = new Object[1]; objArr2[0] = 60; b.setError(b2.a(a, 2131625432, objArr2)); d = false; } else { if (i != null && i.length() > 0 && charSequence.toString().equals(i)) { b.setErrorEnabled(false); d = true; } else if (h.contains(charSequence.toString())) { b.setErrorEnabled(true); b.setError(xB.b().a(a, 2131624950, new Object[0])); d = false; } else { int length2 = g.length; int i5 = 0; while (true) { if (i5 >= length2) { z = false; break; } if (charSequence.toString().equals(g[i5])) { z = true; break; } i5++; } if (z) { b.setErrorEnabled(true); b.setError(xB.b().a(a, 2131624950, new Object[0])); d = false; return; } int length3 = f.length; int i6 = 0; while (true) { if (i6 >= length3) { z2 = false; break; } if (charSequence.toString().equals(f[i6])) { z2 = true; break; } i6++; } if (z2) { b.setErrorEnabled(true); b.setError(xB.b().a(a, 2131625495, new Object[0])); d = false; } else if (!Character.isLetter(charSequence.charAt(0))) { b.setErrorEnabled(true); b.setError(xB.b().a(a, 2131625497, new Object[0])); d = false; } else { if (j.matcher(charSequence.toString()).matches()) { b.setErrorEnabled(false); d = true; } else { b.setErrorEnabled(true); b.setError(xB.b().a(a, 2131625436, new Object[0])); d = false; } if (charSequence.toString().trim().length() < 1) { b.setErrorEnabled(true); xB b3 = xB.b(); Object[] objArr3 = new Object[1]; objArr3[0] = num; b.setError(b3.a(a, 2131625433, objArr3)); d = false; } } } } } }
34.251969
145
0.427816
864766b89a8eb563fe4cc02af3d9593a30fc6e5f
4,498
rs
Rust
rest_api/src/errors.rs
agunde406/consensource
d8f7cd607e992577b5ad445ed5e7686878d16127
[ "ECL-2.0", "Apache-2.0", "MIT" ]
null
null
null
rest_api/src/errors.rs
agunde406/consensource
d8f7cd607e992577b5ad445ed5e7686878d16127
[ "ECL-2.0", "Apache-2.0", "MIT" ]
null
null
null
rest_api/src/errors.rs
agunde406/consensource
d8f7cd607e992577b5ad445ed5e7686878d16127
[ "ECL-2.0", "Apache-2.0", "MIT" ]
null
null
null
use rocket::http::ContentType; use rocket::http::Status; use rocket::request::Request; use rocket::response::{Responder, Response}; use rocket_contrib::{Json, Value}; use std::io::Cursor; #[catch(404)] pub fn not_found() -> Json<Value> { Json(json!({ "error": { "status": Status::NotFound.code, "message": "Not found" } })) } #[catch(500)] pub fn internal_error() -> Json<Value> { Json(json!({ "error": { "status": Status::InternalServerError.code, "message": "Internal error" } })) } #[catch(503)] pub fn service_unavailable() -> Json<Value> { Json(json!({ "error": { "status": Status::ServiceUnavailable.code, "message": "Service unavailable" } })) } #[derive(Debug)] pub enum ApiError { /// Defines the HTTP Errors that the API can return. BadRequest(String), InternalError(String), NotFound(String), TooManyRequests(String), ServiceUnavailable, Unauthorized, } impl<'r> Responder<'r> for ApiError { /// JSON responder for ApiErrors. fn respond_to(self, _req: &Request) -> Result<Response<'r>, Status> { match self { ApiError::BadRequest(ref msg) => Response::build() .header(ContentType::JSON) .status(Status::BadRequest) .sized_body(Cursor::new( json!({ "error": { "status": Status::BadRequest.code, "message": format!("Bad request: {}", msg), } }) .to_string(), )) .ok(), ApiError::InternalError(ref msg) => Response::build() .header(ContentType::JSON) .status(Status::InternalServerError) .sized_body(Cursor::new( json!({ "error": { "status": Status::InternalServerError.code, "message": format!("Internal error: {}", msg), } }) .to_string(), )) .ok(), ApiError::NotFound(ref msg) => Response::build() .header(ContentType::JSON) .status(Status::NotFound) .sized_body(Cursor::new( json!({ "error": { "status": Status::NotFound.code, "message": format!("Not found: {}", msg), } }) .to_string(), )) .ok(), ApiError::TooManyRequests(ref msg) => Response::build() .header(ContentType::JSON) .status(Status::TooManyRequests) .sized_body(Cursor::new( json!({ "error": { "status": Status::TooManyRequests.code, "message": format!("Too many requests: {}", msg), } }) .to_string(), )) .ok(), ApiError::ServiceUnavailable => Response::build() .header(ContentType::JSON) .status(Status::ServiceUnavailable) .sized_body(Cursor::new( json!({ "error": { "status": Status::ServiceUnavailable.code, "message": "Service Unavailable", } }) .to_string(), )) .ok(), ApiError::Unauthorized => Response::build() .header(ContentType::JSON) .status(Status::Unauthorized) .sized_body(Cursor::new( json!({ "error": { "status": Status::Unauthorized.code, "message": "Unauthorized!", } }) .to_string(), )) .ok(), } } } impl From<::diesel::result::Error> for ApiError { fn from(err: ::diesel::result::Error) -> Self { ApiError::InternalError(err.to_string()) } }
32.128571
77
0.418853
16816556d713fd85d0475ef1a679414fcbf283ac
743
ts
TypeScript
src/app/admin/customers/customers.module.ts
dmkuchynski/MAVN.FrontEnd.BackOffice
32c3a80ab77c463cf4cce9552b3c533c67308eeb
[ "MIT" ]
null
null
null
src/app/admin/customers/customers.module.ts
dmkuchynski/MAVN.FrontEnd.BackOffice
32c3a80ab77c463cf4cce9552b3c533c67308eeb
[ "MIT" ]
null
null
null
src/app/admin/customers/customers.module.ts
dmkuchynski/MAVN.FrontEnd.BackOffice
32c3a80ab77c463cf4cce9552b3c533c67308eeb
[ "MIT" ]
null
null
null
import {CustomersService} from './customers.service'; import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {CustomersRoutingModule} from './customers-routing.module'; import {CustomersListPageComponent} from './customers-list-page/customers-list-page.component'; import {SharedModule} from 'src/app/shared/shared.module'; import {CustomerDetailsPageComponent} from './customer-details-page/customer-details-page.component'; import {FormsModule} from '@angular/forms'; @NgModule({ declarations: [CustomersListPageComponent, CustomerDetailsPageComponent], imports: [CommonModule, CustomersRoutingModule, FormsModule, SharedModule], providers: [CustomersService] }) export class CustomersModule {}
43.705882
101
0.79677
7ba2d450b3d4babb61882d7d9d05cc016580f01e
2,476
dart
Dart
lib/app/modules/poke_detail/controllers/status_tab_controller.dart
danieldcastro/pokedex
f170f9542e1121a0426d359d6fa9894afd9c7718
[ "MIT" ]
3
2021-07-15T23:56:09.000Z
2022-03-18T23:14:23.000Z
lib/app/modules/poke_detail/controllers/status_tab_controller.dart
danieldcastro/pokedex
f170f9542e1121a0426d359d6fa9894afd9c7718
[ "MIT" ]
null
null
null
lib/app/modules/poke_detail/controllers/status_tab_controller.dart
danieldcastro/pokedex
f170f9542e1121a0426d359d6fa9894afd9c7718
[ "MIT" ]
null
null
null
import 'package:get/get.dart'; import '../../../data/provider/poke_api_provider.dart'; import '../../../data/repository/poke_api_repository.dart'; import 'poke_detail_controller.dart'; class StatusTabController extends GetxController with StateMixin { PokeDetailController pokeDetailController = Get.find(); final PokeApiRepository _pokeApiRepository = PokeApiRepository(pokeApiProvider: PokeApiProvider()); onInit() { super.onInit(); getPokeInfo(); } getPokeInfo() { change([], status: RxStatus.loading()); _pokeApiRepository .getPokeInfo(pokeDetailController .allPoke[pokeDetailController.current.value].name) .then((data) { change(data, status: RxStatus.success()); }, onError: (e) { print(e); change([], status: RxStatus.error('Deu ruim! Bora tentar mais uma vez?')); }); } List<int> getPokeStatus() { List<int> list = [1, 2, 3, 4, 5, 6, 7]; int sum = 0; state.stats.forEach((f) { sum = sum + f.baseStat; switch (f.stat.name) { case 'hp': list[0] = f.baseStat; break; case 'attack': list[1] = f.baseStat; break; case 'defense': list[2] = f.baseStat; break; case 'special-attack': list[3] = f.baseStat; break; case 'special-defense': list[4] = f.baseStat; break; case 'speed': list[5] = f.baseStat; break; } }); list[6] = sum; return list; } String listPokeAbility() { List _list = []; String abilities = ''; state.abilities.forEach((element) { _list.add(element.ability.name[0].toUpperCase() + element.ability.name.substring(1)); }); abilities = _list.toString().replaceAll('[', '').replaceAll(']', ''); return abilities; } String listPokeForm() { List _list = []; String forms = ''; state.forms.forEach((element) { _list.add(element.name[0].toUpperCase() + element.name.substring(1)); }); forms = _list.toString().replaceAll('[', '').replaceAll(']', ''); return forms; } String listPokeMove() { List _list = []; String moves = ''; state.moves.forEach((element) { _list.add( element.move.name[0].toUpperCase() + element.move.name.substring(1)); }); moves = _list.toString().replaceAll('[', '').replaceAll(']', ''); return moves; } }
25.010101
80
0.573102
ae72c6c69431aab1f573ce5daefecb17d279d330
23,525
dart
Dart
lib/src/android/com/baidu/mapapi/search/route/MassTransitRoutePlanOption.g.dart
yohom/bmap_map_fluttify
5cf8728b1eccd948d3487aace85d5f2349828285
[ "Apache-2.0" ]
null
null
null
lib/src/android/com/baidu/mapapi/search/route/MassTransitRoutePlanOption.g.dart
yohom/bmap_map_fluttify
5cf8728b1eccd948d3487aace85d5f2349828285
[ "Apache-2.0" ]
null
null
null
lib/src/android/com/baidu/mapapi/search/route/MassTransitRoutePlanOption.g.dart
yohom/bmap_map_fluttify
5cf8728b1eccd948d3487aace85d5f2349828285
[ "Apache-2.0" ]
null
null
null
// ignore_for_file: non_constant_identifier_names, camel_case_types, missing_return, unused_import, unused_local_variable, dead_code, unnecessary_cast ////////////////////////////////////////////////////////// // GENERATED BY FLUTTIFY. DO NOT EDIT IT. ////////////////////////////////////////////////////////// import 'dart:typed_data'; import 'package:bmap_map_fluttify/src/android/android.export.g.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:foundation_fluttify/foundation_fluttify.dart'; import 'package:core_location_fluttify/core_location_fluttify.dart'; class com_baidu_mapapi_search_route_MassTransitRoutePlanOption extends java_lang_Object { //region constants static const String name__ = 'com.baidu.mapapi.search.route.MassTransitRoutePlanOption'; @override final String tag__ = 'bmap_map_fluttify'; //endregion //region creators static Future<com_baidu_mapapi_search_route_MassTransitRoutePlanOption> create__() async { final __result__ = await kBmapMapFluttifyChannel.invokeMethod( 'ObjectFactory::createcom_baidu_mapapi_search_route_MassTransitRoutePlanOption__', ); return BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>(__result__); } static Future<List<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>> create_batch__(int length) async { assert(true); final __result_batch__ = await kBmapMapFluttifyChannel.invokeListMethod( 'ObjectFactory::create_batchcom_baidu_mapapi_search_route_MassTransitRoutePlanOption__', {'length': length} ); return __result_batch__ .map((it) => BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>(it)) .toList(); } //endregion //region getters Future<com_baidu_mapapi_search_route_PlanNode> get_mFrom() async { final __result__ = await kBmapMapFluttifyChannel.invokeMethod("com.baidu.mapapi.search.route.MassTransitRoutePlanOption::get_mFrom", {'__this__': this}); return BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_PlanNode>(__result__); } Future<com_baidu_mapapi_search_route_PlanNode> get_mTo() async { final __result__ = await kBmapMapFluttifyChannel.invokeMethod("com.baidu.mapapi.search.route.MassTransitRoutePlanOption::get_mTo", {'__this__': this}); return BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_PlanNode>(__result__); } Future<String> get_mCoordType() async { final __result__ = await kBmapMapFluttifyChannel.invokeMethod("com.baidu.mapapi.search.route.MassTransitRoutePlanOption::get_mCoordType", {'__this__': this}); return __result__; } Future<com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TacticsIncity> get_mTacticsIncity() async { final __result__ = await kBmapMapFluttifyChannel.invokeMethod("com.baidu.mapapi.search.route.MassTransitRoutePlanOption::get_mTacticsIncity", {'__this__': this}); return (__result__ as int).tocom_baidu_mapapi_search_route_MassTransitRoutePlanOption_TacticsIncity(); } Future<com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TacticsIntercity> get_mTacticsIntercity() async { final __result__ = await kBmapMapFluttifyChannel.invokeMethod("com.baidu.mapapi.search.route.MassTransitRoutePlanOption::get_mTacticsIntercity", {'__this__': this}); return (__result__ as int).tocom_baidu_mapapi_search_route_MassTransitRoutePlanOption_TacticsIntercity(); } Future<com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TransTypeIntercity> get_mTransTypeIntercity() async { final __result__ = await kBmapMapFluttifyChannel.invokeMethod("com.baidu.mapapi.search.route.MassTransitRoutePlanOption::get_mTransTypeIntercity", {'__this__': this}); return (__result__ as int).tocom_baidu_mapapi_search_route_MassTransitRoutePlanOption_TransTypeIntercity(); } Future<int> get_mPageSize() async { final __result__ = await kBmapMapFluttifyChannel.invokeMethod("com.baidu.mapapi.search.route.MassTransitRoutePlanOption::get_mPageSize", {'__this__': this}); return __result__; } Future<int> get_mPageIndex() async { final __result__ = await kBmapMapFluttifyChannel.invokeMethod("com.baidu.mapapi.search.route.MassTransitRoutePlanOption::get_mPageIndex", {'__this__': this}); return __result__; } //endregion //region setters Future<void> set_mFrom(com_baidu_mapapi_search_route_PlanNode mFrom) async { await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::set_mFrom', <String, dynamic>{'__this__': this, "mFrom": mFrom}); } Future<void> set_mTo(com_baidu_mapapi_search_route_PlanNode mTo) async { await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::set_mTo', <String, dynamic>{'__this__': this, "mTo": mTo}); } Future<void> set_mCoordType(String mCoordType) async { await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::set_mCoordType', <String, dynamic>{'__this__': this, "mCoordType": mCoordType}); } Future<void> set_mTacticsIncity(com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TacticsIncity mTacticsIncity) async { await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::set_mTacticsIncity', <String, dynamic>{'__this__': this, "mTacticsIncity": mTacticsIncity.toValue()}); } Future<void> set_mTacticsIntercity(com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TacticsIntercity mTacticsIntercity) async { await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::set_mTacticsIntercity', <String, dynamic>{'__this__': this, "mTacticsIntercity": mTacticsIntercity.toValue()}); } Future<void> set_mTransTypeIntercity(com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TransTypeIntercity mTransTypeIntercity) async { await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::set_mTransTypeIntercity', <String, dynamic>{'__this__': this, "mTransTypeIntercity": mTransTypeIntercity.toValue()}); } Future<void> set_mPageSize(int mPageSize) async { await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::set_mPageSize', <String, dynamic>{'__this__': this, "mPageSize": mPageSize}); } Future<void> set_mPageIndex(int mPageIndex) async { await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::set_mPageIndex', <String, dynamic>{'__this__': this, "mPageIndex": mPageIndex}); } //endregion //region methods Future<com_baidu_mapapi_search_route_MassTransitRoutePlanOption> from(com_baidu_mapapi_search_route_PlanNode var1) async { // print log if (fluttifyLogEnabled) { debugPrint('fluttify-dart: com.baidu.mapapi.search.route.MassTransitRoutePlanOption@$refId::from([])'); } // invoke native method final __result__ = await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::from', {"var1": var1, "__this__": this}); // handle native call return BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>(__result__); } @deprecated Future<com_baidu_mapapi_search_route_MassTransitRoutePlanOption> coordType(String var1) async { // print log if (fluttifyLogEnabled) { debugPrint('fluttify-dart: com.baidu.mapapi.search.route.MassTransitRoutePlanOption@$refId::coordType([\'var1\':$var1])'); } // invoke native method final __result__ = await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::coordType', {"var1": var1, "__this__": this}); // handle native call return BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>(__result__); } Future<com_baidu_mapapi_search_route_MassTransitRoutePlanOption> tacticsIncity(com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TacticsIncity var1) async { // print log if (fluttifyLogEnabled) { debugPrint('fluttify-dart: com.baidu.mapapi.search.route.MassTransitRoutePlanOption@$refId::tacticsIncity([])'); } // invoke native method final __result__ = await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::tacticsIncity', {"var1": var1.toValue(), "__this__": this}); // handle native call return BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>(__result__); } Future<com_baidu_mapapi_search_route_MassTransitRoutePlanOption> tacticsIntercity(com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TacticsIntercity var1) async { // print log if (fluttifyLogEnabled) { debugPrint('fluttify-dart: com.baidu.mapapi.search.route.MassTransitRoutePlanOption@$refId::tacticsIntercity([])'); } // invoke native method final __result__ = await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::tacticsIntercity', {"var1": var1.toValue(), "__this__": this}); // handle native call return BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>(__result__); } Future<com_baidu_mapapi_search_route_MassTransitRoutePlanOption> transtypeintercity(com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TransTypeIntercity var1) async { // print log if (fluttifyLogEnabled) { debugPrint('fluttify-dart: com.baidu.mapapi.search.route.MassTransitRoutePlanOption@$refId::transtypeintercity([])'); } // invoke native method final __result__ = await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::transtypeintercity', {"var1": var1.toValue(), "__this__": this}); // handle native call return BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>(__result__); } Future<com_baidu_mapapi_search_route_MassTransitRoutePlanOption> pageSize(int var1) async { // print log if (fluttifyLogEnabled) { debugPrint('fluttify-dart: com.baidu.mapapi.search.route.MassTransitRoutePlanOption@$refId::pageSize([\'var1\':$var1])'); } // invoke native method final __result__ = await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::pageSize', {"var1": var1, "__this__": this}); // handle native call return BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>(__result__); } Future<com_baidu_mapapi_search_route_MassTransitRoutePlanOption> pageIndex(int var1) async { // print log if (fluttifyLogEnabled) { debugPrint('fluttify-dart: com.baidu.mapapi.search.route.MassTransitRoutePlanOption@$refId::pageIndex([\'var1\':$var1])'); } // invoke native method final __result__ = await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::pageIndex', {"var1": var1, "__this__": this}); // handle native call return BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>(__result__); } //endregion @override String toString() { return 'com_baidu_mapapi_search_route_MassTransitRoutePlanOption{refId: $refId, runtimeType: $runtimeType, tag__: $tag__}'; } } extension com_baidu_mapapi_search_route_MassTransitRoutePlanOption_Batch on List<com_baidu_mapapi_search_route_MassTransitRoutePlanOption> { //region getters Future<List<com_baidu_mapapi_search_route_PlanNode>> get_mFrom_batch() async { final resultBatch = await kBmapMapFluttifyChannel.invokeMethod("com.baidu.mapapi.search.route.MassTransitRoutePlanOption::get_mFrom_batch", [for (final __item__ in this) {'__this__': __item__}]); return (resultBatch as List)?.map((__result__) => BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_PlanNode>(__result__))?.cast<com_baidu_mapapi_search_route_PlanNode>()?.toList(); } Future<List<com_baidu_mapapi_search_route_PlanNode>> get_mTo_batch() async { final resultBatch = await kBmapMapFluttifyChannel.invokeMethod("com.baidu.mapapi.search.route.MassTransitRoutePlanOption::get_mTo_batch", [for (final __item__ in this) {'__this__': __item__}]); return (resultBatch as List)?.map((__result__) => BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_PlanNode>(__result__))?.cast<com_baidu_mapapi_search_route_PlanNode>()?.toList(); } Future<List<String>> get_mCoordType_batch() async { final resultBatch = await kBmapMapFluttifyChannel.invokeMethod("com.baidu.mapapi.search.route.MassTransitRoutePlanOption::get_mCoordType_batch", [for (final __item__ in this) {'__this__': __item__}]); return (resultBatch as List)?.map((__result__) => __result__)?.cast<String>()?.toList(); } Future<List<com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TacticsIncity>> get_mTacticsIncity_batch() async { final resultBatch = await kBmapMapFluttifyChannel.invokeMethod("com.baidu.mapapi.search.route.MassTransitRoutePlanOption::get_mTacticsIncity_batch", [for (final __item__ in this) {'__this__': __item__}]); return (resultBatch as List)?.map((__result__) => (__result__ as int).tocom_baidu_mapapi_search_route_MassTransitRoutePlanOption_TacticsIncity())?.cast<com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TacticsIncity>()?.toList(); } Future<List<com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TacticsIntercity>> get_mTacticsIntercity_batch() async { final resultBatch = await kBmapMapFluttifyChannel.invokeMethod("com.baidu.mapapi.search.route.MassTransitRoutePlanOption::get_mTacticsIntercity_batch", [for (final __item__ in this) {'__this__': __item__}]); return (resultBatch as List)?.map((__result__) => (__result__ as int).tocom_baidu_mapapi_search_route_MassTransitRoutePlanOption_TacticsIntercity())?.cast<com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TacticsIntercity>()?.toList(); } Future<List<com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TransTypeIntercity>> get_mTransTypeIntercity_batch() async { final resultBatch = await kBmapMapFluttifyChannel.invokeMethod("com.baidu.mapapi.search.route.MassTransitRoutePlanOption::get_mTransTypeIntercity_batch", [for (final __item__ in this) {'__this__': __item__}]); return (resultBatch as List)?.map((__result__) => (__result__ as int).tocom_baidu_mapapi_search_route_MassTransitRoutePlanOption_TransTypeIntercity())?.cast<com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TransTypeIntercity>()?.toList(); } Future<List<int>> get_mPageSize_batch() async { final resultBatch = await kBmapMapFluttifyChannel.invokeMethod("com.baidu.mapapi.search.route.MassTransitRoutePlanOption::get_mPageSize_batch", [for (final __item__ in this) {'__this__': __item__}]); return (resultBatch as List)?.map((__result__) => __result__)?.cast<int>()?.toList(); } Future<List<int>> get_mPageIndex_batch() async { final resultBatch = await kBmapMapFluttifyChannel.invokeMethod("com.baidu.mapapi.search.route.MassTransitRoutePlanOption::get_mPageIndex_batch", [for (final __item__ in this) {'__this__': __item__}]); return (resultBatch as List)?.map((__result__) => __result__)?.cast<int>()?.toList(); } //endregion //region setters Future<void> set_mFrom_batch(List<com_baidu_mapapi_search_route_PlanNode> mFrom) async { await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::set_mFrom_batch', [for (int __i__ = 0; __i__ < this.length; __i__++) {'__this__': this[__i__], "mFrom": mFrom[__i__]}]); } Future<void> set_mTo_batch(List<com_baidu_mapapi_search_route_PlanNode> mTo) async { await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::set_mTo_batch', [for (int __i__ = 0; __i__ < this.length; __i__++) {'__this__': this[__i__], "mTo": mTo[__i__]}]); } Future<void> set_mCoordType_batch(List<String> mCoordType) async { await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::set_mCoordType_batch', [for (int __i__ = 0; __i__ < this.length; __i__++) {'__this__': this[__i__], "mCoordType": mCoordType[__i__]}]); } Future<void> set_mTacticsIncity_batch(List<com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TacticsIncity> mTacticsIncity) async { await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::set_mTacticsIncity_batch', [for (int __i__ = 0; __i__ < this.length; __i__++) {'__this__': this[__i__], "mTacticsIncity": mTacticsIncity[__i__].toValue()}]); } Future<void> set_mTacticsIntercity_batch(List<com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TacticsIntercity> mTacticsIntercity) async { await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::set_mTacticsIntercity_batch', [for (int __i__ = 0; __i__ < this.length; __i__++) {'__this__': this[__i__], "mTacticsIntercity": mTacticsIntercity[__i__].toValue()}]); } Future<void> set_mTransTypeIntercity_batch(List<com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TransTypeIntercity> mTransTypeIntercity) async { await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::set_mTransTypeIntercity_batch', [for (int __i__ = 0; __i__ < this.length; __i__++) {'__this__': this[__i__], "mTransTypeIntercity": mTransTypeIntercity[__i__].toValue()}]); } Future<void> set_mPageSize_batch(List<int> mPageSize) async { await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::set_mPageSize_batch', [for (int __i__ = 0; __i__ < this.length; __i__++) {'__this__': this[__i__], "mPageSize": mPageSize[__i__]}]); } Future<void> set_mPageIndex_batch(List<int> mPageIndex) async { await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::set_mPageIndex_batch', [for (int __i__ = 0; __i__ < this.length; __i__++) {'__this__': this[__i__], "mPageIndex": mPageIndex[__i__]}]); } //endregion //region methods Future<List<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>> from_batch(List<com_baidu_mapapi_search_route_PlanNode> var1) async { assert(true); // invoke native method final resultBatch = await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::from_batch', [for (int __i__ = 0; __i__ < this.length; __i__++) {"var1": var1[__i__], "__this__": this[__i__]}]); return (resultBatch as List).map((__result__) => BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>(__result__)).cast<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>().toList(); } @deprecated Future<List<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>> coordType_batch(List<String> var1) async { assert(true); // invoke native method final resultBatch = await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::coordType_batch', [for (int __i__ = 0; __i__ < this.length; __i__++) {"var1": var1[__i__], "__this__": this[__i__]}]); return (resultBatch as List).map((__result__) => BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>(__result__)).cast<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>().toList(); } Future<List<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>> tacticsIncity_batch(List<com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TacticsIncity> var1) async { assert(true); // invoke native method final resultBatch = await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::tacticsIncity_batch', [for (int __i__ = 0; __i__ < this.length; __i__++) {"var1": var1[__i__].toValue(), "__this__": this[__i__]}]); return (resultBatch as List).map((__result__) => BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>(__result__)).cast<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>().toList(); } Future<List<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>> tacticsIntercity_batch(List<com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TacticsIntercity> var1) async { assert(true); // invoke native method final resultBatch = await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::tacticsIntercity_batch', [for (int __i__ = 0; __i__ < this.length; __i__++) {"var1": var1[__i__].toValue(), "__this__": this[__i__]}]); return (resultBatch as List).map((__result__) => BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>(__result__)).cast<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>().toList(); } Future<List<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>> transtypeintercity_batch(List<com_baidu_mapapi_search_route_MassTransitRoutePlanOption_TransTypeIntercity> var1) async { assert(true); // invoke native method final resultBatch = await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::transtypeintercity_batch', [for (int __i__ = 0; __i__ < this.length; __i__++) {"var1": var1[__i__].toValue(), "__this__": this[__i__]}]); return (resultBatch as List).map((__result__) => BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>(__result__)).cast<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>().toList(); } Future<List<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>> pageSize_batch(List<int> var1) async { assert(true); // invoke native method final resultBatch = await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::pageSize_batch', [for (int __i__ = 0; __i__ < this.length; __i__++) {"var1": var1[__i__], "__this__": this[__i__]}]); return (resultBatch as List).map((__result__) => BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>(__result__)).cast<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>().toList(); } Future<List<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>> pageIndex_batch(List<int> var1) async { assert(true); // invoke native method final resultBatch = await kBmapMapFluttifyChannel.invokeMethod('com.baidu.mapapi.search.route.MassTransitRoutePlanOption::pageIndex_batch', [for (int __i__ = 0; __i__ < this.length; __i__++) {"var1": var1[__i__], "__this__": this[__i__]}]); return (resultBatch as List).map((__result__) => BmapMapFluttifyAndroidAs<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>(__result__)).cast<com_baidu_mapapi_search_route_MassTransitRoutePlanOption>().toList(); } //endregion }
53.103837
278
0.780616
2a77db2eaafd40537e1aac1be11c3fc68fcac5a1
19,889
java
Java
app/src/main/java/net/kevin/com/healthmanager/adapter/ShoppingCarAdapter.java
plzspara/HealthManager
7be815edea4153715f30b3f282f7fa923d2ef585
[ "Apache-2.0" ]
16
2020-06-30T19:04:54.000Z
2022-03-27T03:26:37.000Z
app/src/main/java/net/kevin/com/healthmanager/adapter/ShoppingCarAdapter.java
plzspara/HealthManager
7be815edea4153715f30b3f282f7fa923d2ef585
[ "Apache-2.0" ]
1
2021-03-24T07:17:52.000Z
2021-03-24T07:17:52.000Z
app/src/main/java/net/kevin/com/healthmanager/adapter/ShoppingCarAdapter.java
plzspara/HealthManager
7be815edea4153715f30b3f282f7fa923d2ef585
[ "Apache-2.0" ]
9
2019-12-01T09:24:27.000Z
2022-03-18T08:39:37.000Z
package net.kevin.com.healthmanager.adapter; import android.content.Context; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.BaseExpandableListAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import net.kevin.com.healthmanager.R; import net.kevin.com.healthmanager.javaBean.Order; import net.kevin.com.healthmanager.javaBean.ShopCar; import net.kevin.com.healthmanager.javaBean.User; import net.kevin.com.healthmanager.util.ToastUtil; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import cn.bmob.v3.BmobBatch; import cn.bmob.v3.BmobObject; import cn.bmob.v3.BmobUser; import cn.bmob.v3.datatype.BatchResult; import cn.bmob.v3.exception.BmobException; import cn.bmob.v3.listener.QueryListListener; /** * 购物车的adapter * 因为使用的是ExpandableListView,所以继承BaseExpandableListAdapter */ public class ShoppingCarAdapter extends BaseExpandableListAdapter { private final Context context; private final LinearLayout llSelectAll; private final ImageView ivSelectAll; private final Button btnOrder; private final Button btnDelete; private final TextView tvTotalPrice; private List<ShopCar> data; private boolean isSelectAll = false; private double total_price; ShopCar datasBean; boolean isSelect; boolean isSelect_shop = false; private static final String TAG = "ShoppingCarAdapter"; public ShoppingCarAdapter(Context context, LinearLayout llSelectAll, ImageView ivSelectAll, Button btnOrder, Button btnDelete, RelativeLayout rlTotalPrice, TextView tvTotalPrice) { this.context = context; this.llSelectAll = llSelectAll; this.ivSelectAll = ivSelectAll; this.btnOrder = btnOrder; this.btnDelete = btnDelete; this.tvTotalPrice = tvTotalPrice; } /** * 自定义设置数据方法; * 通过notifyDataSetChanged()刷新数据,可保持当前位置 * * @param data 需要刷新的数据 */ public void setData(List<ShopCar> data) { this.data = data; notifyDataSetChanged(); } @Override public int getGroupCount() { if (data != null && data.size() > 0) { return data.size(); } else { return 0; } } @Override public Object getGroup(int groupPosition) { return data.get(groupPosition); } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public View getGroupView(final int groupPosition, final boolean isExpanded, View convertView, ViewGroup parent) { GroupViewHolder groupViewHolder; if (convertView == null) { convertView = View.inflate(context, R.layout.item_shopping_car_group, null); groupViewHolder = new GroupViewHolder(convertView); convertView.setTag(groupViewHolder); } else { groupViewHolder = (GroupViewHolder) convertView.getTag(); } datasBean = data.get(groupPosition); //店铺名称 String store_name = datasBean.getShopName(); //设置商家名 if (store_name != null) { groupViewHolder.tvStoreName.setText(store_name); } else { groupViewHolder.tvStoreName.setText(""); } //店铺内的商品都选中的时候,店铺的也要选中 //遍历所有某商家的所有商品 for (int i = 0; i < datasBean.getShops().size(); i++) { ShopCar.shop shops = datasBean.getShops().get(i); isSelect = shops.getSelect_Goods(); if (isSelect) { datasBean.setSelect_Shops(true); } else { //有任一商品没有被选中,就商家不能被选中 datasBean.setSelect_Shops(false); break; } } //因为set之后要重新get,所以这一块代码要放到一起执行 //店铺是否在购物车中被选中 if (datasBean.getSelect_Shops()) { groupViewHolder.ivSelect.setImageResource(R.mipmap.select); } else { groupViewHolder.ivSelect.setImageResource(R.mipmap.unselect); } //店铺选择框的点击事件 groupViewHolder.ivSelect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ShopCar selectData = data.get(groupPosition); isSelect_shop = !selectData.getSelect_Shops(); selectData.setSelect_Shops(isSelect_shop); List<ShopCar.shop> goods = selectData.getShops(); for (int i = 0; i < goods.size(); i++) { ShopCar.shop goodsBean = goods.get(i); goodsBean.setSelect_Goods(isSelect_shop); } notifyDataSetChanged(); } }); /*groupViewHolder.ll_shopName.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { datasBean.setSelect_Shops(!isSelect_shop); List<ShopCar.shop> goods = datasBean.getShops(); for (int i = 0; i < goods.size(); i++) { ShopCar.shop goodsBean = goods.get(i); goodsBean.setSelect_Goods(!isSelect_shop); } Log.d(TAG, "onClick: " + !isSelect_shop); notifyDataSetChanged(); } });*/ //当所有的选择框都是选中的时候,全选也要选中 w: for (int i = 0; i < data.size(); i++) { List<ShopCar.shop> goods = data.get(i).getShops(); for (int y = 0; y < goods.size(); y++) { ShopCar.shop goodsBean = goods.get(y); boolean isSelect = goodsBean.getSelect_Goods(); if (isSelect) { isSelectAll = true; } else { isSelectAll = false; break w;//根据标记,跳出嵌套循环 } } } if (isSelectAll) { ivSelectAll.setBackgroundResource(R.mipmap.select); } else { ivSelectAll.setBackgroundResource(R.mipmap.unselect); } //全选的点击事件 llSelectAll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { isSelectAll = !isSelectAll; if (isSelectAll) { for (int i = 0; i < data.size(); i++) { data.get(i).setSelect_Shops(true); List<ShopCar.shop> goods = data.get(i).getShops(); for (int y = 0; y < goods.size(); y++) { ShopCar.shop goodsBean = goods.get(y); goodsBean.setSelect_Goods(true); } } } else { for (int i = 0; i < data.size(); i++) { data.get(i).setSelect_Shops(false); List<ShopCar.shop> goods = data.get(i).getShops(); for (int y = 0; y < goods.size(); y++) { ShopCar.shop goodsBean = goods.get(y); goodsBean.setSelect_Goods(false); } } } notifyDataSetChanged(); } }); //合计的计算 total_price = 0.0; tvTotalPrice.setText("¥0.00"); for (int i = 0; i < data.size(); i++) { List<ShopCar.shop> goods = data.get(i).getShops(); for (int y = 0; y < goods.size(); y++) { ShopCar.shop goodsBean = goods.get(y); boolean isSelect = goodsBean.getSelect_Goods(); if (isSelect) { int num = Integer.parseInt(data.get(i).getCount().get(y)); double price = goodsBean.getPrice(); total_price = total_price + num * price; //让Double类型完整显示,不用科学计数法显示大写字母E DecimalFormat decimalFormat = new DecimalFormat("0.00"); tvTotalPrice.setText("¥" + decimalFormat.format(total_price)); } } } //去结算的点击事件 btnOrder.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { List<BmobObject> orders = new ArrayList<>(); User user = BmobUser.getCurrentUser(User.class); //如果有收货人信息 if (user.getAddress() != null) { //创建临时的List,用于存储被选中的商品 for (int i = 0; i < data.size(); i++) { List<ShopCar.shop> goods = data.get(i).getShops(); for (int y = 0; y < goods.size(); y++) { ShopCar.shop goodsBean = goods.get(y); boolean isSelect = goodsBean.getSelect_Goods(); if (isSelect) { Date date = new Date(System.currentTimeMillis()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String currentTime = sdf.format(date); Order order = new Order(); order.setAddress(user.getAddress()); order.setCount(Integer.parseInt(data.get(i).getCount().get(y))); order.setGoodsId(goodsBean.getObjectId()); order.setOrderTime(currentTime); order.setPhoneNumber(user.getMobilePhoneNumber()); order.setUserId(user.getObjectId()); order.setIfGet(false); order.setGoodsName(goodsBean.getGoodsName()); orders.add(order); } } } //如果有被选中的 if (orders != null && orders.size() > 0) { new BmobBatch().insertBatch(orders).doBatch(new QueryListListener<BatchResult>() { @Override public void done(List<BatchResult> o, BmobException e) { if(e==null){ for(int i=0;i<o.size();i++){ BatchResult result = o.get(i); BmobException ex =result.getError(); if(ex==null){ Toast.makeText(context,"购买成功",Toast.LENGTH_SHORT).show(); }else{ Log.e("ERROR","第"+i+"个数据批量添加失败:"+ex.getMessage()+","+ex.getErrorCode()); } if (mDeleteListener != null) { mDeleteListener.onBuy(data); } } }else{ Log.i("bmob","失败:"+e.getMessage()+","+e.getErrorCode()); } } }); } else { ToastUtil.makeText(context, "请选择要购买的商品"); } } else { Toast.makeText(context,"没有收货信息,请输入收货人信息",Toast.LENGTH_SHORT).show(); } } }); //删除的点击事件 btnDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mDeleteListener != null) { mDeleteListener.onDelete(data); } } }); return convertView; } static class GroupViewHolder { ImageView ivSelect; TextView tvStoreName; GroupViewHolder(View view) { ivSelect = (ImageView) view.findViewById(R.id.iv_select); tvStoreName = (TextView) view.findViewById(R.id.tv_store_name); } } //------------------------------------------------------------------------------------------------ @Override public int getChildrenCount(int groupPosition) { if (data.get(groupPosition).getShops() != null && data.get(groupPosition).getShops().size() > 0) { return data.get(groupPosition).getShops().size(); } else { return 0; } } @Override public Object getChild(int groupPosition, int childPosition) { return data.get(groupPosition).getShops().get(childPosition); } @Override public long getChildId(int groupPosition, int childPosition) { return childPosition; } @Override public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { ChildViewHolder childViewHolder; if (convertView == null) { convertView = View.inflate(context, R.layout.item_shopping_car_child, null); childViewHolder = new ChildViewHolder(convertView); convertView.setTag(childViewHolder); } else { childViewHolder = (ChildViewHolder) convertView.getTag(); } final ShopCar datasBean = data.get(groupPosition); //店铺名称 String store_name = datasBean.getShopName(); //店铺是否在购物车中被选中 final boolean isSelect_shop = datasBean.getSelect_Shops(); final ShopCar.shop goodsBean = datasBean.getShops().get(childPosition); //商品图片 String goods_image = goodsBean.getGoodImage(); //商品ID final String goods_id = goodsBean.getObjectId(); //商品名称 String goods_name = goodsBean.getGoodsName(); //商品价格 Double goods_price = goodsBean.getPrice(); int i = 0 ; for (;i<data.get(groupPosition).getGoodsId().size();i++) { if (goods_id.equals(data.get(groupPosition).getGoodsId().get(i))) { break; } } //商品数量 int goods_num = Integer.parseInt(data.get(groupPosition).getCount().get(i)); //商品是否被选中 final boolean isSelect = goodsBean.getSelect_Goods(); Glide.with(context) .load(goods_image) .into(childViewHolder.ivPhoto); if (goods_name != null) { childViewHolder.tvName.setText(goods_name); } else { childViewHolder.tvName.setText(""); } if (goods_price != null) { childViewHolder.tvPriceValue.setText(goods_price + ""); } else { childViewHolder.tvPriceValue.setText(""); } if (goods_num > 0) { childViewHolder.tvEditBuyNumber.setText(goods_num + ""); } else { childViewHolder.tvEditBuyNumber.setText(""); } //商品是否被选中 if (isSelect) { childViewHolder.ivSelect.setImageResource(R.mipmap.select); } else { childViewHolder.ivSelect.setImageResource(R.mipmap.unselect); } //商品选择框的点击事件 childViewHolder.ivSelect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { goodsBean.setSelect_Goods(!isSelect); if (!isSelect == false) { datasBean.setSelect_Shops(false); } notifyDataSetChanged(); } }); //加号的点击事件 childViewHolder.ivEditAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //模拟加号操作 int num = Integer.parseInt(datasBean.getCount().get(childPosition)); num++; data.get(groupPosition).getCount().set(childPosition, num + ""); notifyDataSetChanged(); /** * 实际开发中,通过回调请求后台接口实现数量的加减 */ if (mChangeCountListener != null) { mChangeCountListener.onChangeCount(data.get(groupPosition).getObjectId(), num, childPosition); } } }); //减号的点击事件 childViewHolder.ivEditSubtract.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //模拟减号操作 int num = Integer.parseInt(datasBean.getCount().get(childPosition)); if (num > 1) { num--; data.get(groupPosition).getCount().set(childPosition, num + ""); notifyDataSetChanged(); /** * 实际开发中,通过回调请求后台接口实现数量的加减 */ if (mChangeCountListener != null) { mChangeCountListener.onChangeCount(data.get(groupPosition).getObjectId(), num, childPosition); } } else { ToastUtil.makeText(context, "商品不能再减少了"); } notifyDataSetChanged(); } }); if (childPosition == data.get(groupPosition).getShops().size() - 1) { childViewHolder.mView.setVisibility(View.GONE); childViewHolder.viewLast.setVisibility(View.VISIBLE); } else { childViewHolder.mView.setVisibility(View.VISIBLE); childViewHolder.viewLast.setVisibility(View.GONE); } return convertView; } static class ChildViewHolder { ImageView ivSelect, ivPhoto, ivEditSubtract, ivEditAdd; TextView tvName, tvPriceKey, tvPriceValue, tvEditBuyNumber; View mView, viewLast; ChildViewHolder(View view) { ivSelect = (ImageView) view.findViewById(R.id.iv_select); ivPhoto = (ImageView) view.findViewById(R.id.iv_photo); tvName = (TextView) view.findViewById(R.id.tv_name); tvPriceKey = (TextView) view.findViewById(R.id.tv_price_key); tvPriceValue = (TextView) view.findViewById(R.id.tv_price_value); ivEditSubtract = (ImageView) view.findViewById(R.id.iv_edit_subtract); tvEditBuyNumber = (TextView) view.findViewById(R.id.tv_edit_buy_number); ivEditAdd = (ImageView) view.findViewById(R.id.iv_edit_add); mView = (View) view.findViewById(R.id.view); viewLast = (View) view.findViewById(R.id.view_last); } } //----------------------------------------------------------------------------------------------- @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return false; } @Override public boolean hasStableIds() { return false; } //购买和删除的回调 public interface OnDeleteListener { void onDelete(List<ShopCar> shopCars); void onBuy(List<ShopCar> shopCars); } public void setOnDeleteListener(OnDeleteListener listener) { mDeleteListener = listener; } private OnDeleteListener mDeleteListener; //修改商品数量的回调 public interface OnChangeCountListener { void onChangeCount(String objectId, int count, int position); } public void setOnChangeCountListener(OnChangeCountListener listener) { mChangeCountListener = listener; } private OnChangeCountListener mChangeCountListener; }
36.42674
118
0.529941
e76d1ce4a23a7df03b0d870749cd7f5d02711b2a
546
js
JavaScript
models/Location.js
nephraim13/yellowcartwheel
3141ec54a8f8bc70ded026ac79d16dddcfb495e0
[ "Apache-2.0" ]
null
null
null
models/Location.js
nephraim13/yellowcartwheel
3141ec54a8f8bc70ded026ac79d16dddcfb495e0
[ "Apache-2.0" ]
1
2021-05-11T21:26:15.000Z
2021-05-11T21:26:15.000Z
models/Location.js
nephraim13/yellowcartwheel
3141ec54a8f8bc70ded026ac79d16dddcfb495e0
[ "Apache-2.0" ]
2
2020-05-11T16:39:17.000Z
2020-08-02T18:46:59.000Z
'use strict'; const mongoose = require( 'mongoose' ); const Schema = mongoose.Schema; const pointSchema = new mongoose.Schema({ type: { type: String, enum: ['Point'], required: true }, coordinates: { type: [Number], required: true } }); var locationSchema = Schema( { createdAt: Date, comment: String, placeName: String, useremail: String, category: String, website: String, location: { type: pointSchema, required: true } } ); module.exports = mongoose.model( 'Location', locationSchema );
17.612903
62
0.644689
13671f62f24c23c910cea945df1b1e5457c3c3f1
991
c
C
src/libc/utils/die.c
gspu/bitkeeper
994fb651a4045b221e33703fc3d665c3a34784e1
[ "Apache-2.0" ]
342
2016-05-10T14:59:07.000Z
2022-03-09T23:45:43.000Z
src/libc/utils/die.c
rvs/bitkeeper
616740d0daad99530951e46ab48e577807cbbaf4
[ "Apache-2.0" ]
4
2016-05-16T20:14:27.000Z
2020-10-04T19:59:25.000Z
src/libc/utils/die.c
rvs/bitkeeper
616740d0daad99530951e46ab48e577807cbbaf4
[ "Apache-2.0" ]
78
2016-05-10T15:53:30.000Z
2022-03-09T23:46:06.000Z
/* * Copyright 2013,2016 BitMover, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "system.h" void diefn(int seppuku, char *file, int line, char *fmt, ...) { va_list ap; int len; char *format; len = strlen(fmt); if (len && (fmt[len-1] == '\n')) { format = aprintf("%s", fmt); } else { format = aprintf("%s at %s line %d.\n", fmt, file, line); } va_start(ap, fmt); vfprintf(stderr, format, ap); va_end(ap); free(format); if (seppuku) exit(1); }
26.078947
75
0.677094
c5b4880cd68327f52e589e2a92c7ea3f4f77e4c0
3,698
plsql
SQL
policy_06_1412007.plsql
ATBMHTTT-2017/lab01-1412007-1412012-1412053
e3fc6b8aa1372401549622e0d806e69e492136dc
[ "Apache-2.0" ]
null
null
null
policy_06_1412007.plsql
ATBMHTTT-2017/lab01-1412007-1412012-1412053
e3fc6b8aa1372401549622e0d806e69e492136dc
[ "Apache-2.0" ]
null
null
null
policy_06_1412007.plsql
ATBMHTTT-2017/lab01-1412007-1412012-1412053
e3fc6b8aa1372401549622e0d806e69e492136dc
[ "Apache-2.0" ]
null
null
null
alter session set "_ORACLE_SCRIPT"=true; CREATE VIEW viewNHANVIEN AS SELECT * FROM dbaDuAn.NHANVIEN; CREATE OR REPLACE FUNCTION funcNHANVIEN (obj_schema varchar2, obj_name varchar2) RETURN varchar2 IS user varchar2 (20); BEGIN user := SYS_CONTEXT ('userenv', 'SESSION_USER'); RETURN 'maNV = ' || '''' || user || ''''; --return ''; END; BEGIN DBMS_RLS.ADD_POLICY ( object_schema => 'dbaDuAn', object_name => 'viewNHANVIEN', policy_name => 'policy_6_1412007', function_schema => 'dbaDuAn', policy_function => 'funcNHANVIEN', sec_relevant_cols => 'luong', sec_relevant_cols_opt => dbms_rls.ALL_ROWS); END; CREATE OR REPLACE FUNCTION funcNHANVIEN1 (obj_schema varchar2, obj_name varchar2) RETURN varchar2 IS f_maPhong dbaDuAn.PHONGBAN.maPhong%type; user varchar2 (20); BEGIN user := SYS_CONTEXT ('userenv', 'SESSION_USER'); SELECT maPhong INTO f_maPhong FROM dbaDuAn.NHANVIEN WHERE maNV = user; RETURN 'maPhong = ' || '''' || f_maPhong || ''''; --return ''; END; BEGIN DBMS_RLS.ADD_POLICY ( object_schema => 'dbaDuAn', object_name => 'viewNHANVIEN', policy_name => 'policy_6_1412007_2', function_schema => 'dbaDuAn', policy_function => 'funcNHANVIEN1', statement_types => 'select'); END; --TAO SYNONYM CHO NV, TP, TDA, TCN CREATE SYNONYM NV001.viewNHANVIEN FOR dbaDuAn.viewNHANVIEN; CREATE SYNONYM NV002.viewNHANVIEN FOR dbaDuAn.viewNHANVIEN; CREATE SYNONYM NV003.viewNHANVIEN FOR dbaDuAn.viewNHANVIEN; CREATE SYNONYM NV004.viewNHANVIEN FOR dbaDuAn.viewNHANVIEN; CREATE SYNONYM NV005.viewNHANVIEN FOR dbaDuAn.viewNHANVIEN; CREATE SYNONYM NV006.viewNHANVIEN FOR dbaDuAn.viewNHANVIEN; CREATE SYNONYM NV007.viewNHANVIEN FOR dbaDuAn.viewNHANVIEN; CREATE SYNONYM NV008.viewNHANVIEN FOR dbaDuAn.viewNHANVIEN; CREATE SYNONYM NV009.viewNHANVIEN FOR dbaDuAn.viewNHANVIEN; CREATE SYNONYM NV010.viewNHANVIEN FOR dbaDuAn.viewNHANVIEN; CREATE SYNONYM TP001.NHANVIEN FOR dbaDuAn.NHANVIEN; CREATE SYNONYM TP002.NHANVIEN FOR dbaDuAn.NHANVIEN; CREATE SYNONYM TP003.NHANVIEN FOR dbaDuAn.NHANVIEN; CREATE SYNONYM TP004.NHANVIEN FOR dbaDuAn.NHANVIEN; CREATE SYNONYM TP005.NHANVIEN FOR dbaDuAn.NHANVIEN; CREATE SYNONYM TDA001.NHANVIEN FOR dbaDuAn.NHANVIEN; CREATE SYNONYM TDA002.NHANVIEN FOR dbaDuAn.NHANVIEN; CREATE SYNONYM TDA003.NHANVIEN FOR dbaDuAn.NHANVIEN; CREATE SYNONYM TDA004.NHANVIEN FOR dbaDuAn.NHANVIEN; CREATE SYNONYM TDA005.NHANVIEN FOR dbaDuAn.NHANVIEN; CREATE SYNONYM TCN001.NHANVIEN FOR dbaDuAn.NHANVIEN; CREATE SYNONYM TCN002.NHANVIEN FOR dbaDuAn.NHANVIEN; CREATE SYNONYM TCN003.NHANVIEN FOR dbaDuAn.NHANVIEN; CREATE SYNONYM TCN004.NHANVIEN FOR dbaDuAn.NHANVIEN; CREATE SYNONYM TCN005.NHANVIEN FOR dbaDuAn.NHANVIEN; --GAN QUYEN CHO NV GRANT SELECT ON viewNhanVien TO NV001; GRANT SELECT ON viewNhanVien TO NV002; GRANT SELECT ON viewNhanVien TO NV003; GRANT SELECT ON viewNhanVien TO NV004; GRANT SELECT ON viewNhanVien TO NV005; GRANT SELECT ON viewNhanVien TO NV006; GRANT SELECT ON viewNhanVien TO NV007; GRANT SELECT ON viewNhanVien TO NV008; GRANT SELECT ON viewNhanVien TO NV009; GRANT SELECT ON viewNhanVien TO NV010; --TRUONG PHONG GRANT SELECT ON NhanVien TO TP001; GRANT SELECT ON NhanVien TO TP002; GRANT SELECT ON NhanVien TO TP003; GRANT SELECT ON NhanVien TO TP004; GRANT SELECT ON NhanVien TO TP005; --TRUONG DU AN GRANT SELECT ON NhanVien TO TDA001; GRANT SELECT ON NhanVien TO TDA002; GRANT SELECT ON NhanVien TO TDA003; GRANT SELECT ON NhanVien TO TDA004; GRANT SELECT ON NhanVien TO TDA005; --TRUONG CHI NHANH GRANT SELECT ON NhanVien TO TCN001; GRANT SELECT ON NhanVien TO TCN002; GRANT SELECT ON NhanVien TO TCN003; GRANT SELECT ON NhanVien TO TCN004; GRANT SELECT ON NhanVien TO TCN005;
34.240741
81
0.781504
9e20579d9e5389eb8e3e59489a5e7f3ac9b85058
379
asm
Assembly
circle_test.asm
juhovh/spectrum
417e60164e63902ae221c449f5a645c18e01d9c5
[ "Unlicense" ]
26
2015-03-08T13:51:48.000Z
2021-11-16T22:14:46.000Z
circle_test.asm
ktuukkan/spectrum
2f0283e44459402a9dcdc4afb1e4838fdda6782f
[ "Unlicense" ]
null
null
null
circle_test.asm
ktuukkan/spectrum
2f0283e44459402a9dcdc4afb1e4838fdda6782f
[ "Unlicense" ]
4
2015-06-13T15:55:09.000Z
2019-12-25T07:32:22.000Z
org $8000 coords incbin cdata.dat putchar push af push bc push de push hl push af ld hl,coords ld a,b and %01111111 ld l,a xor a rl l adc a,h ld h,a ld c,(hl) inc hl ld b,(hl) pop af call PutChar2 pop hl pop de pop bc pop af ret main call ClearScreen ld b,0 loop ld a,'A' call putchar halt call putchar inc b jr loop include utils.asm end main
9.475
23
0.667546
66d7149800694ec55cae0e09b34a5a988012866e
2,224
swift
Swift
CoreTetris/TetriminoGenerators.swift
numist/Tetris
247236ff180564880b6b8019c74f9ed71cc1ea4e
[ "MIT" ]
null
null
null
CoreTetris/TetriminoGenerators.swift
numist/Tetris
247236ff180564880b6b8019c74f9ed71cc1ea4e
[ "MIT" ]
null
null
null
CoreTetris/TetriminoGenerators.swift
numist/Tetris
247236ff180564880b6b8019c74f9ed71cc1ea4e
[ "MIT" ]
null
null
null
public protocol TetriminoGenerator: Copyable { func next() -> TetriminoShape } // BPS's [Random Generator](http://tetris.wikia.com/wiki/Random_Generator) final public class RandomGenerator<RNG where RNG:RandomNumberGenerator, RNG:Copyable>: TetriminoGenerator, Copyable { private var tetriminos: [TetriminoShape] = [] private let generator: RNG public init(generator: RNG) { self.generator = generator } private init(tetriminos: [TetriminoShape], generator: RNG) { self.tetriminos = tetriminos self.generator = generator } public func copy() -> RandomGenerator { return RandomGenerator(tetriminos: self.tetriminos, generator: self.generator.copy()) } private func generateBag() -> Void { var tetriminos = TetriminoShape.allValues let count = tetriminos.count for i in 0..<count { let element = tetriminos.removeAtIndex(i) // TODO: Modulo sucks, but there are seven tetriminos so it should shuffle pretty nicely? tetriminos.insert(element, atIndex: self.generator.next() % count) } self.tetriminos = tetriminos } public func next() -> TetriminoShape { if self.tetriminos.count == 0 { self.generateBag() } return self.tetriminos.removeFirst() } } // never deals an S, Z or O as the first piece, to avoid a forced overhang // try using rand(0..<7) up to 4 times to generate a piece that is not in the most recent 4 produced class GrandMasterOneGenerator {} // never deals an S, Z or O as the first piece, to avoid a forced overhang // try using rand(0..<7) up to 6 times to generate a piece that is not in the most recent 4 produced // the history begins with a Z,Z,S,S sequence. However, as the first piece of the game overwrites the first Z rather than pushing off the last S, this is effectively a Z,S,S,Z or Z,S,Z,S sequence class GrandMasterGenerator {} // deals a bag of 7 randomized tetrominoes // never deals an S, Z or O as the first piece class GrandMasterAceGenerator {} // http://tetrisconcept.net/threads/randomizer-theory.512/page-9#post-55478 class TerrorInstinctGenerator {}
37.694915
195
0.683453
0d5dad423bedc9669426bb5c09043e553b9e346c
27,848
swift
Swift
FlatlandView/Settings/SettingKeys.swift
sjrankin/FlatlandView
e49731c36c7640dffa97b901db12675b789b7344
[ "FSFAP" ]
null
null
null
FlatlandView/Settings/SettingKeys.swift
sjrankin/FlatlandView
e49731c36c7640dffa97b901db12675b789b7344
[ "FSFAP" ]
1
2020-08-24T04:22:48.000Z
2020-08-24T04:23:41.000Z
FlatlandView/Settings/SettingKeys.swift
sjrankin/FlatlandView
e49731c36c7640dffa97b901db12675b789b7344
[ "FSFAP" ]
null
null
null
// // SettingTypes.swift // Flatland // // Created by Stuart Rankin on 5/24/20. // Copyright © 2020 Stuart Rankin. All rights reserved. // import Foundation /// Settings. Each case refers to a single setting and is used /// by the settings class to access the setting. enum SettingKeys: String, CaseIterable { // MARK: - Infrastructure/initialization-related settings. case InitializationFlag = "InitializationFlag" // MARK: - Map-related settings. /// The type of map to view (the map image). This is used for both 2D and 3D modes /// (but not the cubic mode). case MapType = "MapType" /// Determines the view type - 2D (one of two types) or 3D (one of two types). case ViewType = "ViewType" /// Boolean: Determines if the night mask is shown in 2D mode. case ShowNight = "ShowNight" /// Double: The alpha level of the night mask. See `NightDarkness`. case NightMaskAlpha = "NightMaskAlpha" /// Darkness level that determines the actual alpha level of the night mask. See /// `NightMaskAlpha`. case NightDarkness = "NightDarkness" /// The type of hour to display. case HourType = "HourType" /// The type of time label to display. case TimeLabel = "TimeLabel" /// Boolean: Determines whether seconds are shown in the time label. case TimeLabelSeconds = "TimeLabelSeconds" /// Boolean: Show the sun in 2D mode. case ShowSun = "ShowSun" /// Determines the script to use for certain display elements. case Script = "Script" /// The type of sun image to display. case SunType = "SunType" /// The type of view to show in the sample map image display. case SampleViewType = "SampleViewType" /// NSSize: The size of the window. case WindowSize = "WindowSize" /// CGPoint: The origin of the window. case WindowOrigin = "WindowOrigin" /// NSSize: The size of the primary contents view. case PrimaryViewSize = "PrimaryViewSize" /// Boolean: If true, earthquake coordinates are decorated with cardinal directions. case DecorateEarthquakeCoordinates = "DecorateEarthquakeCoordinates" /// Boolean: If true, a status bar is shown. case ShowStatusBar = "ShowStatusBar" /// Integer: Number of times Flatland has been instantiated for a given version. case InstantiationCount = "InstantiationCount" /// String: Version used for current instantiation count. case InstantiationVersion = "InstantiationVersion" // MARK: - 2D view settings. /// Boolean: Display the equator in 2D mode. case Show2DEquator = "Show2DEquator" /// Boolean: Display polar circles in 2D mode. case Show2DPolarCircles = "Show2DPolarCircles" /// Boolean: Display tropic circles in 2D mode. case Show2DTropics = "Show2DTropics" /// Boolean: Display prime meridians in 2D mode. case Show2DPrimeMeridians = "Show2DPrimeMeridians" /// Boolean: Display noon meridians in 2D mode. case Show2DNoonMeridians = "Show2DNoonMeridians" /// Boolean: Display shadows for protruding objects. case Show2DShadows = "Show2DShadows" /// The shape of earthquakes on the flat map. case EarthquakeShape2D = "EarthquakeShape2D" /// Boolean: Determines if wall clock seperator shapes are displayed. case ShowWallClockSeparators = "ShowWallClockSeparators" /// NSColor: Color of primary grid lines in flat view. case PrimaryGridLineColor = "PrimaryGridLineColor" /// NSColor: Color of secondary grid lines in flat view. case SecondaryGridLineColor = "SecondaryGridLineColor" /// NSColor: Color of wall clock grid lines in flat view. case WallClockGridLineColor = "WallClockGridLineColor" // MARK: - 3D view settings. /// Scale to use for POI 3D objects. case POIScale = "POIScale" /// Boolean: Display grid lines in 3D mode. case Show3DGridLines = "Show3DGridLines" /// Boolean: Display the equator in 3D mode. case Show3DEquator = "Show3DEquator" /// Boolean: Display polar circles in 3D mode. case Show3DPolarCircles = "Show3DPolarCircles" /// Boolean: Display tropic circles in 3D mode. case Show3DTropics = "Show3DTropics" /// Boolean: Display prime meridians in 3D mode. case Show3DPrimeMeridians = "Show3DPrimeMeridians" /// Boolean: Display minor grid lines in 3D mode. case Show3DMinorGrid = "Show3DMinorGrid" /// Double: Grid gap for minor grid lines in 3D mode. case MinorGrid3DGap = "MinorGrid3DGap" /// Double: Alpha level for the 3D globe. case GlobeTransparencyLevel = "GlobeTransparencyLevel" /// Determines how fast stars move when visible. case StarSpeeds = "StarSpeeds" /// Boolean: Show moonlight on 3D globes for the night side. case ShowMoonLight = "ShowMoonLight" /// Determines the shape of the object marking the poles. case PolarShape = "PolarShape" #if false /// Determines the shape of the object making locations in the user's location list. case UserLocationShape = "UserLocationShape" #endif /// Boolean: Reset hour labels periodically. Performance debug option. case ResetHoursPeriodically = "ResetHoursPeriodically" /// Double: How often to reset hours. Performance debug option. case ResetHourTimeInterval = "ResetHourTimeInterval" /// NSColor: The color of the 3D background case BackgroundColor3D = "BackgroundColor3D" /// Boolean: If true, an ambient light (rather than sun and moon lights) is used. case UseAmbientLight = "UseAmbientLight" /// Boolean: If true, user POI locations show light emission. If false, no emission is used. case ShowPOIEmission = "ShowPOIEmission" /// Boolean: If true, the 3D view will try to attract people via animation and other effects. case InAttractMode = "InAttractMode" /// Boolean: If true, the scene's camera is set to HDR mode. case UseHDRCamera = "UseHDRCamera" /// NSColor: Color of the hours. case HourColor = "HourColor" /// NSColor: Color of the emission of hours in the night. case HourEmissionColor = "HourEmissionColor" /// String: Name of the hour font. case HourFontName = "HourFontName" /// Scale of the extruded 3D hour labels. case HourScale = "HourScale" /// NSColor: Color of major grid lines. case GridLineColor = "GridLineColor" /// NSColor: Color of minor grid lines. case MinorGridLineColor = "MinorGridLineColor" /// CGFloat: User camera field of view. case FieldOfView = "FieldOfView" /// Double: User camera orthographic scale value. case OrthographicScale = "OrthographicScale" /// Double: Camera's z-far value. case ZFar = "ZFar" /// Double: Camera's z-near value. case ZNear = "ZNear" /// CGFloat: Closest the user is allowed to zoom in. case ClosestZ = "ClosestZ" /// Integer: Number of sphere segments. case SphereSegmentCount = "SphereSegmentCount" /// Boolean: If true, grid lines are drawn on the map itself. If false, they are drawn /// semi-three dimensionally. case GridLinesDrawnOnMap = "GridLineDrawnOnMap" /// Boolean: If true, city names are drawn on the map itself. If false, they are drawn /// with 3D extruded text. case CityNamesDrawnOnMap = "CityNamesDrawnOnMap" /// Boolean: If true, earthquake magnitude values are drawn on the map itself. If false, /// they are drawn with 3D extruded text. case MagnitudeValuesDrawnOnMap = "MagnitudeValuesDrawnOnMap" /// NSColor: The color to use to draw earthquake region bords. case EarthquakeRegionBorderColor = "EarthquakeRegionBorderColor" /// Double: The width of earthquake borders. case EarthquakeRegionBorderWidth = "EarthquakeRegionBorderWidth" /// Relative size of the font used to stencil city names. case CityFontRelativeSize = "CityFontRelativeSize" /// Relative size of the font used to stencil magnitude values. case MagnitudeRelativeFontSize = "MagnitudeRelativeFontSize" /// Boolean: If true, standard NSStrings are used to draw stenciled text. If false, /// NSAttributedStrings are used. NSStrings are faster... case StencilPlainText = "StencilPlainText" /// Boolean: If true, show a barcode next to the magnitude. case ShowMagnitudeBarCode = "ShowMagnitudeBarCode" // Camera settings. /// SCNVector3: Initial position of the camera. case InitialCameraPosition = "InitialCameraPosition" /// Boolean: If true, `allowsCameraControl` is used to let the user control how the scene /// looks. If false, use the camera control implemented in Flatland. case UseSystemCameraControl = "UseSystemCameraControl" /// Boolean: It true, the user can zoom with Flatland's camera. case EnableZooming = "EnableZooming" /// Boolean: If true, the user can drag/rotate the scene with Flatland's camera. case EnableDragging = "EnableDragging" /// Boolean: If true, the user can move/translate the scene with Flatland's camera. case EnableMoving = "EnableMoving" /// Flatland's camera projection. case CameraProjection = "CameraProjection" /// CGFloat: The field of view for Flatland's camera system. case CameraFieldOfView = "CameraFieldOfView" /// Double: The orthographic scale for Flatland's camera system. case CameraOrthographicScale = "CameraOrthographicScale" /// Boolean: If true, the 3D scenes cannot be moved. If false, they can. case WorldIsLocked = "WorldIsLocked" /// Boolean: If true, 3D jittering is enabled. case EnableJittering = "EnableJittering" /// Antialias value. case AntialiasLevel = "AntialiasLevel" /// Boolean: If true, Flatland will search for what is close to the mouse pointer. case SearchForLocation = "SearchForLocation" /// Boolean: If true, the mouse will be hidden when it is over the Earth. case HideMouseOverEarth = "HideMouseOverEarth" //3D debug settings. /// Render 3D elements as wireframes. case ShowWireframes = "ShowWireframes" /// Boolean: Show bounding boxes around 3D elements. case ShowBoundingBoxes = "ShowBoundingBoxes" /// Boolean: Show skeletons. case ShowSkeletons = "ShowSkeletons" /// Boolean: Show node constraints. case ShowConstraints = "ShowConstraints" /// Boolean: Show light influences. case ShowLightInfluences = "ShowLightInfluences" /// Boolean: Show light extents. case ShowLightExtents = "ShowLightExtents" /// Boolean: Show rendering statistics. case ShowStatistics = "ShowStatistics" /// Boolean: Show the camera. case ShowCamera = "ShowCamera" /// Boolean: Show creases. case ShowCreases = "ShowCreases" /// Boolean: Show physics shapes. case ShowPhysicsShapes = "ShowPhysicsShapes" /// Boolean: Show physics fields. case ShowPhysicsFields = "ShowPhysicsFields" /// Boolean: Render as wireframe. case RenderAsWireframe = "RenderAsWireframe" /// Boolean: If true, the node under the mouse is highlighted. case HighlightNodeUnderMouse = "HighlightNodeUnderMouse" /// Determines which map type is affected by the 3D debug flags. case Debug3DMap = "Debug3DMap" /// Boolean: If true, 3D debugging is enabled. case Enable3DDebugging = "Enable3DDebugging" /// Boolean: If true, axis markers are shown in 3D debug. case ShowAxes = "ShowAxes" /// Boolean: If true, known locations are shown on the map. case ShowKnownLocations = "ShowKnownLocations" /// Boolean: If true, the program name and version will be shown at start-up. case ShowInitialVersion = "ShowInitialVersion" /// Double: Number of seconds to show the initial version string. case InitialVersionDuration = "InitialVersionDuration" // MARK: - Performance and optimization settings. /// Boolean: If true, hours have a chamfer value set. case UseHourChamfer = "UseHourChamfer" /// Boolean: If true, live data labels have a chamfer value set. case UseLiveDataChamfer = "UseLiveDataChamfer" /// CGFloat: Determines text smoothness. case TextSmoothness = "TextSmoothness" // MARK: - Local and home locations. /// Boolean: Show user locations. case ShowUserLocations = "ShowUserLocations" /// Integer: Time zone offset for the user's home location. case LocalTimeZoneOffset = "LocalTimeZoneOffset" /// Determines the shape of the object marking the user's home location. case HomeShape = "HomeShape" /// String: List of locations created by the user. case UserLocations = "UserLocations" /// Boolean: Determines if the user's location is shown, regardless if it is available. case ShowHomeLocation = "ShowHomeLocation" /// NSColor: Color of the home location for shapes that use it. case HomeColor = "HomeColor" /// String: Name of the location for the Today window for non-home locations. case DailyLocationName = "DailyLocationName" /// Double?: Latitude of the location for the Today window for non-home locations. case DailyLocationLatitude = "DailyLocationLatitude" /// Double?: Longitude of the location for the Today window for non-home locations. case DailyLocationLongitude = "DailyLocationLongitude" /// Boolean: Determines if user POIs are shown. case ShowUserPOIs = "ShowUserPOIs" /// Secure string: User's home latitude. Will generate a fatal error if used with normal string functions. case UserHomeLatitude = "UserHomeLatitude" /// Secure string: User's home longitude. Will generate a fatal error if used with normal string functions. case UserHomeLongitude = "UserHomeLongitude" /// Secure string: Name of user's home. Will generate a fatal error if used with normal string functions. case UserHomeName = "UserHomeName" /// Boolean: Show or hide built-in POIs. case ShowBuiltInPOIs = "ShowBuiltInPOIs" // MARK: - City-related settings. /// Boolean: Show cities on the map. This is a filter boolean meaning if it is false, /// no cities will be shown regardless of their settings. case ShowCities = "ShowCities" /// Boolean: Show custom cities. case ShowCustomCities = "ShowCustomCities" /// Boolean: Show African cities. case ShowAfricanCities = "ShowAfricanCities" /// Boolean: Show Asian cities. case ShowAsianCities = "ShowAsianCities" /// Boolean: Show European cities. case ShowEuropeanCities = "ShowEuropeanCities" /// Boolean: Show North American cities. case ShowNorthAmericanCities = "ShowNorthAmericanCities" /// Boolean: Show South American cities. case ShowSouthAmericanCities = "ShowSouthAmericanCities" /// Boolean: Show national capital cities. case ShowCapitalCities = "ShowCapitalCities" /// Boolean: Show all cities (very slow). case ShowAllCities = "ShowAllCities" /// Boolean: Show world cities. case ShowWorldCities = "ShowWorldCities" /// NSColor: Color to use for African cities. case AfricanCityColor = "AfricanCityColor" /// NSColor: Color to use for Asian cities. case AsianCityColor = "AsianCityColor" /// NSColor: Color to use for European cities. case EuropeanCityColor = "EuropeanCityColor" /// NSColor: Color to use for North American cities. case NorthAmericanCityColor = "NorthAmericanCityColor" /// NSColor: Color to use for South American cities. case SouthAmericanCityColor = "SouthAmericanCityColor" /// NSColor: Color to use for capital cities. case CapitalCityColor = "CapitalCityColors" /// NSColor: Color to use for world cities. case WorldCityColor = "WorldCityColors" /// NSColor: Color to use for custom cities. case CustomCityListColor = "CustomCityListColor" /// NSColor: Determines the shape of cities. case CityShapes = "CityShapes" /// Determines how the relative size of cities is calculated. case PopulationType = "PopulationType" /// The font to use for city names. case CityFontName = "CityFontName" /// List of user-customized cities. case CustomCityList = "CustomCityList" /// Boolean: City nodes glow if applicable. case CityNodesGlow = "CityNodesGlow" /// Boolean: Cities by population rank. case ShowCitiesByPopulation = "ShowCitiesByPopulation" /// Integer: Population rank count. case PopulationRank = "PopulationRank" /// Boolean: Use metropolitan population for ranking cities. case PopulationRankIsMetro = "PopulationRankIsMetro" /// Int: Population value to compare against the city list. case PopulationFilterValue = "PopulationFilterValue" /// Boolean: Determines how `PopulationFilterValue` is used. case PopulationFilterGreater = "PopulationFilterGreater" /// NSColor: The color for population-filtered cities. case PopulationColor = "PopulationColor" /// How to filter by city population. case PopulationFilterType = "PopulationFilterType" /// Table of cities from the mappable database. case CityList = "CityList" /// Table of user cities from the mappable database. case UserCityList = "UserCityList" /// Boolean: If true, 3D city names cast shadows. case ExtrudedCitiesCastShadows = "ExtrudedCitiesCastShadows" /// Boolean: If true, 3D floating hours cast shadows. case HoursCastShadows = "HoursCastShadows" // MARK: - World Heritage Site settings /// Boolean: Determines whether World Heritage Sites are shown. case ShowWorldHeritageSites = "ShowWorldHeritageSites" /// Determines the type of site to display. case WorldHeritageSiteType = "WorldHeritageSiteType" /// County filter for World Heritage Sites. case SiteCountry = "SiteCountry" /// Inclusion year for sites. case SiteYear = "SiteYear" /// Inclusion year filter for sites. case SiteYearFilter = "SiteYearFilter" /// Boolean: If true, sites are plotted on the stencil layer. If false, sites are plotted as 3D objects. case PlotSitesAs2D = "PlotSitesAs2D" // MARK: - Earthquake settings. //Earthquake asynchronous settings. /// Double: How often, in seconds, to fetch earthquake data. case EarthquakeFetchInterval = "EarthquakeFetchInterval" /// Boolean: Determines if remote earthquake data is fetched. case EnableEarthquakes = "EnableEarthquakes" /// How to modify the base color on a per-earthquake basis. case ColorDetermination = "ColorDetermination" /// NSColor: The base earthquake color. case BaseEarthquakeColor = "BaseEarthquakeColor" /// How to draw the earthquake. case EarthquakeShapes = "EarthquakeShapes" /// Boolean: Display only the largest earthquake in a region. case DisplayLargestOnly = "DisplayLargestOnly" /// Double: Radius for earthquake regions to determine when to suppress smaller /// earthquakes when `DisplayLargestOnly` is true. case EarthquakeRegionRadius = "EarthquakeRegionRadius" /// String: List of colors for various earthquake magnitudes. case EarthquakeMagnitudeColors = "EarthquakeMagnitudeColors" /// Determines how to list earthquakes. case EarthquakeListStyle = "EarthquakeListStyle" /// Boolean: Highlight recent earthquakes. case HighlightRecentEarthquakes = "HighlightRecentEarthquakes" /// The age an earthquake must be to be considered "recent." case RecentEarthquakeDefinition = "RecentEarthquakeDefinition" /// Texture to use for earthquake indicators that use textures. case EarthquakeTextures = "EarthquakeTextures" /// Earthquake indicator style. case EarthquakeStyles = "EarthquakeStyles" /// Earthquake indicator style for 2D earthquakes. case Earthquake2DStyles = "Earthquake2DStyles" /// Earthquake indicator color for indicators that use colors. case EarthquakeColor = "EarthquakeColor" /// String: Name of the font to use to display earthquake magnitudes. case EarthquakeFontName = "EarthquakeFontName" /// Age of earthquakes to view in the earthquake list dialog. case EarthquakeListAge = "EarthquakeListAge" /// Integer: Minimum magnitude earthquake to display in the earthquake list dialog. case EarthquakeDisplayMagnitude = "EarthquakeDisplayMagnitude" /// Age of earthquakes to view in the earthquake list dialog. Intended for the group view. case GroupEarthquakeListAge = "GroupEarthquakeListAge" /// Integer: Minimum magnitude earthquake to display in the earthquake list dialog. Intended /// for the group view. case GroupEarthquakeDisplayMagnitude = "GroupEarthquakeDisplayMagnitude" /// String: List of cached earthquakes. case CachedEarthquakes = "CachedEarthquakes" /// Determines the scale of 3D nodes used as earthquake indicators. case QuakeScales = "QuakeScales" #if false /// Maximum distance (in kilometers) that earthquakes must be to be combined. case CombineDistance = "CombineDistance" #endif /// How (or if) to display earthquake magnitude values. case EarthquakeMagnitudeViews = "EarthquakeMagnitudeViews" /// NSColor: The color of the bars that indicate a combined earthquake. case CombinedEarthquakeColor = "CombinedEarthquakeColor" /// String: Contains all regions monitored for a set of earthquake parameters. /// - Warning: Do not access this setting directly. /// - Note: See also `GetEarthquakeRegions` and `SetEarthquakeRegions`. case EarthquakeRegions = "EarthquakeRegions" /// Boolean: Enables the visibility of 2D earthquake regions. case ShowEarthquakeRegions = "ShowEarthquakeRegions" /// Double: Minimum value that earthquakes must be to be included in any list. case GeneralMinimumMagnitude = "GeneralMinimumMagnitude" /// Double: Use for earthquake table for regions. Radius of the region from which /// quakes are reported. case QuakeRegionRadius = "QuakeRegionRadius" /// Double: Latitude of the center of the quake region for earthquake tables. case QuakeRegionLatitude = "QuakeRegionLatitude" /// Double: Longitude of the center of the quake region for earthquake tables. case QuakeRegionLongitude = "QuakeRegionLongitude" /// Bool: Enable quake regions in the earthquake table. case QuakeRegionEnable = "QuakeRegionEnable" /// Bool: If true all quakes will be shown in the regional set. Otherwise the current /// filter will be used. case QuakeSetAll = "QuakeSetAll" /// Boolean: If true, tiles from NASA servers are preloaded. Otherwise, they are not /// loaded until the user requires them. case PreloadNASATiles = "PreloadNASATiles" /// List of earthquakes the use was notified about. Used to prevent excessive notifications. case NotifiedEarthquakes = "NotifiedEarthquakes" /// Where notifications appear. case NotifyLocation = "NotifyLocation" // MARK: - NASA tiles settings. /// Boolean: Set according to the environment variable "enable_nasa_tiles". Not user /// accessible. If "enable_nasa_tiles" is not present, true is put into this /// settings. case EnableNASATiles = "EnableNASATiles" /// Int: Hours between tile fetching. case NASATilesFetchInterval = "NASATilesFetchInterval" /// Double?: Last time tiles were fetched from NASA. case LastNASAFetchTime = "LastNASAFetchTime" // MARK: - General settings. /// The last settings viewed by the user. case LastSettingsViewed = "LastSettingsViewed" /// Boolean: Determines if the splash screen is shown on start-up. case ShowSplashScreen = "ShowSplashScreen" /// Double: Amount of time the splash screen is shown, in seconds. case SplashScreenDuration = "SplashScreenDuration" /// Boolean: If true, details of geographic nodes are shown. If false, nothing is shown. case ShowDetailedInformation = "ShowDetailedInformation" /// Boolean: If true, the mouse is tracked in map views. case FollowMouse = "FollowMouse" // MARK: - Time debug settings. /// Boolean: Enables debugging of time. case DebugTime = "DebugTime" /// Controls whether time is running or paused. case TimeControl = "TimeControl" /// Starting time one time resumes. case TestTime = "TestTime" /// Time will stop advancing once this time is reached. case StopTimeAt = "StopTimeAt" /// Double: Value to multipy time by. case TimeMultiplier = "TimeMultiplier" /// Boolean: Enables or disables the stop time. case EnableStopTime = "EnableStopTime" // MARK: - General debug settings /// Boolean: Enable clock control case Debug_EnableClockControl = "Debug_EnableClockControl" /// Determines which map type is affected by the debug. case Debug_ClockDebugMap = "Debug_ClockDebugMap" /// Boolean: Freeze the clock. case Debug_ClockActionFreeze = "Debug_ClockActionFreeze" /// Boolean: Freeze the clock at the specified time. case Debug_ClockActionFreezeAtTime = "Debug_ClockActionFreezeAtTime" /// Date: When to freeze the clock (only the time component is used). case Debug_ClockActionFreezeTime = "Debug_ClockActionFreezeTime" /// Boolean: Set the clock angle. case Debug_ClockActionSetClockAngle = "Debug_ClockActionSetAngle" /// Double: New clock angle. case Debug_ClockActionClockAngle = "Debug_ClockActionClockAngle" /// Boolean: Use clock multiplier. case Debug_ClockUseTimeMultiplier = "Debug_ClockUseTimeMultiplier" /// Double: Clock time multiplier. case Debug_ClockActionClockMultiplier = "Debug_ClockActionClockMultiplier" // MARK: - Input/local settings. /// Determines the default input unit. case InputUnit = "InputUnit" // MARK: - Interface settings. /// Determines how fancy the interface is. case InterfaceStyle = "InterfaceStyle" /// Determines the numeric input type for color channels. case ColorInputType = "ColorInputType" /// The last selected colorspace for the color picker. case ColorPickerColorspace = "ColorPickerColorspace" /// Boolean: Show or hide UI help buttons ("􀁝"). case ShowUIHelp = "ShowUIHelp" // MARK: - Event and sound settings /// Boolean: Determines if sounds are globally enabled. case EnableSounds = "EnableSounds" /// Boolean: Determines if hour chiming is enable. case EnableHourEvent = "EnableHourEvent" /// Boolean: If true, a mute period is observed every day. case EnableMutePeriod = "EnableMutePeriod" /// Integer: Start of mute period in seconds since midnight. case MutePeriodStart = "MutePeriodStart" /// Integer: Duration of mute period in seconds since start of period. case MutePeriodDuration = "MutePeriodDuration" /// Time units for period duration. case MutePeriodTimeUnits = "MutePeriodTimeUnits" // MARK: - Settings that interface with the database. /// [City2]: List of built-in cities. case DB_Cities = "DB_Cities" /// [City2]: List of user cities. case DB_UserCities = "DB_UserCities" /// [POI2]: List of built-in POIs. case DB_BuiltInPOIs = "DB_BuiltInPOIs" /// [POI2]: List of user POIs. case DB_UserPOIs = "DB_UserPOIs" /// [POI2]: List of homes specified by the user. case DB_Homes = "DB_Homes" /// [WorldHeritageSite]: List of UNESCO world heritage sites. case DB_WorldHeritageSites = "DB_WorldHeritageSites" // MARK: - Settings used to trigger events. /// Integer: New memory measurement available. case Trigger_MemoryMeasured = "Tigger_MemoryMeasured" // MARK: - Settings used in areas outside of the Settings system. /// Live data viewer. case LiveViewWindowFrame = "LiveViewWindowFrame" /// Earthquake data viewer. case EarthquakeViewWindowFrame = "EarthquakeViewWindowFrame" }
50.086331
111
0.716102
493fa20e6cce0edfe7546e34f863928344f6f713
4,831
dart
Dart
lib/widgets/session/sign_up_form.dart
kawanji01/BooQs_on_mobiles
11fda70c7e0e236b44f638115fbac9d50dd0d4db
[ "MIT" ]
8
2021-12-11T10:35:02.000Z
2022-02-23T14:19:21.000Z
lib/widgets/session/sign_up_form.dart
kawanji01/BooQs_on_mobiles
11fda70c7e0e236b44f638115fbac9d50dd0d4db
[ "MIT" ]
56
2021-11-16T08:54:14.000Z
2022-02-23T13:22:09.000Z
lib/widgets/session/sign_up_form.dart
kawanji01/BooQs_on_mobiles
11fda70c7e0e236b44f638115fbac9d50dd0d4db
[ "MIT" ]
null
null
null
import 'package:booqs_mobile/data/provider/user.dart'; import 'package:booqs_mobile/data/remote/sessions.dart'; import 'package:booqs_mobile/models/user.dart'; import 'package:booqs_mobile/pages/user/mypage.dart'; import 'package:booqs_mobile/utils/user_setup.dart'; import 'package:booqs_mobile/widgets/session/form_field.dart'; import 'package:flutter/material.dart'; import 'package:flutter_easyloading/flutter_easyloading.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; class SignUpForm extends ConsumerStatefulWidget { const SignUpForm({Key? key}) : super(key: key); @override _SignUpFormState createState() => _SignUpFormState(); } class _SignUpFormState extends ConsumerState<SignUpForm> { final _formKey = GlobalKey<FormState>(); final _nameController = TextEditingController(); final _idController = TextEditingController(); final _passwordController = TextEditingController(); @override void dispose() { // Clean up the controller when the widget is removed from the widget tree. _nameController.dispose(); _idController.dispose(); _passwordController.dispose(); super.dispose(); } // Note: Remember to dispose of the TextEditingController when it’s no longer needed. This ensures that you discard any resources used by the object. // ref: https://docs.flutter.dev/cookbook/forms/text-field-changes @override Widget build(BuildContext context) { // 送信 Future _submit() async { // 画面全体にローディングを表示 EasyLoading.show(status: 'loading...'); if (!_formKey.currentState!.validate()) { // ローディングを消去 EasyLoading.dismiss(); return; } /* // デバイスの識別IDなどを取得する final deviceInfo = DeviceInfoService(); String platform = deviceInfo.getPlatform(); String deviceIdentifier = await deviceInfo.getIndentifier(); String deviceName = await deviceInfo.getName(); // リクエスト var url = Uri.parse( '${const String.fromEnvironment("ROOT_URL")}/${Localizations.localeOf(context).languageCode}/api/v1/mobile/users'); var res = await http.post(url, body: { 'name': _nameController.text, 'email': _idController.text, 'password': _passwordController.text, 'device_identifier': deviceIdentifier, 'device_name': deviceName, 'platform': platform, }); */ final String name = _nameController.text; final String email = _idController.text; final String password = _passwordController.text; final Map? resMap = await RemoteSessions.signUp(name, email, password); // レスポンスに対する処理 if (resMap == null) { _passwordController.text = ''; const snackBar = SnackBar( content: Text('登録できませんでした。指定メールアドレスのユーザーはすでに存在しているか、パスワードが短すぎます。')); ScaffoldMessenger.of(context).showSnackBar(snackBar); } else { User user = User.fromJson(resMap['user']); await UserSetup.signIn(user); ref.read(currentUserProvider.notifier).state = user; final snackBar = SnackBar(content: Text('${resMap['message']}')); ScaffoldMessenger.of(context).showSnackBar(snackBar); UserMyPage.push(context); } EasyLoading.dismiss(); } Widget _submitButton() { return InkWell( onTap: () { _submit(); }, child: Container( width: MediaQuery.of(context).size.width, padding: const EdgeInsets.symmetric(vertical: 15), alignment: Alignment.center, decoration: BoxDecoration( borderRadius: const BorderRadius.all(Radius.circular(5)), boxShadow: <BoxShadow>[ BoxShadow( color: Colors.grey.shade200, offset: const Offset(2, 4), blurRadius: 5, spreadRadius: 2) ], gradient: const LinearGradient( begin: Alignment.centerLeft, end: Alignment.centerRight, colors: [Color(0xfffbb448), Color(0xfff7892b)])), child: const Text( '登録する', style: TextStyle( fontSize: 20, color: Colors.white, fontWeight: FontWeight.bold), ), ), ); } return Form( key: _formKey, child: Column( children: <Widget>[ SessionFormField( label: "ユーザー名", controller: _nameController, isPassword: false), SessionFormField( label: "メールアドレス", controller: _idController, isPassword: false), SessionFormField( label: "パスワード(6文字以上)", controller: _passwordController, isPassword: true), const SizedBox(height: 20), _submitButton(), ], ), ); } }
35.785185
151
0.631339
4a3e17e41b83375767d72a60af05a672315afd75
9,800
js
JavaScript
src/screens/calculation/UltimateShear.js
madhuwantha/civil-construction-tool-client
60d24ceeddfc888c0e6acd3400bf3e6ade5eb8c0
[ "MIT" ]
null
null
null
src/screens/calculation/UltimateShear.js
madhuwantha/civil-construction-tool-client
60d24ceeddfc888c0e6acd3400bf3e6ade5eb8c0
[ "MIT" ]
15
2021-01-14T12:31:47.000Z
2021-06-01T19:28:52.000Z
src/screens/calculation/UltimateShear.js
madhuwantha/civil-construction-tool-client
60d24ceeddfc888c0e6acd3400bf3e6ade5eb8c0
[ "MIT" ]
null
null
null
import React, {useState} from 'react'; import {useForm} from "react-hook-form"; import {calcShearCapacity, calcSpacing} from "./CalculationUSBSI"; import {calcFinal, calcVDesign} from "./CalculationUSEC"; import {getPdf, savePdf} from "../../helpers/pdf"; import {degrees, rgb} from "pdf-lib"; const UltimateShear = (props) => { const {register, handleSubmit, errors} = useForm(); const [isSubmit, setIsSubmit] = useState(false); const [answer11, setAnswer11] = useState(0); const [answer12, setAnswer12] = useState(0); const [answer13, setAnswer13] = useState(0); const [answer21, setAnswer21] = useState(0); const [answer22, setAnswer22] = useState(0); const [answer23, setAnswer23] = useState(0); const [pdf, setPdf] = useState(null); const onSubmit = async data => { let ans11 = await calcShearCapacity(parseFloat(data["v"]), parseFloat(data["b"]), parseFloat(data["d"])); let ans12 = await calcSpacing(parseFloat(data["fyv"]), parseFloat(data["b"]), parseFloat(data["sc"]), parseFloat(data["fcu"]),parseFloat(data["d"]),parseFloat(data["As"]), parseFloat(data["v"])) let ans13 = 150; let ans21 = await calcVDesign(parseFloat(data["v"]), parseFloat(data["l"]), parseFloat(data["d"])); let ans22 = await calcFinal(parseFloat(data["v"]), parseFloat(data["l"]), parseFloat(data["b"]), parseFloat(data["d"]), parseFloat(data["fck"]), parseFloat(data["As"]), parseFloat(data["fy"])); let ans23 = 150; setAnswer11(parseFloat(ans11["mainAnswer"].toFixed(4))) setAnswer12(parseFloat(ans12["mainAnswer"].toFixed(4))) setAnswer13(parseFloat(ans13?.toFixed(4))) setAnswer21(parseFloat(ans21["mainAnswer"]?.toFixed(4))) setAnswer22(typeof(ans22["mainAnswer"]) === "string" ? ans22 : parseFloat(ans22["mainAnswer"]?.toFixed(4))) setAnswer23(parseFloat(ans23?.toFixed(4))) setIsSubmit(true) const pdfDoc = await getPdf('shear_work_sheet.pdf'); const page = pdfDoc.getPage(0); page.drawText('This text was added with Deno!', { x: 40, y: page.getHeight() / 2 + 250, size: 50, color: rgb(0.95, 0.1, 0.1), rotate: degrees(-45), }); setPdf(await savePdf(pdfDoc)); } return( <div className="container col-8 card"> <p>Shear Capacity and Shear Reinforcement Calculator</p> <form action="#" onSubmit={handleSubmit(onSubmit)}> <div className="col-12 lesson-image-container"> <p>Beam Dimensions</p> <div style={{"border": "1px solid black"}} className="col-12 lesson-image-container"> {errors.b && <span>This field is required</span>} <div className="input-group mb-3"> <span className="input-group-text col-md-10" id="strength-concrete">Breadth (mm)</span> <div className="input-group-append col-md-2"> <input name="b" type="number" step="0.00001" className="form-control" aria-describedby="m" ref={register({required: true})}/> </div> </div> {errors.d && <span>This field is required</span>} <div className="input-group mb-3"> <span className="input-group-text col-md-10" id="strength-concrete">Effective Depth (mm)</span> <div className="input-group-append col-md-2"> <input name="d" type="number" step="0.00001" className="form-control" aria-describedby="m" ref={register({required: true})}/> </div> </div> </div> </div> <div className="col-12 lesson-image-container"> <p>Concrete</p> <div style={{"border": "1px solid black"}} className="col-12 lesson-image-container"> {errors.fck && <span>This field is required</span>} <div className="input-group mb-3"> <span className="input-group-text col-md-10" id="strength-concrete">Cylindrical Strength (Mpa)</span> <div className="input-group-append col-md-2"> <input name="fck" type="number" step="0.00001" className="form-control" aria-describedby="m" ref={register({required: true})}/> </div> </div> {errors.fcu && <span>This field is required</span>} <div className="input-group mb-3"> <span className="input-group-text col-md-10" id="strength-concrete">Cubic Strength (MPa)</span> <div className="input-group-append col-md-2"> <input name="fcu" type="number" step="0.00001" className="form-control" aria-describedby="m" ref={register({required: true})}/> </div> </div> </div> </div> <div className="col-12 lesson-image-container"> <p>Loading Details</p> <div style={{"border": "1px solid black"}} className="col-12 lesson-image-container"> {errors.v && <span>This field is required</span>} <div className="input-group mb-3"> <span className="input-group-text col-md-10" id="strength-concrete"> Shear Force (kN)</span> <div className="input-group-append col-md-2"> <input name="v" type="number" step="0.00001" className="form-control" aria-describedby="m" ref={register({required: true})}/> </div> </div> {errors.l && <span>This field is required</span>} <div className="input-group mb-3"> <span className="input-group-text col-md-10" id="strength-concrete">Span (kNm)</span> <div className="input-group-append col-md-2"> <input name="l" type="number" step="0.00001" className="form-control" aria-describedby="m" ref={register({required: true})}/> </div> </div> </div> </div> <div className="col-12 lesson-image-container"> <p>Strength of r/f</p> <div style={{"border": "1px solid black"}} className="col-12 lesson-image-container"> {errors.fy && <span>This field is required</span>} <div className="input-group mb-3"> <span className="input-group-text col-md-10" id="strength-concrete">f <sub>y</sub> (MPa)</span> <div className="input-group-append col-md-2"> <input name="fy" type="number" step="0.00001" className="form-control" aria-describedby="m" ref={register({required: true})}/> </div> </div> {errors.fyv && <span>This field is required</span>} <div className="input-group mb-3"> <span className="input-group-text col-md-10" id="strength-concrete">f <sub>yv</sub> (MPa)</span> <div className="input-group-append col-md-2"> <input name="fyv" type="number" step="0.00001" className="form-control" aria-describedby="m" ref={register({required: true})}/> </div> </div> </div> </div> <div className="col-12 lesson-image-container"> <p>Reinforcement</p> <div style={{"border": "1px solid black"}} className="col-12 lesson-image-container"> {errors.As && <span>This field is required</span>} <div className="input-group mb-3"> <span className="input-group-text col-md-10" id="strength-concrete">Tensile r/f (mm<sup>2</sup>)</span> <div className="input-group-append col-md-2"> <input name="As" type="number" step="0.00001" className="form-control" aria-describedby="m" ref={register({required: true})}/> </div> </div> {errors.Asv && <span>This field is required</span>} <div className="input-group mb-3"> <span className="input-group-text col-md-10" id="strength-concrete">Shear r/f (mm<sup>2</sup>)</span> <div className="input-group-append col-md-2"> <input name="Asv" type="number" step="0.00001" className="form-control" aria-describedby="m" ref={register({required: true})}/> </div> </div> </div> </div> <div className="col-12 lesson-image-container"> <div style={{"border": "1px solid black"}} className="col-12 lesson-image-container"> <div className="col"> <input name="" value="Calculate" className="btn btn-primary lesson-button" type="submit"/> </div> </div> </div> {isSubmit ? <table className="table table-bordered"> <thead> <tr> <th scope="col" rowSpan={2}> </th> <th scope="col" rowSpan={2}>Shear Capacity (kN)</th> <th scope="col" colSpan={2}>Spacing of Shear r/f (mm)</th> </tr> <tr> <th scope="col">Spacing for design shear r/f</th> <th scope="col">Spacing for minimum shear r/f</th> </tr> </thead> <tbody> <tr> <th scope="row">BS</th> <td>{answer11}</td> <td>{answer12}</td> <td>{answer13}</td> </tr> <tr> <th scope="row">EC</th> <td>{answer21}</td> <td>{answer22}</td> <td>{answer23}</td> </tr> </tbody> </table> : <></> } </form> {pdf !== null ? <iframe className="pdf-viewer" title="test-frame" src={pdf} type="application/pdf" /> : <></> } </div> ); } export default UltimateShear;
46.889952
123
0.551939
6b1913e80a1173f83e36d6ef45c932acf325122a
757
sql
SQL
migrations/2018-02-18-071905_add_default_games_and_modes/up.sql
mattdeboard/rs-pugbot
e8bf082e5d1fe059b3e237d660457f29929427ba
[ "MIT" ]
3
2018-12-26T13:58:40.000Z
2020-06-18T04:33:11.000Z
migrations/2018-02-18-071905_add_default_games_and_modes/up.sql
mattdeboard/rs-pugbot
e8bf082e5d1fe059b3e237d660457f29929427ba
[ "MIT" ]
89
2018-12-28T01:40:58.000Z
2021-05-08T20:39:17.000Z
migrations/2018-02-18-071905_add_default_games_and_modes/up.sql
mattdeboard/rs-pugbot
e8bf082e5d1fe059b3e237d660457f29929427ba
[ "MIT" ]
1
2021-05-01T20:56:30.000Z
2021-05-01T20:56:30.000Z
insert into game_titles (game_name) values ('Overwatch'), ('Rocket League') ; with ow_id as ( select game_title_id as id from game_titles where game_name = 'Overwatch' ) insert into game_modes (game_title_id, mode_name, team_size) values ((select id from ow_id), 'Standard', 6), ((select id from ow_id), 'Capture The Flag', 6), ((select id from ow_id), '1v1', 1), ((select id from ow_id), '5v5', 5); with rl_id as ( select game_title_id as id from game_titles where game_name = 'Rocket League' ) insert into game_modes (game_title_id, mode_name, team_size) values ((select id from rl_id), 'Standard 3v3', 3), ((select id from rl_id), '2v2', 2), ((select id from rl_id), '4v4', 4), ((select id from rl_id), '1v1', 1);
28.037037
67
0.673712
b582a0144fc3c07c04438418d27de4f9d32c5f8c
786
rs
Rust
rust/src/problems/s344_reverse_string.rs
eteplus/leetcode
13cb7aac323dd68c670b1548a8d72667eb68bd7c
[ "MIT" ]
1
2022-01-25T09:03:59.000Z
2022-01-25T09:03:59.000Z
rust/src/problems/s344_reverse_string.rs
eteplus/leetcode
13cb7aac323dd68c670b1548a8d72667eb68bd7c
[ "MIT" ]
null
null
null
rust/src/problems/s344_reverse_string.rs
eteplus/leetcode
13cb7aac323dd68c670b1548a8d72667eb68bd7c
[ "MIT" ]
null
null
null
struct Solution; impl Solution { pub fn reverse_string(s: &mut Vec<char>) { let mut i = 0; let mut j = s.len() - 1; while i < j { s.swap(i, j); i += 1; j -= 1; } } } struct Example { input: Vec<char>, output: Vec<char>, } #[test] pub fn test() { let examples = vec![ Example { input: vec!['h', 'e', 'l', 'l', 'o'], output: vec!['o', 'l', 'l', 'e', 'h'], }, Example { input: vec!['H', 'a', 'n', 'n', 'a', 'h'], output: vec!['h', 'a', 'n', 'n', 'a', 'H'], }, ]; for mut example in examples { Solution::reverse_string(example.input.as_mut()); assert_eq!(example.input, example.output); } }
21.243243
57
0.414758
f4ef1223ec0545fde83548a3065b57141f659680
2,625
go
Go
pkg/v1/tkg/azure/mocks/resourceskus_mock.go
benjaminapetersen/tanzu-framework
fbabd54a42868572dee518178c64dcb80fc02cd2
[ "Apache-2.0" ]
92
2021-10-04T07:46:46.000Z
2022-03-24T22:13:14.000Z
pkg/v1/tkg/azure/mocks/resourceskus_mock.go
benjaminapetersen/tanzu-framework
fbabd54a42868572dee518178c64dcb80fc02cd2
[ "Apache-2.0" ]
1,061
2021-10-04T09:35:11.000Z
2022-03-31T21:34:35.000Z
pkg/v1/tkg/azure/mocks/resourceskus_mock.go
benjaminapetersen/tanzu-framework
fbabd54a42868572dee518178c64dcb80fc02cd2
[ "Apache-2.0" ]
110
2021-10-04T07:22:29.000Z
2022-03-23T20:18:07.000Z
// Copyright 2021 VMware, Inc. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // Code generated by MockGen. DO NOT EDIT. // Source: github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute/computeapi (interfaces: ResourceSkusClientAPI) // Package azure is a generated GoMock package. package azure import ( context "context" reflect "reflect" compute "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2019-12-01/compute" gomock "github.com/golang/mock/gomock" ) // MockResourceSkusClientAPI is a mock of ResourceSkusClientAPI interface. type MockResourceSkusClientAPI struct { ctrl *gomock.Controller recorder *MockResourceSkusClientAPIMockRecorder } // MockResourceSkusClientAPIMockRecorder is the mock recorder for MockResourceSkusClientAPI. type MockResourceSkusClientAPIMockRecorder struct { mock *MockResourceSkusClientAPI } // NewMockResourceSkusClientAPI creates a new mock instance. func NewMockResourceSkusClientAPI(ctrl *gomock.Controller) *MockResourceSkusClientAPI { mock := &MockResourceSkusClientAPI{ctrl: ctrl} mock.recorder = &MockResourceSkusClientAPIMockRecorder{mock} return mock } // EXPECT returns an object that allows the caller to indicate expected use. func (m *MockResourceSkusClientAPI) EXPECT() *MockResourceSkusClientAPIMockRecorder { return m.recorder } // List mocks base method. func (m *MockResourceSkusClientAPI) List(arg0 context.Context, arg1 string) (compute.ResourceSkusResultPage, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "List", arg0, arg1) ret0, _ := ret[0].(compute.ResourceSkusResultPage) ret1, _ := ret[1].(error) return ret0, ret1 } // List indicates an expected call of List. func (mr *MockResourceSkusClientAPIMockRecorder) List(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "List", reflect.TypeOf((*MockResourceSkusClientAPI)(nil).List), arg0, arg1) } // ListComplete mocks base method. func (m *MockResourceSkusClientAPI) ListComplete(arg0 context.Context, arg1 string) (compute.ResourceSkusResultIterator, error) { m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ListComplete", arg0, arg1) ret0, _ := ret[0].(compute.ResourceSkusResultIterator) ret1, _ := ret[1].(error) return ret0, ret1 } // ListComplete indicates an expected call of ListComplete. func (mr *MockResourceSkusClientAPIMockRecorder) ListComplete(arg0, arg1 interface{}) *gomock.Call { mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListComplete", reflect.TypeOf((*MockResourceSkusClientAPI)(nil).ListComplete), arg0, arg1) }
37.5
146
0.780952
b599b1eb843fd705a56b390c201f58e01e3f5cb9
1,225
sql
SQL
src/test/regress/sql/ce_functions_return_variable.sql
Yanci0/openGauss-server
b2ff10be1367c77f2fda396d6c12ffa3c25874c7
[ "MulanPSL-1.0" ]
360
2020-06-30T14:47:34.000Z
2022-03-31T15:21:53.000Z
src/test/regress/sql/ce_functions_return_variable.sql
Yanci0/openGauss-server
b2ff10be1367c77f2fda396d6c12ffa3c25874c7
[ "MulanPSL-1.0" ]
4
2020-06-30T15:09:16.000Z
2020-07-14T06:20:03.000Z
src/test/regress/sql/ce_functions_return_variable.sql
futurewei-cloud/chogori-opengauss
f43410e1643c887819e718d9baceb9e853ad9574
[ "MulanPSL-1.0" ]
133
2020-06-30T14:47:36.000Z
2022-03-25T15:29:00.000Z
\! gs_ktool -d all \! gs_ktool -g DROP CLIENT MASTER KEY IF EXISTS ret_cmk3 CASCADE; CREATE CLIENT MASTER KEY ret_cmk3 WITH ( KEY_STORE = gs_ktool , KEY_PATH = "gs_ktool/1" , ALGORITHM = AES_256_CBC); CREATE COLUMN ENCRYPTION KEY ret_cek3 WITH VALUES (CLIENT_MASTER_KEY = ret_cmk3, ALGORITHM = AEAD_AES_256_CBC_HMAC_SHA256); create table accounts ( id serial, name varchar(100) not null ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = ret_cek3, ENCRYPTION_TYPE = DETERMINISTIC), balance dec(15,2) not null ENCRYPTED WITH (COLUMN_ENCRYPTION_KEY = ret_cek3, ENCRYPTION_TYPE = DETERMINISTIC), primary key(id) ); insert into accounts(name,balance) values('Bob',10000); insert into accounts(name,balance) values('Alice',10000); CREATE OR REPLACE FUNCTION f_processed_in_plpgsql(a varchar(100), b dec(15,2)) RETURNS varchar(100) AS $$ declare c varchar(100); BEGIN SELECT into c name from accounts where name=$1 or balance=$2 LIMIT 1; RETURN c; END; $$ LANGUAGE plpgsql; SELECT f_processed_in_plpgsql('Bob', 10000); CALL f_processed_in_plpgsql('Bob',10000); DROP FUNCTION f_processed_in_plpgsql(); DROP TABLE accounts; DROP COLUMN ENCRYPTION KEY ret_cek3; DROP CLIENT MASTER KEY ret_cmk3; \! gs_ktool -d all
35
123
0.764898
ffac06b9e30d42c93e17da909a3f33857d3e77d1
913
dart
Dart
test/groups/model/group_test.dart
lucvanderzandt/dart-rest-api
88bdb8570c98f8f742f93e8fd7560ae840151cd1
[ "BSD-3-Clause" ]
4
2020-01-07T16:55:24.000Z
2021-03-28T23:05:48.000Z
test/groups/model/group_test.dart
lucvanderzandt/dart-rest-api
88bdb8570c98f8f742f93e8fd7560ae840151cd1
[ "BSD-3-Clause" ]
6
2020-01-07T20:31:49.000Z
2020-06-25T12:08:53.000Z
test/groups/model/group_test.dart
lucvanderzandt/dart-rest-api
88bdb8570c98f8f742f93e8fd7560ae840151cd1
[ "BSD-3-Clause" ]
4
2020-01-07T19:04:41.000Z
2022-03-29T14:27:09.000Z
import 'dart:io'; import 'package:messagebird/groups.dart'; import 'package:test/test.dart'; void main() { group('Group', () { Group group; setUp(() { group = Group.fromJson(File('test_resources/group.json').readAsStringSync()); }); test('should deserialize from json', () { expect(group.id, equals('61afc0531573b08ddbe36e1c85602827')); expect(group.contacts.totalCount, equals(0)); expect( group.createdDatetime, DateTime.parse('2016-04-29T09:42:26+00:00')); }); test('should serialize to json', () { final Map<String, dynamic> serialized = group.toMap(); expect(serialized['id'], equals('61afc0531573b08ddbe36e1c85602827')); expect(serialized['contacts']['totalCount'], equals(0)); expect(serialized['createdDatetime'], equals(DateTime.parse('2016-04-29T09:42:26+00:00').toString())); }); }); }
28.53125
79
0.634173
1396ca28c91c6c57182f29310a653c9a8176f7c4
291
dart
Dart
lib/src/qr_row.dart
sentd94/qr_svg_generator
e7dd28ffa010d1ee1dbbeb401ded6aa53f4bdf9c
[ "BSD-3-Clause" ]
null
null
null
lib/src/qr_row.dart
sentd94/qr_svg_generator
e7dd28ffa010d1ee1dbbeb401ded6aa53f4bdf9c
[ "BSD-3-Clause" ]
null
null
null
lib/src/qr_row.dart
sentd94/qr_svg_generator
e7dd28ffa010d1ee1dbbeb401ded6aa53f4bdf9c
[ "BSD-3-Clause" ]
null
null
null
import 'qr_rect.dart'; class QrRow { QrRow({required this.id, required this.rectList}); String id; List<QrRect> rectList; @override String toString() { final rectsStr = rectList.map((rect) => rect.toString()).join('\n'); return ' <g id="$id">\n$rectsStr\n </g>'; } }
20.785714
72
0.621993
8a2f83e83d9cca779c0cd8e02eeab8db2661fd6c
65
rs
Rust
src/sheet_music_format/kifu_rpm/mod.rs
muzudho/rust-kifuwarabe-wcsc29-lib
5f18ee2417a51035921164640c045fbc1613be5c
[ "MIT" ]
null
null
null
src/sheet_music_format/kifu_rpm/mod.rs
muzudho/rust-kifuwarabe-wcsc29-lib
5f18ee2417a51035921164640c045fbc1613be5c
[ "MIT" ]
null
null
null
src/sheet_music_format/kifu_rpm/mod.rs
muzudho/rust-kifuwarabe-wcsc29-lib
5f18ee2417a51035921164640c045fbc1613be5c
[ "MIT" ]
null
null
null
pub mod rpm_tape; pub mod rpm_tape_box; pub mod rpm_tape_tracks;
16.25
24
0.815385
966632a7274a39337ee846f26ebb0d17d3ae5c2e
612
php
PHP
resources/views/front/auth/inscription.blade.php
AxelCardinaels/Museo
932672e856993cc50cef10c9c15ebc3967b177ca
[ "MIT" ]
null
null
null
resources/views/front/auth/inscription.blade.php
AxelCardinaels/Museo
932672e856993cc50cef10c9c15ebc3967b177ca
[ "MIT" ]
null
null
null
resources/views/front/auth/inscription.blade.php
AxelCardinaels/Museo
932672e856993cc50cef10c9c15ebc3967b177ca
[ "MIT" ]
null
null
null
@extends( "partials.front.app" ) @section("menu__class", "menu--inside") @section( "content") </header> <main> <section class="section"> <div class="intro__container intro__container--centered"> <h3 class="section__title title--section">Rejoignez Museo</h3> <p class="section__subtitle">Afin de profiter de toutes les possibilités de Museo, il vous suffit de vous inscrire. Cela prend 5 minutes maximum, promis!</p> </div> <img src="{{URL::asset("img/connexion.png")}}" alt="Image connexion" class="login__img"/> @include("front.auth.forms.register") </section> @endsection
29.142857
163
0.694444
bece433de06658ea24900e93a24788f9d4aab883
11,876
dart
Dart
lib/OverviewPage.dart
SubmarineApp/periscope
a2b2b2d6de787d1ad4cf7d11c9ba42d5cea5a2d3
[ "MIT" ]
null
null
null
lib/OverviewPage.dart
SubmarineApp/periscope
a2b2b2d6de787d1ad4cf7d11c9ba42d5cea5a2d3
[ "MIT" ]
null
null
null
lib/OverviewPage.dart
SubmarineApp/periscope
a2b2b2d6de787d1ad4cf7d11c9ba42d5cea5a2d3
[ "MIT" ]
null
null
null
import 'dart:collection'; import 'package:backend_api/api.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:jiffy/jiffy.dart'; import 'package:charts_flutter/flutter.dart' as charts; import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart'; class OverviewPage extends StatefulWidget { final DefaultApi client; final List<Subscription> subscriptions; final HashMap<int, Category> categories; OverviewPage({this.client, this.subscriptions, this.categories}); @override _OverviewPageState createState() => _OverviewPageState( client: this.client, subscriptions: this.subscriptions, categories: this.categories); } class _OverviewPageState extends State<OverviewPage> { final DefaultApi client; List<Subscription> subscriptions; final HashMap<int, Category> categories; List<CategoryMonthlyPctAccumulator> _categorySpendingThisMonth = <CategoryMonthlyPctAccumulator>[]; List<MonthlySpendingAccumulator> _monthlySpending = []; Map<Category, List<MonthlySpendingAccumulator>> _categoryMonthlySpending = new HashMap<Category, List<MonthlySpendingAccumulator>>(); final List<charts.Color> _colors = [ charts.Color(a: 0xFF, b: 0xA6, g: 0x5D, r: 0x90), charts.Color(a: 0xFF, b: 0x7A, g: 0x5D, r: 0xA6), charts.Color(a: 0xFF, b: 0x5D, g: 0x9E, r: 0xA6), charts.Color(a: 0xFF, b: 0x67, g: 0xA6, r: 0x5D), charts.Color(a: 0xFF, b: 0xA6, g: 0x8A, r: 0x5D), charts.Color(a: 0xFF, b: 0xA6, g: 0x5D, r: 0x90), ]; double _totalAdjustedMonthlySpending = 0; _OverviewPageState({this.client, this.subscriptions, this.categories}) { _init(); } List<DateTime> _recurrencesThisMonth(Subscription sub, DateTime month) { if (month.isBefore(sub.startsAt)) return []; var monthJiffy = Jiffy(month); var startsAtJiffy = Jiffy(sub.startsAt); DateTime renewalDate; List<DateTime> result = []; if (sub.recurrence == 'monthly') { var monthsBetween = monthJiffy.diff(startsAtJiffy, Units.MONTH); renewalDate = startsAtJiffy.add(months: monthsBetween); result.add(renewalDate); } else if (sub.recurrence == 'weekly') { var dayOfWeek = startsAtJiffy.day; renewalDate = Jiffy(monthJiffy.startOf(Units.WEEK)).add(days: dayOfWeek); var nextMonth = monthJiffy.add(months: 1); for (int i = 0; i < 4; i++) { if (renewalDate.isAfter(nextMonth)) break; result.add(renewalDate); renewalDate = Jiffy(renewalDate).add(weeks: 1); } } else if (sub.recurrence == 'yearly') { var renewalMonthNumber = sub.startsAt.month; if (month.month == renewalMonthNumber) { result.add(new DateTime(month.year, month.month, sub.startsAt.day)); } } // debugPrint("MONTH: ${month}"); // debugPrint("${sub.id} - ${sub.title}:"); // debugPrint(result.toString()); return result; } _init() async { // An old, dilapidated sign with faded writing stands in your path: // ABANDON ALL HOPE // YE WHO ENTER HERE // ... eh. Must be nothing. HashMap<int, int> tempSpending = HashMap<int, int>(); int totalSpending = 0; subscriptions = await client.subscriptionsGet(); (await client.categoriesGet()).forEach((e) => {categories[e.id] = e}); subscriptions.forEach((element) { var recurrenceCost = element.cost; if (element.recurrence == "weekly") recurrenceCost *= 4; else if (element.recurrence == "yearly") recurrenceCost ~/= 12; tempSpending[element.category] = (tempSpending[element.category] ?? 0) + recurrenceCost; totalSpending += recurrenceCost; }); tempSpending.forEach((category, amount) { _categorySpendingThisMonth.add(CategoryMonthlyPctAccumulator( categoryName: categories[category].name, amount: amount.toDouble() / totalSpending * 100)); }); var now = new DateTime.now(); HashMap<DateTime, int> spendingPerMonth = new HashMap<DateTime, int>(); HashMap<Category, HashMap<DateTime, int>> spendingPerCategoryPerMonth = new HashMap<Category, HashMap<DateTime, int>>(); var subsStartedPriorToNow = subscriptions.where((element) => element.startsAt.isBefore(now)); subsStartedPriorToNow.forEach((sub) { for (int i = -6; i < 7; i++) { var startOfMonth = Jiffy(Jiffy(DateTime.now()).add(months: i)).startOf(Units.MONTH); var recurrencesThisMonth = _recurrencesThisMonth(sub, startOfMonth); var recurrenceCost = recurrencesThisMonth.length * sub.cost; spendingPerMonth[startOfMonth] ??= 0; spendingPerMonth[startOfMonth] += recurrenceCost; spendingPerCategoryPerMonth[categories[sub.category]] ??= new HashMap<DateTime, int>(); spendingPerCategoryPerMonth[categories[sub.category]][startOfMonth] ??= 0; spendingPerCategoryPerMonth[categories[sub.category]][startOfMonth] += recurrenceCost; } }); spendingPerMonth.forEach((month, amount) { _monthlySpending.add( MonthlySpendingAccumulator(month: month, amount: amount / 100.0)); }); _categoryMonthlySpending = spendingPerCategoryPerMonth.map((category, map) { List<MonthlySpendingAccumulator> monthlySpendingForCategory = []; map.forEach((month, amount) { monthlySpendingForCategory.add( MonthlySpendingAccumulator(month: month, amount: amount / 100.0)); }); return MapEntry(category, monthlySpendingForCategory); }); _categorySpendingThisMonth.forEach((value) { _totalAdjustedMonthlySpending += value.amount; }); setState(() {}); } int _findSpendingForThisMonth() { int totalCost = 0; subscriptions.forEach((sub) { var recurrencesThisMonth = _recurrencesThisMonth(sub, DateTime.now()); totalCost += recurrencesThisMonth.length * sub.cost; }); return totalCost; } @override Widget build(BuildContext context) { final simpleCurrencyFormatter = new charts.BasicNumericTickFormatterSpec.fromNumberFormat( new NumberFormat.compactSimpleCurrency()); return StaggeredGridView.count( crossAxisCount: 4, staggeredTiles: [ const StaggeredTile.count(1, 1), const StaggeredTile.count(1, 1), const StaggeredTile.count(1, 1), const StaggeredTile.count(2, 1), ], children: [ Container( padding: EdgeInsets.all(16), child: Flex( direction: Axis.vertical, children: [ Text( "Actual Spending for this Month", style: TextStyle(fontSize: 18), ), Expanded( child: Center( child: Text( NumberFormat.simpleCurrency() .format(_findSpendingForThisMonth() / 100), style: TextStyle( fontSize: 36, fontWeight: FontWeight.bold, ), ), ), ), ], ), ), Container( padding: EdgeInsets.all(16), child: Flex( direction: Axis.vertical, children: [ Text( "Adjusted Monthly Spending", style: TextStyle(fontSize: 18), ), Expanded( child: Center( child: Text( NumberFormat.simpleCurrency() .format(_totalAdjustedMonthlySpending), style: TextStyle( fontSize: 36, fontWeight: FontWeight.bold, ), ), ), ), ], ), ), CategorySpendingPieChart( categorySpendingThisMonth: _categorySpendingThisMonth, colors: _colors), Container( padding: EdgeInsets.all(16), child: Flex( direction: Axis.vertical, children: [ Text( "Total Spending by Month", style: TextStyle(fontSize: 18), ), Flexible( child: _categoryMonthlySpending.isEmpty ? Center(child: CircularProgressIndicator()) : charts.TimeSeriesChart( <charts.Series<MonthlySpendingAccumulator, DateTime>>[ ..._categoryMonthlySpending .map( (category, monthlySpendingAcc) => MapEntry( category, charts.Series<MonthlySpendingAccumulator, DateTime>( id: category.name, data: monthlySpendingAcc, domainFn: (data, _) => data.month, measureFn: (data, _) => data.amount, colorFn: (_, i) => _colors[category.id], ), ), ) .values ], primaryMeasureAxis: charts.NumericAxisSpec( tickFormatterSpec: simpleCurrencyFormatter, ), ), ), ], ), ), ], ); } } class CategorySpendingPieChart extends StatefulWidget { final List<CategoryMonthlyPctAccumulator> categorySpendingThisMonth; final List<charts.Color> colors; CategorySpendingPieChart({ @required this.categorySpendingThisMonth, @required this.colors, }); @override _CategorySpendingPieChartState createState() => _CategorySpendingPieChartState( categorySpendingThisMonth: this.categorySpendingThisMonth, colors: this.colors, ); } class _CategorySpendingPieChartState extends State<CategorySpendingPieChart> { final List<CategoryMonthlyPctAccumulator> categorySpendingThisMonth; final List<charts.Color> colors; _CategorySpendingPieChartState({ @required this.categorySpendingThisMonth, @required this.colors, }); @override Widget build(BuildContext context) { return Container( padding: EdgeInsets.all(16), child: Flex( direction: Axis.vertical, children: [ Text( "Adjusted Monthly Spending by Category", style: TextStyle(fontSize: 18), ), Flexible( child: charts.PieChart( [ charts.Series<CategoryMonthlyPctAccumulator, String>( id: 'Adjusted Monthly Spending', data: categorySpendingThisMonth, domainFn: (data, _) => data.categoryName, measureFn: (data, _) => data.amount, labelAccessorFn: (data, _) => "${data.categoryName}\n${data.amount.toStringAsFixed(1)}%", colorFn: (_, index) => colors[index], ) ], defaultRenderer: new charts.ArcRendererConfig( arcRendererDecorators: [new charts.ArcLabelDecorator()], ), ), ), ], ), ); } } class CategoryMonthlyPctAccumulator { final String categoryName; final double amount; CategoryMonthlyPctAccumulator({this.categoryName, this.amount}); } class MonthlySpendingAccumulator { final double amount; final DateTime month; MonthlySpendingAccumulator({this.month, this.amount}); }
35.663664
81
0.584203
271cb92c4c5abba6938a15f5a90faba029304638
8,307
c
C
arch/riscv/RiscvDisassembler.c
stettberger/capstone
83b6bdfc3ea06a5f5921cff6a2220a0cdf0f4556
[ "BSD-3-Clause" ]
null
null
null
arch/riscv/RiscvDisassembler.c
stettberger/capstone
83b6bdfc3ea06a5f5921cff6a2220a0cdf0f4556
[ "BSD-3-Clause" ]
null
null
null
arch/riscv/RiscvDisassembler.c
stettberger/capstone
83b6bdfc3ea06a5f5921cff6a2220a0cdf0f4556
[ "BSD-3-Clause" ]
null
null
null
//===-- RISCVDisassembler.cpp - Disassembler for RISCV --------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the RISCVDisassembler class. // //===----------------------------------------------------------------------===// #ifdef CAPSTONE_HAS_RISCV #include <stdio.h> #include <assert.h> #include <string.h> #include <platform.h> #include "../../utils.h" #include "../../MCInst.h" #include "../../MCRegisterInfo.h" #include "../../SStream.h" #include "../../MathExtras.h" #include "RiscvDisassembler.h" // #include "MCTargetDesc/RISCVMCTargetDesc.h" // #include "llvm/MC/MCContext.h" #include "../../MCDisassembler.h" #include "../../MCFixedLenDisassembler.h" #include "../../MCInst.h" #include "../../MCRegisterInfo.h" // #include "llvm/MC/MCSubtargetInfo.h" // #include "llvm/Support/Endian.h" // #include "llvm/Support/TargetRegistry.h" #define GET_SUBTARGETINFO_ENUM #include "RiscvGenSubTargetInfo.inc" static uint64_t getFeatureBits(int mode) { uint64_t Bits = 0; // TODO: limited to the M extension (multiply) for now. Bits |= RISCV_FeatureStdExtM; if (mode & CS_MODE_32) { // nothing to do } else if (mode & CS_MODE_64) { Bits |= RISCV_Feature64Bit; } return Bits; } #define GET_REGINFO_ENUM #include "RiscvGenRegisterInfo.inc" static const unsigned GPRDecoderTable[] = { RISCV_X0, RISCV_X1, RISCV_X2, RISCV_X3, RISCV_X4, RISCV_X5, RISCV_X6, RISCV_X7, RISCV_X8, RISCV_X9, RISCV_X10, RISCV_X11, RISCV_X12, RISCV_X13, RISCV_X14, RISCV_X15, RISCV_X16, RISCV_X17, RISCV_X18, RISCV_X19, RISCV_X20, RISCV_X21, RISCV_X22, RISCV_X23, RISCV_X24, RISCV_X25, RISCV_X26, RISCV_X27, RISCV_X28, RISCV_X29, RISCV_X30, RISCV_X31 }; static DecodeStatus DecodeGPRRegisterClass(MCInst *Inst, uint64_t RegNo, uint64_t Address, const MCRegisterInfo *Decoder) { if (RegNo > sizeof(GPRDecoderTable)) { return MCDisassembler_Fail; } // We must define our own mapping from RegNo to register identifier. // Accessing index RegNo in the register class will work in the case that // registers were added in ascending order, but not in general. unsigned Reg = GPRDecoderTable[RegNo]; MCOperand_CreateReg0(Inst, Reg); return MCDisassembler_Success; } static const unsigned FPR32DecoderTable[] = { RISCV_F0_32, RISCV_F1_32, RISCV_F2_32, RISCV_F3_32, RISCV_F4_32, RISCV_F5_32, RISCV_F6_32, RISCV_F7_32, RISCV_F8_32, RISCV_F9_32, RISCV_F10_32, RISCV_F11_32, RISCV_F12_32, RISCV_F13_32, RISCV_F14_32, RISCV_F15_32, RISCV_F16_32, RISCV_F17_32, RISCV_F18_32, RISCV_F19_32, RISCV_F20_32, RISCV_F21_32, RISCV_F22_32, RISCV_F23_32, RISCV_F24_32, RISCV_F25_32, RISCV_F26_32, RISCV_F27_32, RISCV_F28_32, RISCV_F29_32, RISCV_F30_32, RISCV_F31_32 }; static DecodeStatus DecodeFPR32RegisterClass(MCInst *Inst, uint64_t RegNo, uint64_t Address, const MCRegisterInfo *Decoder) { if (RegNo > sizeof(FPR32DecoderTable)) { return MCDisassembler_Fail; } // We must define our own mapping from RegNo to register identifier. // Accessing index RegNo in the register class will work in the case that // registers were added in ascending order, but not in general. unsigned Reg = FPR32DecoderTable[RegNo]; MCOperand_CreateReg0(Inst, Reg); return MCDisassembler_Success; } static const unsigned FPR64DecoderTable[] = { RISCV_F0_64, RISCV_F1_64, RISCV_F2_64, RISCV_F3_64, RISCV_F4_64, RISCV_F5_64, RISCV_F6_64, RISCV_F7_64, RISCV_F8_64, RISCV_F9_64, RISCV_F10_64, RISCV_F11_64, RISCV_F12_64, RISCV_F13_64, RISCV_F14_64, RISCV_F15_64, RISCV_F16_64, RISCV_F17_64, RISCV_F18_64, RISCV_F19_64, RISCV_F20_64, RISCV_F21_64, RISCV_F22_64, RISCV_F23_64, RISCV_F24_64, RISCV_F25_64, RISCV_F26_64, RISCV_F27_64, RISCV_F28_64, RISCV_F29_64, RISCV_F30_64, RISCV_F31_64 }; static DecodeStatus DecodeFPR64RegisterClass(MCInst *Inst, uint64_t RegNo, uint64_t Address, const MCRegisterInfo *Decoder) { if (RegNo > sizeof(FPR64DecoderTable)) { return MCDisassembler_Fail; } // We must define our own mapping from RegNo to register identifier. // Accessing index RegNo in the register class will work in the case that // registers were added in ascending order, but not in general. unsigned Reg = FPR64DecoderTable[RegNo]; MCOperand_CreateReg0(Inst, Reg); return MCDisassembler_Success; } static DecodeStatus DecodeUImmOperand(MCInst *Inst, uint64_t Imm, int64_t Address, const MCRegisterInfo *Decoder) { MCOperand_CreateImm0(Inst, Imm); return MCDisassembler_Success; } static DecodeStatus DecodeSImmOperand_12(MCInst *Inst, uint64_t Imm, int64_t Address, const MCRegisterInfo *Decoder) { // Sign-extend the number in the bottom N = 12 bits of Imm MCOperand_CreateImm0(Inst, SignExtend64(Imm, 12)); return MCDisassembler_Success; } static DecodeStatus DecodeSImmOperandAndLsl1_13(MCInst *Inst, uint64_t Imm, int64_t Address, const MCRegisterInfo *Decoder) { // Sign-extend the number in the bottom N bits of Imm after accounting for // the fact that the N=13 bit immediate is stored in N-1 bits (the LSB is // always zero) MCOperand_CreateImm0(Inst, SignExtend64((Imm << 1), 13)); return MCDisassembler_Success; } static DecodeStatus DecodeSImmOperandAndLsl1_21(MCInst *Inst, uint64_t Imm, int64_t Address, const MCRegisterInfo *Decoder) { // Sign-extend the number in the bottom N bits of Imm after accounting for // the fact that the N=21 bit immediate is stored in N-1 bits (the LSB is // always zero) MCOperand_CreateImm0(Inst, SignExtend64((Imm << 1), 21)); return MCDisassembler_Success; } #include "RiscvGenDisassemblerTables.inc" static DecodeStatus readInstruction32(unsigned char *code, uint32_t *insn, bool isBigEndian) { assert(!isBigEndian); *insn = (code[0] << 0) | (code[1] << 8) | (code[2] << 16) | (code[3] << 24); return MCDisassembler_Success; } static DecodeStatus RISCVDisassembler_getInstruction( int mode, MCInst *instr, const uint8_t *code, size_t code_len, uint16_t *Size, uint64_t Address, bool isBigEndian, MCRegisterInfo *MRI) { uint32_t Insn; DecodeStatus Result; if (instr->flat_insn->detail) { memset(instr->flat_insn->detail, 0, sizeof(cs_detail)); } // TODO: although assuming 4-byte instructions is sufficient for RV32 and // RV64, this will need modification when supporting the compressed // instruction set extension (RVC) which uses 16-bit instructions. Other // instruction set extensions have the option of defining instructions up to // 176 bits wide. if (code_len < 4) { return MCDisassembler_Fail; } Result = readInstruction32((unsigned char*)code, &Insn, isBigEndian); if (Result == MCDisassembler_Fail) return MCDisassembler_Fail; Result = decodeInstruction(DecoderTable32, instr, Insn, Address, MRI, mode); if (Result != MCDisassembler_Fail) { *Size = 4; return Result; } return MCDisassembler_Fail; } bool RISCV_getInstruction(csh ud, const uint8_t *code, size_t code_len, MCInst *instr, uint16_t *size, uint64_t address, void *info) { cs_struct *handle = (cs_struct *)(uintptr_t)ud; DecodeStatus status = RISCVDisassembler_getInstruction(handle->mode, instr, code, code_len, size, address, MODE_IS_BIG_ENDIAN(handle->mode), (MCRegisterInfo *)info); return status == MCDisassembler_Success; } bool RISCV64_getInstruction(csh ud, const uint8_t *code, size_t code_len, MCInst *instr, uint16_t *size, uint64_t address, void *info) { return RISCV_getInstruction(ud, code, code_len, instr, size, address, info); } #define GET_REGINFO_MC_DESC #include "RiscvGenRegisterInfo.inc" void RISCV_init(MCRegisterInfo *MRI) { MCRegisterInfo_InitMCRegisterInfo(MRI, RISCVRegDesc, sizeof(RISCVRegDesc) / sizeof(RISCVRegDesc[0]), 0, 0, RISCVMCRegisterClasses, sizeof(RISCVMCRegisterClasses) / sizeof(RISCVMCRegisterClasses[0]), 0, 0, RISCVRegDiffLists, 0, RISCVSubRegIdxLists, sizeof(RISCVSubRegIdxLists) / sizeof(RISCVSubRegIdxLists[0]), 0); } #endif
31.585551
94
0.724088
bb217e753d326dbdbe2c211b53a6adba7eb0c01e
2,911
kt
Kotlin
kotlin-client/src/main/kotlin/com/couchbase/client/kotlin/view/ViewFlowItem.kt
trickster/couchbase-jvm-clients
3a9e105651b076b5ed18ce29419be0e3fd8bc8f4
[ "Apache-2.0" ]
26
2019-04-15T08:51:51.000Z
2022-02-17T18:31:35.000Z
kotlin-client/src/main/kotlin/com/couchbase/client/kotlin/view/ViewFlowItem.kt
trickster/couchbase-jvm-clients
3a9e105651b076b5ed18ce29419be0e3fd8bc8f4
[ "Apache-2.0" ]
14
2019-08-26T19:01:18.000Z
2022-03-31T05:51:08.000Z
kotlin-client/src/main/kotlin/com/couchbase/client/kotlin/view/ViewFlowItem.kt
trickster/couchbase-jvm-clients
3a9e105651b076b5ed18ce29419be0e3fd8bc8f4
[ "Apache-2.0" ]
31
2019-03-31T05:45:58.000Z
2022-03-31T07:29:31.000Z
/* * Copyright 2021 Couchbase, Inc. * * 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 com.couchbase.client.kotlin.view import com.couchbase.client.core.deps.com.fasterxml.jackson.core.type.TypeReference import com.couchbase.client.core.deps.com.fasterxml.jackson.databind.node.ObjectNode import com.couchbase.client.core.json.Mapper import com.couchbase.client.core.msg.view.ViewChunkHeader import com.couchbase.client.core.msg.view.ViewChunkTrailer import com.couchbase.client.kotlin.codec.JsonSerializer import com.couchbase.client.kotlin.codec.typeRef import kotlin.LazyThreadSafetyMode.PUBLICATION public sealed class ViewFlowItem /** * One row of a View result. */ public class ViewRow internal constructor( content: ByteArray, @property:PublishedApi internal val defaultSerializer: JsonSerializer, ) : ViewFlowItem() { private val rootNode = Mapper.decodeIntoTree(content) as ObjectNode /** * Raw key bytes. */ public val key: ByteArray = Mapper.encodeAsBytes(rootNode.get("key")) /** * Raw value bytes. */ public val value: ByteArray by lazy(PUBLICATION) { Mapper.encodeAsBytes(rootNode.get("value")) } /** * Document ID associated with this row, or null if reduction was used. */ public val id: String? by lazy(PUBLICATION) { rootNode.path("id").textValue() } public inline fun <reified T> keyAs(serializer: JsonSerializer? = null): T = (serializer ?: defaultSerializer).deserialize(key, typeRef()) public inline fun <reified T> valueAs(serializer: JsonSerializer? = null): T = (serializer ?: defaultSerializer).deserialize(value, typeRef()) override fun toString(): String { return "ViewRow(content=$rootNode)" } } /** * Metadata about View execution. Always the last item in the flow. */ public class ViewMetadata internal constructor( internal val header: ViewChunkHeader, internal val trailer: ViewChunkTrailer, ) : ViewFlowItem() { public val totalRows: Long = header.totalRows() public val debug: Map<String, Any?>? by lazy { header.debug().map { Mapper.decodeInto(it, MAP_TYPE_REF) }.orElse(null) } override fun toString(): String { return "ViewMetadata(totalRows=$totalRows, error=${trailer.error().orElse(null)} debug=${debug})" } } private val MAP_TYPE_REF = object : TypeReference<Map<String, Any?>>() {}
33.848837
105
0.722776
9112c1abca1e0671e757c2e38c878667465b761e
1,620
swift
Swift
ProgramingExampleViewController.swift
PierrePerrin/PPMusicImageShadow
8774096ab3958fd7dba7de81d4fc88fbfde21f5f
[ "MIT" ]
339
2017-03-06T22:24:29.000Z
2021-09-30T07:55:04.000Z
ProgramingExampleViewController.swift
PierrePerrin/PPMusicImageShadow
8774096ab3958fd7dba7de81d4fc88fbfde21f5f
[ "MIT" ]
1
2017-04-05T15:40:32.000Z
2017-07-25T15:38:47.000Z
ProgramingExampleViewController.swift
PierrePerrin/PPMusicImageShadow
8774096ab3958fd7dba7de81d4fc88fbfde21f5f
[ "MIT" ]
22
2017-03-06T22:24:29.000Z
2019-07-09T11:18:48.000Z
// // ProgramingExampleViewController.swift // PPMusicImageShadow // // Created by Pierre Perrin on 06/03/2017. // Copyright © 2017 Pierre Perrin. All rights reserved. // import UIKit class ProgramingExampleViewController: UIViewController { var exampleView : PPMusicImageShadow! override func viewDidLoad() { super.viewDidLoad() self.addEffectView() self.prepareExampleView() self.setImageToExampleView() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() self.exampleView.center = self.view.center } //MARK: Example func addEffectView(){ self.exampleView = PPMusicImageShadow(frame: CGRect.init(x: 0, y: 0, width: 300, height: 300)) self.view.addSubview(self.exampleView) } func setImageToExampleView(){ let image = UIImage(named: "prairie-679016_1920.jpg") self.exampleView.image = image } func prepareExampleView(){ self.exampleView.cornerRaduis = 10 self.exampleView.blurRadius = 5 } // MARK: - Navigation @IBAction func dismiss(_ sender: Any) { self.dismiss(animated: true, completion: nil) } /* // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
24.179104
106
0.637654
47fce7278c87aac7d4bec613a23d68818391afcd
94
css
CSS
docroot/themes/contrib/thunder_admin/css/layout/layout.css
DiversiCon/uc-d8-deploy
39294a57583639883bc6b9b87bf818de471aed13
[ "MIT" ]
null
null
null
docroot/themes/contrib/thunder_admin/css/layout/layout.css
DiversiCon/uc-d8-deploy
39294a57583639883bc6b9b87bf818de471aed13
[ "MIT" ]
1
2021-06-17T05:29:22.000Z
2021-06-17T05:29:22.000Z
docroot/themes/contrib/thunder_admin/css/layout/layout.css
DiversiCon/uc-d8-deploy
39294a57583639883bc6b9b87bf818de471aed13
[ "MIT" ]
null
null
null
.page-content{ margin-bottom:80px; } .layout-icon__region{ fill:#f5f5f2; stroke:#666; }
11.75
21
0.680851
fb04fd0d288280436d94208fc99bf813dc647333
656
h
C
include/Triangle.h
Liyara/JGL
b3597700fe865b929c5bd52e81add32a6c0b297c
[ "MIT" ]
null
null
null
include/Triangle.h
Liyara/JGL
b3597700fe865b929c5bd52e81add32a6c0b297c
[ "MIT" ]
null
null
null
include/Triangle.h
Liyara/JGL
b3597700fe865b929c5bd52e81add32a6c0b297c
[ "MIT" ]
null
null
null
#ifndef TRIANGLE_H #define TRIANGLE_H namespace jgl { struct Triangle : public Object { public: enum Type { STANDARD, RIGHT }; Triangle(const Position&, const Dimensions&, const Color& = Color::White); Triangle(const Position&, const Dimensions&, Type); Triangle(const Position&, const Dimensions&, Type, const Color&); Triangle(const Position&, const Dimensions&, const Color&, Type); long double area() const; private: Type type; Triangle(); jutil::Queue<jml::Vertex> generateVertices() const override; }; } #endif // TRIANGLE_H
24.296296
82
0.606707
be90aff740a1189fb6ff0ebf1f14c95cbc0f9660
696
kts
Kotlin
gradle/dexcount.gradle.kts
isuPatches/android-viewglu
a741482b3fd8ff884d5068c4f58728c3f394fe66
[ "Apache-2.0" ]
1
2021-08-03T22:31:34.000Z
2021-08-03T22:31:34.000Z
gradle/dexcount.gradle.kts
isuPatches/android-viewglu
a741482b3fd8ff884d5068c4f58728c3f394fe66
[ "Apache-2.0" ]
3
2021-08-09T13:54:07.000Z
2021-08-09T14:17:13.000Z
gradle/dexcount.gradle.kts
isuPatches/android-viewglu
a741482b3fd8ff884d5068c4f58728c3f394fe66
[ "Apache-2.0" ]
null
null
null
import com.getkeepsafe.dexcount.DexCountExtension import com.getkeepsafe.dexcount.DexMethodCountPlugin import com.getkeepsafe.dexcount.OutputFormat buildscript { repositories { mavenCentral() } dependencies { val versions = com.isupatches.android.viewglu.build.Versions classpath("com.getkeepsafe.dexcount:dexcount-gradle-plugin:${versions.DEXCOUNT}") } } plugins.apply(DexMethodCountPlugin::class) configure<DexCountExtension> { format.set(OutputFormat.TREE) includeClasses.set(true) includeFieldCount.set(true) includeTotalMethodCount.set(true) orderByMethodCount.set(true) verbose.set(false) runOnEachPackage.set(true) }
25.777778
89
0.752874
5551cd9194852cae71fc056fe57a24c56484be1f
2,588
kt
Kotlin
src/main/kotlin/me/ethanbrews/utils/block/renderer/StorageNetworkControllerBlockRenderer.kt
ethanbrews/dynamicstorage
04e237f3a9a1d7e5ab79e67881ef12731708adee
[ "CC0-1.0" ]
null
null
null
src/main/kotlin/me/ethanbrews/utils/block/renderer/StorageNetworkControllerBlockRenderer.kt
ethanbrews/dynamicstorage
04e237f3a9a1d7e5ab79e67881ef12731708adee
[ "CC0-1.0" ]
null
null
null
src/main/kotlin/me/ethanbrews/utils/block/renderer/StorageNetworkControllerBlockRenderer.kt
ethanbrews/dynamicstorage
04e237f3a9a1d7e5ab79e67881ef12731708adee
[ "CC0-1.0" ]
null
null
null
package me.ethanbrews.utils.block.renderer import me.ethanbrews.utils.block.entity.StorageNetworkControllerBlockEntity import me.ethanbrews.utils.lib.colour import net.fabricmc.api.EnvType import net.fabricmc.api.Environment import net.minecraft.client.MinecraftClient import net.minecraft.client.render.OverlayTexture import net.minecraft.client.render.VertexConsumerProvider import net.minecraft.client.render.WorldRenderer import net.minecraft.client.render.block.entity.BlockEntityRenderDispatcher import net.minecraft.client.render.block.entity.BlockEntityRenderer import net.minecraft.client.render.model.json.ModelTransformation import net.minecraft.client.util.math.MatrixStack import net.minecraft.client.util.math.Vector3f import net.minecraft.item.ItemStack import net.minecraft.item.Items import kotlin.math.sin @Environment(EnvType.CLIENT) class StorageNetworkControllerBlockRenderer(dispatcher: BlockEntityRenderDispatcher) : BlockEntityRenderer<StorageNetworkControllerBlockEntity>(dispatcher) { override fun render( be: StorageNetworkControllerBlockEntity, tickDelta: Float, matrices: MatrixStack, vertexConsumers: VertexConsumerProvider, light: Int, overlay: Int ) { val colour = if (be.isNetworkValid) colour(0x00AA00) else colour(0xFF5555) matrices.push(); val offset = sin((be.world!!.time + tickDelta) / 8.0) / 4.0 matrices.translate(0.5, 1.25 + offset, 0.5) matrices.multiply(Vector3f.POSITIVE_Y.getDegreesQuaternion((be.world!!.time + tickDelta) * 4)) val lightAbove = WorldRenderer.getLightmapCoordinates(be.world, be.pos.up()) if (be.isNetworkValid) MinecraftClient.getInstance().itemRenderer.renderItem(stackRedstone, ModelTransformation.Type.GROUND, lightAbove, overlay, matrices, vertexConsumers); else MinecraftClient.getInstance().itemRenderer.renderItem(stackGold, ModelTransformation.Type.GROUND, lightAbove, overlay, matrices, vertexConsumers); /* MinecraftClient.getInstance().blockRenderManager.renderBlock( MinecraftClient.getInstance().world?.getBlockState(be.pos)!!, be.pos, MinecraftClient.getInstance().world!!, matrices, vertexConsumers.getBuffer(RenderLayer.getSolid()).color(255, 0, 0, 255), true, Random() ) */ matrices.pop() } companion object { val stackRedstone = ItemStack(Items.REDSTONE) val stackGold = ItemStack(Items.GOLD_INGOT) } }
41.079365
162
0.732226
70cb735f8100dfbe03ed6f829f1910ccb122ba3d
18,153
c
C
new/libr/util/utype.c
benbenwt/lisa_docker
0b851223dbaecef9b27c418eae05890fea752d49
[ "Apache-2.0" ]
null
null
null
new/libr/util/utype.c
benbenwt/lisa_docker
0b851223dbaecef9b27c418eae05890fea752d49
[ "Apache-2.0" ]
1
2021-12-17T00:14:27.000Z
2021-12-17T00:14:27.000Z
new/libr/util/utype.c
benbenwt/lisa_docker
0b851223dbaecef9b27c418eae05890fea752d49
[ "Apache-2.0" ]
null
null
null
/* radare - LGPL - Copyright 2013-2020 - pancake, oddcoder, sivaramaaa */ #include <r_util.h> R_API int r_type_set(Sdb *TDB, ut64 at, const char *field, ut64 val) { const char *kind; char var[128]; sprintf (var, "link.%08"PFMT64x, at); kind = sdb_const_get (TDB, var, NULL); if (kind) { const char *p = sdb_const_get (TDB, kind, NULL); if (p) { snprintf (var, sizeof (var), "%s.%s.%s", p, kind, field); int off = sdb_array_get_num (TDB, var, 1, NULL); //int siz = sdb_array_get_num (DB, var, 2, NULL); eprintf ("wv 0x%08"PFMT64x" @ 0x%08"PFMT64x, val, at + off); return true; } eprintf ("Invalid kind of type\n"); } return false; } R_API int r_type_kind(Sdb *TDB, const char *name) { if (!name) { return -1; } const char *type = sdb_const_get (TDB, name, 0); if (!type) { return -1; } if (!strcmp (type, "enum")) { return R_TYPE_ENUM; } if (!strcmp (type, "struct")) { return R_TYPE_STRUCT; } if (!strcmp (type, "union")) { return R_TYPE_UNION; } if (!strcmp (type, "type")) { return R_TYPE_BASIC; } if (!strcmp (type, "typedef")) { return R_TYPE_TYPEDEF; } return -1; } R_API RList* r_type_get_enum (Sdb *TDB, const char *name) { char *p, var[130]; int n; if (r_type_kind (TDB, name) != R_TYPE_ENUM) { return NULL; } RList *res = r_list_new (); snprintf (var, sizeof (var), "enum.%s", name); for (n = 0; (p = sdb_array_get (TDB, var, n, NULL)); n++) { RTypeEnum *member = R_NEW0 (RTypeEnum); if (member) { char *var2 = r_str_newf ("%s.%s", var, p); if (var2) { char *val = sdb_array_get (TDB, var2, 0, NULL); if (val) { member->name = p; member->val = val; r_list_append (res, member); } else { free (member); free (var2); } } else { free (member); } } } return res; } R_API char *r_type_enum_member(Sdb *TDB, const char *name, const char *member, ut64 val) { if (r_type_kind (TDB, name) != R_TYPE_ENUM) { return NULL; } const char *q = member ? sdb_fmt ("enum.%s.%s", name, member) : sdb_fmt ("enum.%s.0x%"PFMT64x, name, val); return sdb_get (TDB, q, 0); } R_API char *r_type_enum_getbitfield(Sdb *TDB, const char *name, ut64 val) { char *q, *ret = NULL; const char *res; int i; if (r_type_kind (TDB, name) != R_TYPE_ENUM) { return NULL; } bool isFirst = true; ret = r_str_appendf (ret, "0x%08"PFMT64x" : ", val); for (i = 0; i < 32; i++) { ut32 n = 1ULL << i; if (!(val & n)) { continue; } q = sdb_fmt ("enum.%s.0x%x", name, n); res = sdb_const_get (TDB, q, 0); if (isFirst) { isFirst = false; } else { ret = r_str_append (ret, " | "); } if (res) { ret = r_str_append (ret, res); } else { ret = r_str_appendf (ret, "0x%x", n); } } return ret; } R_API ut64 r_type_get_bitsize(Sdb *TDB, const char *type) { char *query; /* Filter out the structure keyword if type looks like "struct mystruc" */ const char *tmptype; if (!strncmp (type, "struct ", 7)) { tmptype = type + 7; } else if (!strncmp (type, "union ", 6)) { tmptype = type + 6; } else { tmptype = type; } if ((strstr (type, "*(") || strstr (type, " *")) && strncmp (type, "char *", 7)) { return 32; } const char *t = sdb_const_get (TDB, tmptype, 0); if (!t) { if (!strncmp (tmptype, "enum ", 5)) { //XXX: Need a proper way to determine size of enum return 32; } return 0; } if (!strcmp (t, "type")){ query = r_str_newf ("type.%s.size", tmptype); ut64 r = sdb_num_get (TDB, query, 0); // returns size in bits free (query); return r; } if (!strcmp (t, "struct") || !strcmp (t, "union")) { query = r_str_newf ("%s.%s", t, tmptype); char *members = sdb_get (TDB, query, 0); char *next, *ptr = members; ut64 ret = 0; if (members) { do { char *name = sdb_anext (ptr, &next); if (!name) { break; } free (query); query = r_str_newf ("%s.%s.%s", t, tmptype, name); char *subtype = sdb_get (TDB, query, 0); R_FREE (query); if (!subtype) { break; } char *tmp = strchr (subtype, ','); if (tmp) { *tmp++ = 0; tmp = strchr (tmp, ','); if (tmp) { *tmp++ = 0; } int elements = r_num_math (NULL, tmp); if (elements == 0) { elements = 1; } if (!strcmp (t, "struct")) { ret += r_type_get_bitsize (TDB, subtype) * elements; } else { ut64 sz = r_type_get_bitsize (TDB, subtype) * elements; ret = sz > ret ? sz : ret; } } free (subtype); ptr = next; } while (next); free (members); } free (query); return ret; } return 0; } R_API char *r_type_get_struct_memb(Sdb *TDB, const char *type, int offset) { int i, cur_offset, next_offset = 0; char *res = NULL; if (offset < 0) { return NULL; } char* query = sdb_fmt ("struct.%s", type); char *members = sdb_get (TDB, query, 0); if (!members) { //eprintf ("%s is not a struct\n", type); return NULL; } int nargs = r_str_split (members, ','); for (i = 0; i < nargs ; i++) { const char *name = r_str_word_get0 (members, i); if (!name) { break; } query = sdb_fmt ("struct.%s.%s", type, name); char *subtype = sdb_get (TDB, query, 0); if (!subtype) { break; } int len = r_str_split (subtype, ','); if (len < 3) { free (subtype); break; } cur_offset = r_num_math (NULL, r_str_word_get0 (subtype, len - 2)); if (cur_offset > 0 && cur_offset < next_offset) { free (subtype); break; } if (!cur_offset) { cur_offset = next_offset; } if (cur_offset == offset) { res = r_str_newf ("%s.%s", type, name); free (subtype); break; } int arrsz = r_num_math (NULL, r_str_word_get0 (subtype, len - 1)); int fsize = (r_type_get_bitsize (TDB, subtype) * (arrsz ? arrsz : 1)) / 8; if (!fsize) { free (subtype); break; } next_offset = cur_offset + fsize; // Handle nested structs if (offset > cur_offset && offset < next_offset) { char *nested_type = (char *)r_str_word_get0 (subtype, 0); if (r_str_startswith (nested_type, "struct ") && !r_str_endswith (nested_type, " *")) { len = r_str_split (nested_type, ' '); if (len < 2) { free (subtype); break; } nested_type = (char *)r_str_word_get0 (nested_type, 1); char *nested_res = r_type_get_struct_memb (TDB, nested_type, offset - cur_offset); if (nested_res) { len = r_str_split(nested_res, '.'); res = r_str_newf ("%s.%s.%s", type, name, r_str_word_get0 (nested_res, len - 1)); free (nested_res); free (subtype); break; } } } free (subtype); } free (members); return res; } // XXX this function is slow! R_API RList* r_type_get_by_offset(Sdb *TDB, ut64 offset) { RList *offtypes = r_list_new (); SdbList *ls = sdb_foreach_list (TDB, true); SdbListIter *lsi; SdbKv *kv; ls_foreach (ls, lsi, kv) { // TODO: Add unions support if (!strncmp (sdbkv_value (kv), "struct", 6) && strncmp (sdbkv_key (kv), "struct.", 7)) { char *res = r_type_get_struct_memb (TDB, sdbkv_key (kv), offset); if (res) { r_list_append (offtypes, res); } } } ls_free (ls); return offtypes; } // XXX 12 is the maxstructsizedelta #define TYPE_RANGE_BASE(x) ((x)>>16) static RList *types_range_list(Sdb *db, ut64 addr) { RList *list = NULL; ut64 base = TYPE_RANGE_BASE (addr); char *s = r_str_newf ("range.%"PFMT64x, base); if (s) { char *r = sdb_get (db, s, 0); if (r) { list = r_str_split_list (r, " ", -1); } free (s); } return list; } static void types_range_del(Sdb *db, ut64 addr) { ut64 base = TYPE_RANGE_BASE (addr); const char *k = sdb_fmt ("range.%"PFMT64x, base); char valstr[SDB_NUM_BUFSZ]; const char *v = sdb_itoa (addr, valstr, SDB_NUM_BASE); sdb_array_remove (db, k, v, 0); } static void types_range_add(Sdb *db, ut64 addr) { ut64 base = TYPE_RANGE_BASE (addr); const char *k = sdb_fmt ("range.%"PFMT64x, base); (void)sdb_array_add_num (db, k, addr, 0); } R_API char *r_type_link_at(Sdb *TDB, ut64 addr) { if (addr == UT64_MAX) { return NULL; } const char *query = sdb_fmt ("link.%08"PFMT64x, addr); char *res = sdb_get (TDB, query, 0); if (!res) { // resolve struct memb if possible for given addr RList *list = types_range_list (TDB, addr); RListIter *iter; const char *s; r_list_foreach (list, iter, s) { ut64 laddr = r_num_get (NULL, s); if (addr > laddr) { int delta = addr - laddr; const char *lk = sdb_fmt ("link.%08"PFMT64x, laddr); char *k = sdb_get (TDB, lk, 0); res = r_type_get_struct_memb (TDB, k, delta); if (res) { break; } free (k); } } } return res; } R_API int r_type_set_link(Sdb *TDB, const char *type, ut64 addr) { if (sdb_const_get (TDB, type, 0)) { char *laddr = r_str_newf ("link.%08"PFMT64x, addr); sdb_set (TDB, laddr, type, 0); types_range_add (TDB, addr); free (laddr); return true; } return false; } R_API int r_type_link_offset(Sdb *TDB, const char *type, ut64 addr) { if (sdb_const_get (TDB, type, 0)) { char *laddr = r_str_newf ("offset.%08"PFMT64x, addr); sdb_set (TDB, laddr, type, 0); free (laddr); return true; } return false; } R_API int r_type_unlink(Sdb *TDB, ut64 addr) { char *laddr = sdb_fmt ("link.%08"PFMT64x, addr); sdb_unset (TDB, laddr, 0); types_range_del (TDB, addr); return true; } static char *fmt_struct_union(Sdb *TDB, char *var, bool is_typedef) { // assumes var list is sorted by offset.. should do more checks here char *p = NULL, *vars = NULL, var2[132], *fmt = NULL; size_t n; char *fields = r_str_newf ("%s.fields", var); char *nfields = (is_typedef) ? fields : var; for (n = 0; (p = sdb_array_get (TDB, nfields, n, NULL)); n++) { char *struct_name = NULL; const char *tfmt = NULL; bool isStruct = false; bool isEnum = false; bool isfp = false; snprintf (var2, sizeof (var2), "%s.%s", var, p); size_t alen = sdb_array_size (TDB, var2); int elements = sdb_array_get_num (TDB, var2, alen - 1, NULL); char *type = sdb_array_get (TDB, var2, 0, NULL); if (type) { char var3[128] = {0}; // Handle general pointers except for char * if ((strstr (type, "*(") || strstr (type, " *")) && strncmp (type, "char *", 7)) { isfp = true; } else if (r_str_startswith (type, "struct ")) { struct_name = type + 7; // TODO: iterate over all the struct fields, and format the format and vars snprintf (var3, sizeof (var3), "struct.%s", struct_name); tfmt = sdb_const_get (TDB, var3, NULL); isStruct = true; } else { // special case for char[]. Use char* format type without * if (!strcmp (type, "char") && elements > 0) { tfmt = sdb_const_get (TDB, "type.char *", NULL); if (tfmt && *tfmt == '*') { tfmt++; } } else { if (r_str_startswith (type, "enum ")) { snprintf (var3, sizeof (var3), "%s", type + 5); isEnum = true; } else { snprintf (var3, sizeof (var3), "type.%s", type); } tfmt = sdb_const_get (TDB, var3, NULL); } } if (isfp) { // consider function pointer as void * for printing fmt = r_str_append (fmt, "p"); vars = r_str_append (vars, p); vars = r_str_append (vars, " "); } else if (tfmt) { (void) r_str_replace_ch (type, ' ', '_', true); if (elements > 0) { fmt = r_str_appendf (fmt, "[%d]", elements); } if (isStruct) { fmt = r_str_append (fmt, "?"); if (struct_name) { vars = r_str_appendf (vars, "(%s)%s", struct_name, p); } vars = r_str_append (vars, " "); } else if (isEnum) { fmt = r_str_append (fmt, "E"); vars = r_str_appendf (vars, "(%s)%s", type + 5, p); vars = r_str_append (vars, " "); } else { fmt = r_str_append (fmt, tfmt); vars = r_str_append (vars, p); vars = r_str_append (vars, " "); } } else { eprintf ("Cannot resolve type '%s'\n", var3); } free (type); } free (p); } free (fields); fmt = r_str_append (fmt, " "); fmt = r_str_append (fmt, vars); free (vars); return fmt; } R_API char *r_type_format(Sdb *TDB, const char *t) { char var[130], var2[132]; const char *kind = sdb_const_get (TDB, t, NULL); if (!kind) { return NULL; } // only supports struct atm snprintf (var, sizeof (var), "%s.%s", kind, t); if (!strcmp (kind, "type")) { const char *fmt = sdb_const_get (TDB, var, NULL); if (fmt) { return strdup (fmt); } } else if (!strcmp (kind, "struct") || !strcmp (kind, "union")) { return fmt_struct_union(TDB, var, false); } if (!strcmp (kind, "typedef")) { snprintf (var2, sizeof (var2), "typedef.%s", t); const char *type = sdb_const_get (TDB, var2, NULL); // only supports struct atm if (type && !strcmp (type, "struct")) { return fmt_struct_union (TDB, var, true); } } return NULL; } R_API void r_type_del(Sdb *TDB, const char *name) { const char *kind = sdb_const_get (TDB, name, 0); if (!kind) { return; } if (!strcmp (kind, "type")) { sdb_unset (TDB, sdb_fmt ("type.%s", name), 0); sdb_unset (TDB, sdb_fmt ("type.%s.size", name), 0); sdb_unset (TDB, sdb_fmt ("type.%s.meta", name), 0); sdb_unset (TDB, name, 0); } else if (!strcmp (kind, "struct") || !strcmp (kind, "union")) { int i, n = sdb_array_length(TDB, sdb_fmt ("%s.%s", kind, name)); char *elements_key = r_str_newf ("%s.%s", kind, name); for (i = 0; i< n; i++) { char *p = sdb_array_get (TDB, elements_key, i, NULL); sdb_unset (TDB, sdb_fmt ("%s.%s", elements_key, p), 0); free (p); } sdb_unset (TDB, elements_key, 0); sdb_unset (TDB, name, 0); free (elements_key); } else if (!strcmp (kind, "func")) { int i, n = sdb_num_get (TDB, sdb_fmt ("func.%s.args", name), 0); for (i = 0; i < n; i++) { sdb_unset (TDB, sdb_fmt ("func.%s.arg.%d", name, i), 0); } sdb_unset (TDB, sdb_fmt ("func.%s.ret", name), 0); sdb_unset (TDB, sdb_fmt ("func.%s.cc", name), 0); sdb_unset (TDB, sdb_fmt ("func.%s.noreturn", name), 0); sdb_unset (TDB, sdb_fmt ("func.%s.args", name), 0); sdb_unset (TDB, name, 0); } else if (!strcmp (kind, "enum")) { RList *list = r_type_get_enum (TDB, name); RTypeEnum *member; RListIter *iter; r_list_foreach (list, iter, member) { sdb_unset (TDB, sdb_fmt ("enum.%s.%s", name, member->name), 0); sdb_unset (TDB, sdb_fmt ("enum.%s.%s", name, member->val), 0); } sdb_unset (TDB, name, 0); r_list_free (list); } else if (!strcmp (kind, "typedef")) { RStrBuf buf; r_strbuf_init (&buf); r_strbuf_setf (&buf, "typedef.%s", name); sdb_unset (TDB, r_strbuf_get (&buf), 0); r_strbuf_fini (&buf); sdb_unset (TDB, name, 0); } else { eprintf ("Unrecognized type kind \"%s\"\n", kind); } } // Function prototypes api R_API int r_type_func_exist(Sdb *TDB, const char *func_name) { const char *fcn = sdb_const_get (TDB, func_name, 0); return fcn && !strcmp (fcn, "func"); } R_API const char *r_type_func_ret(Sdb *TDB, const char *func_name){ const char *query = sdb_fmt ("func.%s.ret", func_name); return sdb_const_get (TDB, query, 0); } R_API int r_type_func_args_count(Sdb *TDB, const char *func_name) { const char *query = sdb_fmt ("func.%s.args", func_name); return sdb_num_get (TDB, query, 0); } R_API R_OWN char *r_type_func_args_type(Sdb *TDB, R_NONNULL const char *func_name, int i) { const char *query = sdb_fmt ("func.%s.arg.%d", func_name, i); char *ret = sdb_get (TDB, query, 0); if (ret) { char *comma = strchr (ret, ','); if (comma) { *comma = 0; return ret; } free (ret); } return NULL; } R_API const char *r_type_func_args_name(Sdb *TDB, R_NONNULL const char *func_name, int i) { const char *query = sdb_fmt ("func.%s.arg.%d", func_name, i); const char *get = sdb_const_get (TDB, query, 0); if (get) { char *ret = strchr (get, ','); return ret == 0 ? ret : ret + 1; } return NULL; } #define MIN_MATCH_LEN 4 static inline bool is_function(const char *name) { return name && !strcmp("func", name); } static R_OWN char *type_func_try_guess(Sdb *TDB, R_NONNULL char *name) { if (strlen(name) < MIN_MATCH_LEN) { return NULL; } const char *res = sdb_const_get(TDB, name, NULL); if (is_function(res)) { return strdup(name); } return NULL; } static inline bool is_auto_named(char *func_name, size_t slen) { return slen > 4 && (r_str_startswith (func_name, "fcn.") || r_str_startswith (func_name, "loc.")); } static inline bool has_r_prefixes(char *func_name, int offset, size_t slen) { return slen > 4 && (offset + 3 < slen) && func_name[offset + 3] == '.'; } static char *strip_r_prefixes(char *func_name, size_t slen) { // strip r2 prefixes (sym, sym.imp, etc') int offset = 0; while (has_r_prefixes(func_name, offset, slen)) { offset += 4; } return func_name + offset; } static char *strip_common_prefixes_stdlib(char *func_name) { // strip common prefixes from standard lib functions if (r_str_startswith (func_name, "__isoc99_")) { func_name += 9; } else if (r_str_startswith (func_name, "__libc_") && !strstr(func_name, "_main")) { func_name += 7; } else if (r_str_startswith (func_name, "__GI_")) { func_name += 5; } return func_name; } static char *strip_dll_prefix(char *func_name) { char *tmp = strstr(func_name, "dll_"); if (tmp) { return tmp + 3; } return func_name; } static void clean_function_name(char *func_name) { char *last = (char *)r_str_lchr (func_name, '_'); if (!last || !r_str_isnumber(last + 1)) { return; } *last = '\0'; } // TODO: // - symbol names are long and noisy, some of them might not be matched due // to additional information added around name R_API R_OWN char *r_type_func_guess(Sdb *TDB, R_NONNULL char *func_name) { char *str = func_name; char *result = NULL; r_return_val_if_fail (TDB, false); r_return_val_if_fail (func_name, false); size_t slen = strlen (str); if (slen < MIN_MATCH_LEN || is_auto_named(str, slen)) { return NULL; } str = strip_r_prefixes(str, slen); str = strip_common_prefixes_stdlib(str); str = strip_dll_prefix(str); if ((result = type_func_try_guess (TDB, str))) { return result; } str = strdup (str); clean_function_name(str); if (*str == '_' && (result = type_func_try_guess (TDB, str + 1))) { free (str); return result; } free (str); return result; }
26.578331
99
0.610147
ff961c7ecb05166a6783bf4a04c271c21bbf25f4
2,779
dart
Dart
lib/widget/drawer/drawer.dart
MysteRys337/contas-flutter
ba17ee309b775d64297c73ab0ecd41cb4800540a
[ "MIT" ]
1
2021-03-16T15:44:29.000Z
2021-03-16T15:44:29.000Z
lib/widget/drawer/drawer.dart
MysteRys337/todo-flutter
ba17ee309b775d64297c73ab0ecd41cb4800540a
[ "MIT" ]
null
null
null
lib/widget/drawer/drawer.dart
MysteRys337/todo-flutter
ba17ee309b775d64297c73ab0ecd41cb4800540a
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; import 'package:todo/provider/auth.dart'; import 'package:todo/provider/theme_changer.dart'; import 'package:todo/screens/configuration.dart'; class AppDrawer extends StatelessWidget { @override Widget build(BuildContext context) { final currTheme = Provider.of<ThemeChanger>(context).currTheme; final user = Provider.of<AuthProvider>(context).currUser; return ClipRRect( borderRadius: BorderRadius.only( topRight: const Radius.circular(35), bottomRight: const Radius.circular(35)), child: Drawer( child: ListView( padding: EdgeInsets.zero, children: <Widget>[ DrawerHeader( child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ CircleAvatar( backgroundColor: currTheme == ThemeType.light ? Colors.yellowAccent[100] : Colors.purpleAccent[900], radius: 40, child: Text( user.initials, style: Theme.of(context).textTheme.headline3, ), ), const SizedBox( height: 15, ), Text( user.name, style: Theme.of(context).textTheme.headline1, ), Text(user.email) ], ), decoration: BoxDecoration(color: Theme.of(context).primaryColor)), ListTile( leading: Icon(Icons.settings, color: currTheme == ThemeType.light ? Colors.black : Colors.white), title: Text( 'Configurações', style: Theme.of(context).textTheme.headline1, ), onTap: () => Navigator.of(context).pushNamed(Configuration.routeName)), ListTile( leading: Icon( Icons.exit_to_app, color: Colors.red, ), title: Text( 'Logout', style: Theme.of(context) .textTheme .headline1 .copyWith(color: Colors.red), ), onTap: () { Provider.of<ThemeChanger>(context, listen: false) .setTheme(ThemeType.light); Provider.of<AuthProvider>(context, listen: false).logout(); }) ], )), ); } }
35.177215
80
0.486866
d0ea1cfb8264853e260efac9b21a3c9d68676ccc
567
css
CSS
third_party/libSBML-5.11.0-Source/docs/src/css/libsbml-python-stylesheet.css
gitter-badger/sbmlsolver
c92936832297ea1d2ad7f17223b68ada43c8f0b2
[ "Apache-2.0" ]
null
null
null
third_party/libSBML-5.11.0-Source/docs/src/css/libsbml-python-stylesheet.css
gitter-badger/sbmlsolver
c92936832297ea1d2ad7f17223b68ada43c8f0b2
[ "Apache-2.0" ]
null
null
null
third_party/libSBML-5.11.0-Source/docs/src/css/libsbml-python-stylesheet.css
gitter-badger/sbmlsolver
c92936832297ea1d2ad7f17223b68ada43c8f0b2
[ "Apache-2.0" ]
null
null
null
/** * @file libsbml-python-stylesheet.css * @brief Additional stylesheet used for Python documentation. * @author Michael Hucka * * This file is part of libSBML. Please visit http://sbml.org for more * information about SBML, and the latest version of libSBML. */ .memdoc > p:first-child:after { content: "The Python method signature(s) are as follows:"; } .contents div.textblock div.fragment { padding-left: 0.25em !important; /* Overrides libsbml-doxygen-stylesheet */ padding-top: 0 !important; padding-bottom: 0.25em !important; }
29.842105
80
0.707231
9d41051efa7bfda26b2c0bc23ac82a890cef8054
692
html
HTML
manuscript/page-100/body.html
marvindanig/a-guide-to-health
3d515e508e76e20cdef85b1143f9180ccaa20824
[ "BlueOak-1.0.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
manuscript/page-100/body.html
marvindanig/a-guide-to-health
3d515e508e76e20cdef85b1143f9180ccaa20824
[ "BlueOak-1.0.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
manuscript/page-100/body.html
marvindanig/a-guide-to-health
3d515e508e76e20cdef85b1143f9180ccaa20824
[ "BlueOak-1.0.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
<div class="leaf flex"><div class="inner justify"><h4>Chapter Vii</h4><h3>Exercise</h3><p class=" stretch-last-line start-chapter">Exercise is as much of a vital necessity for man as air, water and food, in the sense that no man who does not take exercise regularly, can be perfectly healthy. By “exercise” we do not mean merely walking, or games like hockey, football, and cricket; we include under the term all physical and mental activity. Exercise, even as food, is as essential to the mind as to the body. The mind is much weakened by want of exercise as the body, and a feeble mind is, indeed, a form of disease. An athlete, for instance, who is an expert in wrestling,</p></div> </div>
692
692
0.757225
19ff83c4514e6849bc7d811f28efd3b989b2124a
9,606
go
Go
todoist/api.go
seanrees/tripist
b5ee4389a25b28173e1a9dcd69990f0d2b83bc03
[ "MIT" ]
3
2016-04-24T22:49:49.000Z
2022-01-31T22:29:16.000Z
todoist/api.go
seanrees/tripist
b5ee4389a25b28173e1a9dcd69990f0d2b83bc03
[ "MIT" ]
null
null
null
todoist/api.go
seanrees/tripist
b5ee4389a25b28173e1a9dcd69990f0d2b83bc03
[ "MIT" ]
null
null
null
package todoist import ( "encoding/json" "fmt" "io/ioutil" "log" "net/url" "strconv" "strings" "time" "github.com/seanrees/tripist/tasks" "github.com/twinj/uuid" "golang.org/x/oauth2" ) const ( ApiPath = "https://todoist.com/API/v8/sync" ) func PTR(s string) *string { return &s } // Removes special characters from the project name. // Todoist only supports these characters in project names: - _ and . // They specifically call out # " ( ) | & ! , as exclusions -- so we'll // start with these. // // Src: https://todoist.com/help/articles/create-a-project func rewriteProjectName(s string) string { ret := s chars := []string{"#", "\"", "(", ")", "|", "&", "!", ","} for _, c := range chars { ret = strings.ReplaceAll(ret, c, "") } return ret } type SyncV8API struct { token *oauth2.Token } func NewSyncV8API(t *oauth2.Token) *SyncV8API { return &SyncV8API{token: t} } func (s *SyncV8API) makeRequest(path string, data url.Values, obj interface{}) error { c := buildConfig().Client(oauth2.NoContext, s.token) resp, err := c.PostForm(path, data) if err != nil { return err } defer resp.Body.Close() j, err := ioutil.ReadAll(resp.Body) if err != nil { return err } if err := json.Unmarshal(j, &obj); err != nil { return err } return nil } // Reads specific types and returns a ReadResponse. Possible types are in constants: // Projects, Items. func (s *SyncV8API) Read(types []string) (ReadResponse, error) { resp := ReadResponse{} params := url.Values{} params.Add("token", s.token.AccessToken) params.Add("sync_token", "*") t, err := json.Marshal(types) if err != nil { return resp, nil } params.Add("resource_types", string(t)) if err := s.makeRequest(ApiPath, params, &resp); err != nil { return resp, err } return resp, nil } func (s *SyncV8API) Write(c Commands) (WriteResponse, error) { resp := WriteResponse{} params := url.Values{} params.Add("token", s.token.AccessToken) cmds, err := json.Marshal(c) if err != nil { return resp, nil } params.Add("commands", string(cmds)) log.Printf("Writing %d commands to Todoist", len(c)) if err := s.makeRequest(ApiPath, params, &resp); err != nil { return resp, err } if errs := s.checkErrors(&c, &resp); len(errs) > 0 { for _, e := range errs { log.Printf("Write error from Todoist: %s", e.Message) } return resp, fmt.Errorf("write failed for %d/%d commands, call checkErrors", len(errs), len(c)) } return resp, nil } func (s *SyncV8API) checkErrors(cmds *Commands, r *WriteResponse) []writeError { var ret []writeError uuidTbl := make(map[string]WriteItem) for _, c := range *cmds { uuidTbl[*c.UUID] = c } for uuid, i := range r.SyncStatus { msg := "" handled := false // If it's a string, it should be just "ok" -- if not, that's an // unexpected state from Todoist. if state, ok := i.(string); ok { if state != "ok" { msg = fmt.Sprintf("unexpected error code %q (should be map or 'ok')", state) } handled = true } // If it's an error, it should be a map with numerous properties (like: // "error", "error_code", etc. if m, ok := i.(map[string]interface{}); ok { code, cok := m["error_code"] if !cok { code = "(no error_code)" } err, eok := m["error"] if !eok { err = "(no error message)" } tag, tagok := m["error_tag"] if !tagok { tag = "(no error_tag)" } msg = fmt.Sprintf("sync %q error code %v: %v", tag, code, err) handled = true } if !handled { // If we got here, then we got an unknown response from Todoist. Sigh. msg = fmt.Sprintf("unknown response type %T from Todoist, data: %v", i, i) } c, ok := uuidTbl[uuid] if !ok { msg += ", error for a different UUID than asked" } if len(msg) > 0 { msg += fmt.Sprintf(" (uuid %s)", uuid) ret = append(ret, writeError{Message: msg, Item: c}) } } return ret } func (s *SyncV8API) listItems(p *Project) ([]Item, error) { resp, err := s.Read([]string{Items}) if err != nil { log.Printf("Could not read Todoist items: %v", err) return nil, err } var ret []Item for _, i := range resp.Items { if i.ProjectIdInt() == *p.Id { ret = append(ret, i) } } log.Printf("Loaded %d items (%d for this project) from Todoist", len(resp.Items), len(ret)) return ret, nil } func (s *SyncV8API) findProject(name string) (*Project, error) { resp, err := s.Read([]string{Projects}) if err != nil { log.Printf("Could not read Todoist projects: %v", err) return nil, err } rp := rewriteProjectName(name) for _, p := range resp.Projects { if *p.Name == rp { log.Printf("Found existing project %q id=%d", *p.Name, *p.Id) return &p, nil } } return nil, nil } func (s *SyncV8API) createProject(name, tempId string) WriteItem { return WriteItem{ Type: PTR(ProjectAdd), TempId: PTR(tempId), UUID: PTR(uuid.NewV4().String()), Args: Project{Name: PTR(rewriteProjectName(name))}} } func (s *SyncV8API) deleteProject(p *Project) WriteItem { return WriteItem{ Type: PTR(ProjectDelete), UUID: PTR(uuid.NewV4().String()), Args: IdContainer{Id: *p.Id}} } func (s *SyncV8API) createItem(projId string, parent *string, t tasks.Task) WriteItem { log.Printf("Creating task %q (pos=%d) due %s", t.Content, t.Position, t.DueDateUTC.Format(time.RFC3339)) // Todoist does not deal well with ItemOrder = 0; it won't honour order with // something at zero. pos := t.Position + 1 return WriteItem{ Type: PTR(ItemAdd), TempId: PTR(uuid.NewV4().String()), UUID: PTR(uuid.NewV4().String()), Args: Item{ Content: &t.Content, ParentId: parent, ChildOrder: &pos, Due: &Due{ Date: t.DueDateUTC.Format(time.RFC3339), Timezone: PTR("UTC"), }, ProjectId: &projId}} } func (s *SyncV8API) updateItem(i Item, t tasks.Task) WriteItem { log.Printf("Updating task %q (pos=%d) due %s", t.Content, t.Position, t.DueDateUTC.Format(time.RFC3339)) // Todoist does not deal well with ItemOrder = 0; it won't honour order with // something at zero. pos := t.Position + 1 i.Due.Date = t.DueDateUTC.Format(time.RFC3339) i.Due.Timezone = PTR("UTC") i.ChildOrder = &pos return WriteItem{ Type: PTR(ItemUpdate), TempId: PTR(uuid.NewV4().String()), UUID: PTR(uuid.NewV4().String()), Args: i} } func (s *SyncV8API) deleteItem(i Item) WriteItem { return WriteItem{ Type: PTR(ItemDelete), UUID: PTR(uuid.NewV4().String()), Args: IdContainer{Id: *i.Id}} } // Returns a tasks.Project, whether or not it was found, and any error. func (s *SyncV8API) LoadProject(name string) (tasks.Project, bool, error) { ret := tasks.Project{Name: name} found := false p, err := s.findProject(name) switch { case err != nil: return ret, found, err case p == nil: return ret, found, nil } found = true li, err := s.listItems(p) if err != nil { return ret, found, err } parents := []int{0} for _, i := range li { if !i.Valid() { log.Printf("Ignoring invalid item: %s", i) continue } var due time.Time if i.Due == nil { log.Printf("No due date for %q, using empty value", *i.Content) } else { due, err = time.ParseInLocation(time.RFC3339, i.Due.Date, time.UTC) if err != nil { log.Printf("Could not parse %q: %v (ignoring, may generate diffs)", i.Due.Date, err) } } // Remapping task hierarchy onto indentation levels. indent := 0 if i.ParentId != nil { for idx, id := range parents { if id == i.ParentIdInt() { indent = idx + 1 } } for len(parents) < indent+1 { parents = append(parents, 0) } parents[indent] = *i.Id } else { parents[0] = *i.Id } ret.Tasks = append(ret.Tasks, tasks.Task{ Content: *i.Content, DueDateUTC: due, // For historical reasons in Todoist, we're 1-based. Indent: indent + 1, Completed: *i.Checked == 1, Position: (*i.ChildOrder) - 1}) } ret.External = &projectItems{ProjectId: *p.Id, Items: li} return ret, found, nil } func (s *SyncV8API) CreateProject(p tasks.Project) error { tempId := uuid.NewV4().String() cmds := Commands{s.createProject(p.Name, tempId)} cmds = append(cmds, s.addTasks(tempId, p.Tasks)...) _, err := s.Write(cmds) return err } func (s *SyncV8API) addTasks(tempId string, ts []tasks.Task) Commands { var cmds Commands // Support indent -> parentId conversion. max := 0 for _, t := range ts { if t.Indent > max { max = t.Indent } } parents := make([]*string, max+1) for _, t := range ts { i := s.createItem(tempId, parents[t.Indent-1], t) parents[t.Indent] = i.TempId cmds = append(cmds, i) } return cmds } func (s *SyncV8API) UpdateProject(p tasks.Project, diffs []tasks.Diff) error { tp, ok := p.External.(*projectItems) if !ok { return fmt.Errorf("missing or invalid external project pointer on %q", p.Name) } var cmds Commands var adds []tasks.Task for _, d := range diffs { switch d.Type { case tasks.Added: adds = append(adds, d.Task) case tasks.Changed: for _, i := range tp.Items { if *i.Content == d.Task.Content { cmds = append(cmds, s.updateItem(i, d.Task)) break } } case tasks.Removed: log.Printf("Not removing missing task: %q", d.Task.Content) } } // Sigh. Todoist's API is inconsistent here; in Create, we make a string but get // back an int. So we need to make it a string again. projectId := strconv.Itoa(tp.ProjectId) cmds = append(cmds, s.addTasks(projectId, adds)...) if len(cmds) > 0 { _, err := s.Write(cmds) return err } else { log.Printf("No commands to run to update project %q", p.Name) } return nil }
23.25908
105
0.634187
d25fe1fbcdc95f0c19fb58e47c0b5983c630900d
1,226
php
PHP
resources/views/pages/snooker.blade.php
BisiDavi/the-hmi
8299b78ce93a51497c697abcab8e5d35c062b131
[ "MIT" ]
1
2020-10-05T03:17:49.000Z
2020-10-05T03:17:49.000Z
resources/views/pages/snooker.blade.php
BisiDavi/the-hmi
8299b78ce93a51497c697abcab8e5d35c062b131
[ "MIT" ]
null
null
null
resources/views/pages/snooker.blade.php
BisiDavi/the-hmi
8299b78ce93a51497c697abcab8e5d35c062b131
[ "MIT" ]
null
null
null
@extends('layout') @section('title') Snooker Returns - @endsection @section('link') <link rel="stylesheet" href="css/pages/snooker.css"> @endsection @section('content') <div class="container-fluid snooker-return"> <div class="banner"> <div class="banner-text"> <h1 class="banner-title text-center text-dark"> Snooker Returns </h1> <p class="breadcrumbs text-center"> <a href="/">Home</a> / <a href="/latest-news"> Latest News </a> / Snooker Returns</p> </div> </div> <div class="uploaded-post"> <p>Great News Snooker Fans! – Snooker is now back at the HMI with a few restrictions. Call 01323 840459 to book by the hour.</p> <img src="{{ asset('images/snooker_image.png') }}" alt="HMI - Snooker is back at the HMI"> </div> <div class="commment m-auto"> <h3 class="text-center text-dark">Leave a Reply</h3> <hr class="m-auto w-25"> <p class="text-center">Logged in as <a href="#GuestUser">Guest User.</a><a href="#logout">Log out?</a></p> </div> <a class="postbutton" href="#button"> <button class="btn btn-light">Post Comment</button> </a> </div> @endsection
30.65
120
0.595432
cb70fc87d6e440bbbb89b9220436e7352de34033
2,722
html
HTML
django/templates/admin_index.html
dellsystem/new-socialist
64352ee0025267f93598b1ab7f5a3dabb3f8922e
[ "MIT" ]
3
2019-02-07T10:46:38.000Z
2020-09-23T12:29:11.000Z
django/templates/admin_index.html
dellsystem/new-socialist
64352ee0025267f93598b1ab7f5a3dabb3f8922e
[ "MIT" ]
30
2018-03-28T13:47:20.000Z
2022-01-13T00:37:39.000Z
django/templates/admin_index.html
dellsystem/new-socialist
64352ee0025267f93598b1ab7f5a3dabb3f8922e
[ "MIT" ]
1
2020-04-23T15:25:56.000Z
2020-04-23T15:25:56.000Z
{% extends "admin/base_site.html" %} {% load i18n static admin_stats %} {% block breadcrumbs %} {% endblock %} {% block content %} <div class="ui container"> <div class="ui segment"> <div class="ui middle aligned stackable grid"> <div class="ui four wide column"> <a class="ui green fluid icon button" href="{% url 'editor:journal_article_add' %}"> Add a new article <i class="plus icon"></i> </a> <br /> <a class="ui blue fluid icon button" href="{% url 'editor:journal_article_changelist' %}"> Manage existing articles </a> </div> <div class="ui twelve wide column"> {% show_article_stats %} </div> </div> </div> <br /> <h1>Article calendar</h1> {% show_article_calendar %} <br /> <div class="ui segment"> <h2 class="ui center aligned header">Other website management</h2> <div class="ui five column doubling grid"> <div class="column"> <h3 class="ui icon center aligned header"> <i class="money icon"></i> <a href="{% url 'editor:journal_commission_changelist' %}"> Commissions </a> </h3> </div> <div class="column"> <h3 class="ui icon center aligned header"> <i class="archive icon"></i> <a href="{% url 'editor:cms_page_changelist' %}"> Pages </a> </h3> </div> <div class="column"> <h3 class="ui icon center aligned header"> <i class="tags icon"></i> <a href="{% url 'editor:journal_tag_changelist' %}"> Tags </a> </h3> </div> <div class="column"> <h3 class="ui icon center aligned header"> <i class="users icon"></i> <a href="{% url 'editor:journal_author_changelist' %}"> Authors </a> </h3> </div> <div class="column"> <h3 class="ui icon center aligned header"> <i class="image outline icon"></i> <a href="{% url 'editor:uploads_imageupload_changelist' %}"> Images </a> </h3> </div> </div> </div> </div> {% endblock %}
34.897436
80
0.425055
f4ff93083540b2358cbeab58be10e843031c6cf2
594
dart
Dart
tests/language_2/regress/regress32353_2_test.dart
TheRakeshPurohit/sdk
2885ecc42664e4972343addeb73beb892f4737ea
[ "BSD-3-Clause" ]
8,969
2015-05-16T16:49:24.000Z
2022-03-31T19:54:40.000Z
tests/language_2/regress/regress32353_2_test.dart
Fareed-Ahmad7/sdk
5183ba3ca4fe3787cae3c0a6cc7f8748ff01bcf5
[ "BSD-3-Clause" ]
30,202
2015-05-17T02:27:45.000Z
2022-03-31T22:54:46.000Z
tests/language_2/regress/regress32353_2_test.dart
Fareed-Ahmad7/sdk
5183ba3ca4fe3787cae3c0a6cc7f8748ff01bcf5
[ "BSD-3-Clause" ]
1,619
2015-05-16T21:36:42.000Z
2022-03-29T20:36:59.000Z
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // @dart = 2.9 // The following compile-time error is expected: // // Error: 'D' can't implement both '#lib1::B<#lib1::D::X, #lib1::D::Y>' and // '#lib1::B<#lib1::D::X, #lib1::A>' // class D<X, Y> extends B<X, Y> with C<X> {} // ~ class A {} class B<X, Y> {} mixin C<X> on B<X, A> {} class /*@compile-error=unspecified*/ D<X, Y> extends B<X, Y> with C {} main() {}
25.826087
77
0.614478
22e89b2d01d23afc28a18508ba84be9b68dfa153
4,887
c
C
Sviluppo_software_in_gruppi_di_lavoro_complessi/Esercizi_Eiffel/Eiffel User Files/19.05/projects/RingBuffer/EIFGENs/ringbuffer/W_code/C2/in994d.c
katema-official/Universita_magistrale_anno_1.1
ee63415b8a4e9b34f704f253a272d0f0a8c247a4
[ "MIT" ]
null
null
null
Sviluppo_software_in_gruppi_di_lavoro_complessi/Esercizi_Eiffel/Eiffel User Files/19.05/projects/RingBuffer/EIFGENs/ringbuffer/W_code/C2/in994d.c
katema-official/Universita_magistrale_anno_1.1
ee63415b8a4e9b34f704f253a272d0f0a8c247a4
[ "MIT" ]
null
null
null
Sviluppo_software_in_gruppi_di_lavoro_complessi/Esercizi_Eiffel/Eiffel User Files/19.05/projects/RingBuffer/EIFGENs/ringbuffer/W_code/C2/in994d.c
katema-official/Universita_magistrale_anno_1.1
ee63415b8a4e9b34f704f253a272d0f0a8c247a4
[ "MIT" ]
null
null
null
/* * Class INET6_ADDRESS */ #include "eif_macros.h" #ifdef __cplusplus extern "C" { #endif static const EIF_TYPE_INDEX egt_0_994 [] = {0xFF01,232,0xFFFF}; static const EIF_TYPE_INDEX egt_1_994 [] = {0xFF01,245,993,0xFFFF}; static const EIF_TYPE_INDEX egt_2_994 [] = {0xFF01,993,0xFFFF}; static const EIF_TYPE_INDEX egt_3_994 [] = {0,0xFFFF}; static const EIF_TYPE_INDEX egt_4_994 [] = {0,0xFFFF}; static const EIF_TYPE_INDEX egt_5_994 [] = {0xFF01,993,0xFFFF}; static const EIF_TYPE_INDEX egt_6_994 [] = {0xFF01,993,0xFFFF}; static const EIF_TYPE_INDEX egt_7_994 [] = {0,0xFFFF}; static const EIF_TYPE_INDEX egt_8_994 [] = {0xFF01,14,0xFFFF}; static const EIF_TYPE_INDEX egt_9_994 [] = {0xFF01,232,0xFFFF}; static const EIF_TYPE_INDEX egt_10_994 [] = {0xFF01,232,0xFFFF}; static const EIF_TYPE_INDEX egt_11_994 [] = {0xFF01,15,0xFFFF}; static const EIF_TYPE_INDEX egt_12_994 [] = {0xFF01,993,0xFFFF}; static const EIF_TYPE_INDEX egt_13_994 [] = {0xFF01,232,0xFFFF}; static const EIF_TYPE_INDEX egt_14_994 [] = {0xFF01,232,0xFFFF}; static const EIF_TYPE_INDEX egt_15_994 [] = {0xFF01,453,209,0xFFFF}; static const EIF_TYPE_INDEX egt_16_994 [] = {0xFF01,171,0xFFFF}; static const EIF_TYPE_INDEX egt_17_994 [] = {0xFF01,453,209,0xFFFF}; static const EIF_TYPE_INDEX egt_18_994 [] = {0xFF01,232,0xFFFF}; static const struct desc_info desc_994[] = { {EIF_GENERIC(NULL), 0xFFFFFFFF, 0xFFFFFFFF}, {EIF_GENERIC(egt_0_994), 0, 0xFFFFFFFF}, {EIF_GENERIC(egt_1_994), 1, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 2, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 3, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 4, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 5, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 6, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 7, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 8, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 9, 0xFFFFFFFF}, {EIF_GENERIC(egt_2_994), 10, 0xFFFFFFFF}, {EIF_GENERIC(NULL), 11, 0xFFFFFFFF}, {EIF_GENERIC(NULL), 12, 0xFFFFFFFF}, {EIF_GENERIC(egt_3_994), 13, 0xFFFFFFFF}, {EIF_GENERIC(egt_4_994), 14, 0xFFFFFFFF}, {EIF_GENERIC(egt_5_994), 15, 0xFFFFFFFF}, {EIF_GENERIC(egt_6_994), 16, 0xFFFFFFFF}, {EIF_GENERIC(egt_7_994), 17, 0xFFFFFFFF}, {EIF_GENERIC(NULL), 18, 0xFFFFFFFF}, {EIF_GENERIC(NULL), 19, 0xFFFFFFFF}, {EIF_GENERIC(egt_8_994), 20, 0xFFFFFFFF}, {EIF_GENERIC(egt_9_994), 21, 0xFFFFFFFF}, {EIF_GENERIC(egt_10_994), 22, 0xFFFFFFFF}, {EIF_GENERIC(NULL), 23, 0xFFFFFFFF}, {EIF_GENERIC(egt_11_994), 24, 0xFFFFFFFF}, {EIF_GENERIC(NULL), 25, 0xFFFFFFFF}, {EIF_GENERIC(NULL), 26, 0xFFFFFFFF}, {EIF_GENERIC(NULL), 27, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x07C3 /*993*/), 28, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x01C7 /*227*/), 29, 0xFFFFFFFF}, {EIF_GENERIC(egt_12_994), 30, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x01B5 /*218*/), 13792, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x01B5 /*218*/), 13793, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x01B5 /*218*/), 13794, 16}, {EIF_NON_GENERIC(0x0197 /*203*/), 13795, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 13803, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 13804, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 13805, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 13806, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 13807, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 13808, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 13810, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 13811, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 13812, 0xFFFFFFFF}, {EIF_GENERIC(egt_13_994), 13796, 0xFFFFFFFF}, {EIF_GENERIC(egt_14_994), 13802, 0xFFFFFFFF}, {EIF_GENERIC(egt_15_994), 13813, 0xFFFFFFFF}, {EIF_GENERIC(egt_16_994), 13814, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x01D1 /*232*/), 13790, 0}, {EIF_NON_GENERIC(0x01B5 /*218*/), 13791, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 13774, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 13775, 0xFFFFFFFF}, {EIF_GENERIC(NULL), 13776, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x01B5 /*218*/), 13797, 0xFFFFFFFF}, {EIF_GENERIC(NULL), 13798, 0xFFFFFFFF}, {EIF_GENERIC(NULL), 13799, 0xFFFFFFFF}, {EIF_GENERIC(NULL), 13800, 0xFFFFFFFF}, {EIF_GENERIC(NULL), 13801, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 13809, 0xFFFFFFFF}, {EIF_GENERIC(egt_17_994), 13815, 4}, {EIF_NON_GENERIC(0x01B5 /*218*/), 13816, 20}, {EIF_NON_GENERIC(0x01D1 /*232*/), 13817, 8}, {EIF_NON_GENERIC(0x0197 /*203*/), 13818, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x0197 /*203*/), 13819, 12}, {EIF_GENERIC(egt_18_994), 13820, 0xFFFFFFFF}, {EIF_GENERIC(NULL), 13821, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x01C7 /*227*/), 13822, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x01B5 /*218*/), 13823, 0xFFFFFFFF}, {EIF_NON_GENERIC(0x01A3 /*209*/), 13824, 0xFFFFFFFF}, }; void Init994(void) { IDSC(desc_994, 0, 993); IDSC(desc_994 + 1, 1, 993); IDSC(desc_994 + 32, 373, 993); IDSC(desc_994 + 51, 385, 993); IDSC(desc_994 + 54, 381, 993); } #ifdef __cplusplus } #endif
41.415254
68
0.72212
3b156afceb6e6d2bfc60532585517b46426e0809
3,356
c
C
Examples/cubemx-example/FreeRTOSHooks.c
fractalembedded/stm32-cmake-boilerplate
0ec306027bb64bae2cae87d9953f303537101adf
[ "BSD-3-Clause" ]
null
null
null
Examples/cubemx-example/FreeRTOSHooks.c
fractalembedded/stm32-cmake-boilerplate
0ec306027bb64bae2cae87d9953f303537101adf
[ "BSD-3-Clause" ]
null
null
null
Examples/cubemx-example/FreeRTOSHooks.c
fractalembedded/stm32-cmake-boilerplate
0ec306027bb64bae2cae87d9953f303537101adf
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2021, Fractal Embedded LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <FreeRTOS.h> #include <task.h> #include <timers.h> // FreeRTOS has a number of hook functions that will be called by the OS if they are configured in. void vApplicationTickHook(void) {} void vApplicationIdleHook(void) {} void vApplicationMallocFailedHook(void) { taskDISABLE_INTERRUPTS(); for (;;) ; } void vApplicationStackOverflowHook(TaskHandle_t pxTask, char* pcTaskName) { (void)pcTaskName; (void)pxTask; taskDISABLE_INTERRUPTS(); for (;;) ; } /* We use static allocation in FreeRTOS so we can keep a good handle on memory usage at compile * time. We ahve to provide the allocators for the idle and timer task memory resources. */ void vApplicationGetIdleTaskMemory(StaticTask_t** ppxIdleTaskTCBBuffer, StackType_t** ppxIdleTaskStackBuffer, uint32_t* pulIdleTaskStackSize) { static StackType_t IdleStack[configMINIMAL_STACK_SIZE]; static StaticTask_t IdleTCB; *ppxIdleTaskTCBBuffer = &IdleTCB; *ppxIdleTaskStackBuffer = IdleStack; *pulIdleTaskStackSize = sizeof(IdleStack) / sizeof(IdleStack[0]); } void vApplicationGetTimerTaskMemory(StaticTask_t** ppxTimerTaskTCBBuffer, StackType_t** ppxTimerTaskStackBuffer, uint32_t* pulTimerTaskStackSize) { static StackType_t TimerStack[configTIMER_TASK_STACK_DEPTH]; static StaticTask_t TimerTCB; *ppxTimerTaskTCBBuffer = &TimerTCB; *ppxTimerTaskStackBuffer = TimerStack; *pulTimerTaskStackSize = sizeof(TimerStack) / sizeof(TimerStack[0]); } // this is called by the generated CubeMX code. We can do any init we want to here. // This is called after driver initialization but before the scheduler starts. void MX_FREERTOS_Init(void) {}
40.433735
99
0.744934
0fa8cdfcddfbb4dff2ae7fab376ec32b81cbe9a5
1,497
lua
Lua
crawl-ref/source/dat/dlua/lm_1way.lua
petercordia/crawl
c18c9092ac65e4306219b2c8d675610b0e127db0
[ "CC0-1.0" ]
1,921
2015-04-01T00:23:38.000Z
2022-03-31T23:42:29.000Z
crawl-ref/source/dat/dlua/lm_1way.lua
petercordia/crawl
c18c9092ac65e4306219b2c8d675610b0e127db0
[ "CC0-1.0" ]
1,768
2015-04-06T15:16:31.000Z
2022-03-31T13:16:47.000Z
crawl-ref/source/dat/dlua/lm_1way.lua
petercordia/crawl
c18c9092ac65e4306219b2c8d675610b0e127db0
[ "CC0-1.0" ]
1,150
2015-04-04T01:07:27.000Z
2022-03-28T23:54:55.000Z
------------------------------------------------------------------------------ -- lm_1way.lua: -- One-way stair marker. ------------------------------------------------------------------------------ util.subclass(PortalDescriptor, "OneWayStair") function OneWayStair:new(props) local instance = PortalDescriptor.new(self, props) if instance.props and instance.props.onclimb then instance.props.onclimb = global_function(instance.props.onclimb) end return instance end function OneWayStair:activate(marker) local ev = dgn.dgn_event_type('player_climb') dgn.register_listener(ev, marker, marker:pos()) end function OneWayStair:disappear(marker, x, y) dgn.terrain_changed(x, y, self.props.floor or 'floor', false) dgn.tile_feat_changed(x, y, self.props.feat_tile or nil) if self.props.floor_tile ~= nil then dgn.tile_floor_changed(x, y, self.props.floor_tile) end dgn.remove_listener(marker, x, y) dgn.remove_marker(marker) end function OneWayStair:event(marker, ev) if ev:type() == dgn.dgn_event_type('player_climb') then local x, y = ev:pos() -- If there's an onclimb function, call it before we do our thing. if self.props.onclimb then self.props.onclimb(self, marker, ev) end self:disappear(marker, x, y) return true end end function OneWayStair:read(marker, th) PortalDescriptor.read(self, marker, th) setmetatable(self, OneWayStair) return self end function one_way_stair(pars) return OneWayStair:new(pars) end
27.722222
78
0.661323
40f64bc603e815fd05103e31dca6aa4ae5720318
2,713
py
Python
dragonfly/nn/unittest_nn_domains.py
hase1128/dragonfly
4be7e4c539d3edccc4d243ab9f972b1ffb0d9a5c
[ "MIT" ]
675
2018-08-23T17:30:46.000Z
2022-03-30T18:37:23.000Z
dragonfly/nn/unittest_nn_domains.py
hase1128/dragonfly
4be7e4c539d3edccc4d243ab9f972b1ffb0d9a5c
[ "MIT" ]
62
2018-11-30T23:40:19.000Z
2022-03-10T19:47:27.000Z
dragonfly/nn/unittest_nn_domains.py
hase1128/dragonfly
4be7e4c539d3edccc4d243ab9f972b1ffb0d9a5c
[ "MIT" ]
349
2018-09-10T19:04:34.000Z
2022-03-31T13:10:45.000Z
""" Unit tests for functions/classes in nn_constraint_checker.py -- kandasamy@cs.cmu.edu """ # pylint: disable=no-member # pylint: disable=invalid-name # pylint: disable=relative-import # Local imports from . import nn_domains from .unittest_neural_network import generate_cnn_architectures, \ generate_mlp_architectures from ..utils.base_test_class import BaseTestClass, execute_tests class NNConstraintCheckerTestCase(BaseTestClass): """ Contains unit tests for the TransportNNDistanceComputer class. """ def __init__(self, *args, **kwargs): """ Constructor. """ super(NNConstraintCheckerTestCase, self).__init__(*args, **kwargs) self.nns = generate_cnn_architectures() + generate_mlp_architectures() self.cnn_constraint_checker = nn_domains.CNNConstraintChecker( 25, 5, 500000, 0, 5, 2, 15, 512, 16, 4) self.mlp_constraint_checker = nn_domains.MLPConstraintChecker( 25, 5, 500000, 900, 5, 2, 15, 30, 8) def test_constraint_checker(self): """ Tests if the constraints are satisfied for each network. """ report_str = ('Testing constraint checker: max_layers=%d, max_mass=%d,' + 'max_out_deg=%d, max_in_deg=%d, max_edges=%d, max_2stride=%d.')%( self.cnn_constraint_checker.max_num_layers, self.cnn_constraint_checker.max_mass, self.cnn_constraint_checker.max_in_degree, self.cnn_constraint_checker.max_out_degree, self.cnn_constraint_checker.max_num_edges, self.cnn_constraint_checker.max_num_2strides, ) self.report(report_str) for nn in self.nns: if nn.nn_class == 'cnn': violation = self.cnn_constraint_checker(nn, True) constrain_satisfied = self.cnn_constraint_checker(nn) img_inv_sizes = [piis for piis in nn.post_img_inv_sizes if piis != 'x'] nn_class_str = ', max_inv_size=%d '%(max(img_inv_sizes)) else: violation = self.mlp_constraint_checker(nn, True) constrain_satisfied = self.mlp_constraint_checker(nn) nn_class_str = ' ' self.report(('%s: #layers:%d, mass:%d, max_outdeg:%d, max_indeg:%d, ' + '#edges:%d%s:: %s, %s')%( nn.nn_class, len(nn.layer_labels), nn.get_total_mass(), nn.get_out_degrees().max(), nn.get_in_degrees().max(), nn.conn_mat.sum(), nn_class_str, str(constrain_satisfied), violation), 'test_result') assert (constrain_satisfied and violation == '') or \ (not constrain_satisfied and violation != '') if __name__ == '__main__': execute_tests()
42.390625
89
0.65094
86c9d26ba201cc5da6b22b2b0ff6253a01184e31
4,103
go
Go
perf-tools/framework/app_info.go
wilfred-s/yunikorn-release
96ca08d832ac2a41d08f5542558bc82a3ee5eea0
[ "Apache-2.0" ]
1
2021-11-02T14:12:24.000Z
2021-11-02T14:12:24.000Z
perf-tools/framework/app_info.go
kobe860219/incubator-yunikorn-release
e8ad5c40ccb08a0bae36f05df93793dd5ca503ad
[ "Apache-2.0" ]
null
null
null
perf-tools/framework/app_info.go
kobe860219/incubator-yunikorn-release
e8ad5c40ccb08a0bae36f05df93793dd5ca503ad
[ "Apache-2.0" ]
1
2022-03-26T06:19:41.000Z
2022-03-26T06:19:41.000Z
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package framework import ( "time" "github.com/apache/yunikorn-core/pkg/common/resources" apiv1 "k8s.io/api/core/v1" ) type AppInfo struct { Namespace string AppID string Queue string RequestInfos []*RequestInfo PodSpec apiv1.PodSpec PodTemplateSpec apiv1.PodTemplateSpec AppStatus AppStatus TasksStatus map[string]*TaskStatus } type RequestInfo struct { Number int32 PriorityClass string RequestResources map[string]string LimitResources map[string]string } type AppStatus struct { CreateTime time.Time // running time of the last task RunningTime time.Time DesiredNum int CreatedNum int ReadyNum int } type TaskStatus struct { TaskID string CreateTime time.Time RunningTime time.Time NodeID string RequestResources *resources.Resource Conditions []*TaskCondition } type TaskCondition struct { CondType TaskConditionType TransitionTime time.Time } type TasksDistributionInfo struct { LeastNum int LeastNumNodeID string MostNum int MostNumNodeID string AvgNum float64 SortedNodeInfos []*NodeInfo } type TaskConditionType string const ( PodCreated TaskConditionType = "PodCreated" PodScheduled TaskConditionType = "PodScheduled" PodStarted TaskConditionType = "PodStarted" PodInitialized TaskConditionType = "Initialized" PodReady TaskConditionType = "Ready" ContainersReady TaskConditionType = "ContainersReady" ) func NewRequestInfo(number int32, priorityClass string, requestResources, limitResources map[string]string) *RequestInfo { return &RequestInfo{ Number: number, PriorityClass: priorityClass, RequestResources: requestResources, LimitResources: limitResources, } } func NewAppInfo(namespace, appID, queue string, requestInfos []*RequestInfo, podTemplateSpec apiv1.PodTemplateSpec, podSpec apiv1.PodSpec) *AppInfo { return &AppInfo{ Namespace: namespace, AppID: appID, Queue: queue, RequestInfos: requestInfos, PodTemplateSpec: podTemplateSpec, PodSpec: podSpec, } } func NewTaskStatus(taskID, nodeID string, createTime, runningTime time.Time, requestResources *resources.Resource, conditions []*TaskCondition) *TaskStatus { return &TaskStatus{ TaskID: taskID, CreateTime: createTime, RunningTime: runningTime, NodeID: nodeID, RequestResources: requestResources, Conditions: conditions, } } func (appInfo *AppInfo) SetAppStatus(desiredNum, createdNum, readyNum int) { appInfo.AppStatus.DesiredNum = desiredNum appInfo.AppStatus.CreatedNum = createdNum appInfo.AppStatus.ReadyNum = readyNum } func (appInfo *AppInfo) GetDesiredNumTasks() int32 { var desiredNum int32 for _, requestInfo := range appInfo.RequestInfos { desiredNum += requestInfo.Number } return desiredNum } func (taskStatus *TaskStatus) GetTransitionTime(condType TaskConditionType) *time.Time { for _, cond := range taskStatus.Conditions { if cond.CondType == condType { return &cond.TransitionTime } } return nil } func GetOrderedTaskConditionTypes() []TaskConditionType { return []TaskConditionType{PodCreated, PodScheduled, PodStarted, PodInitialized, PodReady, ContainersReady} }
27.353333
122
0.740434
5f1dfb84040f9d3119b1feb91a5168f55f3504da
634
ts
TypeScript
src/rating/rating.module.ts
GlukKazan/DagazServer
1e1d9bbf2ceffcade004a3638cef8b555bcce4e5
[ "MIT" ]
4
2020-06-18T10:53:24.000Z
2021-02-23T20:42:06.000Z
src/rating/rating.module.ts
GlukKazan/DagazServer
1e1d9bbf2ceffcade004a3638cef8b555bcce4e5
[ "MIT" ]
3
2020-10-06T12:57:23.000Z
2021-08-31T02:14:45.000Z
src/rating/rating.module.ts
GlukKazan/DagazServer
1e1d9bbf2ceffcade004a3638cef8b555bcce4e5
[ "MIT" ]
2
2020-10-12T10:33:29.000Z
2020-12-03T07:39:49.000Z
import { Module } from '@nestjs/common'; import { DatabaseModule } from '../database/database.module'; import { tokensProvider } from '../users/tokens.provider'; import { usersProvider } from '../users/users.provider'; import { UsersService } from '../users/users.service'; import { RatingController } from './rating.controller'; import { rateProvider } from './rating.provider'; import { RatingService } from './rating.service'; @Module({ imports: [DatabaseModule], providers: [...rateProvider, ...usersProvider, ...tokensProvider, RatingService, UsersService], controllers: [RatingController] }) export class RatingModule {}
39.625
97
0.727129
fe47818b24f72a16e58e94be79980db561750bf4
93
h
C
includes/macro.h
tmt514/contest-testcase-generator
e58ccdec652d8a38f250cd4d9206ccf179ac87ce
[ "MIT" ]
2
2018-08-24T04:42:47.000Z
2020-02-21T13:57:05.000Z
includes/macro.h
tmt514/contest-testcase-generator
e58ccdec652d8a38f250cd4d9206ccf179ac87ce
[ "MIT" ]
null
null
null
includes/macro.h
tmt514/contest-testcase-generator
e58ccdec652d8a38f250cd4d9206ccf179ac87ce
[ "MIT" ]
null
null
null
#define FOR(it, c) for(__typeof((c)->begin()) it = ((c)->begin()); it != ((c)->end()); it++)
46.5
92
0.483871
9685ba80f8c8dbe04e26f182e42782a764e41206
315
php
PHP
app/Model/News.php
ahmed-farid/tasks
046f478d8062a76fb7ff3d5ec20f4e7c6f55dc07
[ "MIT" ]
null
null
null
app/Model/News.php
ahmed-farid/tasks
046f478d8062a76fb7ff3d5ec20f4e7c6f55dc07
[ "MIT" ]
null
null
null
app/Model/News.php
ahmed-farid/tasks
046f478d8062a76fb7ff3d5ec20f4e7c6f55dc07
[ "MIT" ]
null
null
null
<?php namespace App\Model; use Illuminate\Database\Eloquent\Model; class News extends Model { // protected $table = 'news'; protected $fillable = ['name', 'image', 'description', 'cat_id']; public function category() { return $this->belongsTo('App\Model\Category', 'cat_id'); } }
16.578947
69
0.631746
3bf5ec28a0eae39b2010eb231652fe89f24311a7
3,390
kt
Kotlin
pumpkin/src/main/kotlin/net/tjalp/peach/pumpkin/player/PlayerService.kt
tjalp/minestom-tjalp-server
0d74c084b3e83dfaaec7a2bf52f056de7a5f6a08
[ "MIT" ]
null
null
null
pumpkin/src/main/kotlin/net/tjalp/peach/pumpkin/player/PlayerService.kt
tjalp/minestom-tjalp-server
0d74c084b3e83dfaaec7a2bf52f056de7a5f6a08
[ "MIT" ]
null
null
null
pumpkin/src/main/kotlin/net/tjalp/peach/pumpkin/player/PlayerService.kt
tjalp/minestom-tjalp-server
0d74c084b3e83dfaaec7a2bf52f056de7a5f6a08
[ "MIT" ]
null
null
null
package net.tjalp.peach.pumpkin.player import net.tjalp.peach.peel.PLAYER_SWITCH import net.tjalp.peach.peel.signal.PlayerSwitchSignal import net.tjalp.peach.pumpkin.PumpkinServer import net.tjalp.peach.pumpkin.node.apple.AppleNode import net.tjalp.peach.pumpkin.node.apple.AppleServerNode import net.tjalp.peach.pumpkin.node.melon.MelonNode import net.tjalp.peach.pumpkin.node.melon.MelonServerNode import reactor.core.publisher.Mono import java.util.* class PlayerService( val pumpkin: PumpkinServer ) { private val thread = pumpkin.mainThread private val registeredPlayers = mutableListOf<PeachPlayer>() fun setup() { pumpkin.logger.info("Setting up player service") } fun switch(player: PeachPlayer, node: AppleNode) { thread.ensureMainThread() if (!node.isOnline) { throw IllegalStateException("Target Apple Node is not online!") } else { if (player.currentAppleNode != node) { (player.currentAppleNode as AppleServerNode).connectedPlayers.remove(player) (node as AppleServerNode).connectedPlayers.add(player as ConnectedPlayer) player.currentAppleNode = node val signal = PlayerSwitchSignal().apply { this.uniqueId = player.uniqueId this.nodeId = node.nodeIdentifier } pumpkin.redis.publish(PLAYER_SWITCH, signal).subscribe() } } } fun getPlayer(uniqueId: UUID): PeachPlayer? { thread.ensureMainThread() return registeredPlayers.firstOrNull { it.uniqueId == uniqueId } } fun getPlayers(username: String): List<PeachPlayer> { thread.ensureMainThread() return registeredPlayers.filter { it.username == username } } internal fun register( uniqueId: UUID, username: String, melonNode: MelonNode, appleNode: AppleNode ): PeachPlayer { thread.ensureMainThread() if (registeredPlayers.any { it.uniqueId == uniqueId }) { throw IllegalArgumentException("A player with the unique identifier $uniqueId is already registered!") } val connectedPlayer = ConnectedPlayer(uniqueId, username, melonNode, appleNode) val melonServerNode = melonNode as MelonServerNode val appleServerNode = appleNode as AppleServerNode melonServerNode.connectedPlayers.add(connectedPlayer) appleServerNode.connectedPlayers.add(connectedPlayer) registeredPlayers.add(connectedPlayer) pumpkin.logger.info("Registered player (username: $username, uniqueId: $uniqueId)") return connectedPlayer } internal fun unregister(player: ConnectedPlayer) { thread.ensureMainThread() if (player !in registeredPlayers) { throw IllegalArgumentException("Unknown player $player") } val melonServerNode = player.currentMelonNode as MelonServerNode val appleServerNode = player.currentAppleNode as AppleServerNode melonServerNode.connectedPlayers.remove(player) appleServerNode.connectedPlayers.remove(player) registeredPlayers.remove(player) pumpkin.logger.info("Unregistered player (username: ${player.username}, uniqueId: ${player.uniqueId})") } }
32.285714
114
0.674926
53bb1cb48e4efe377a0de84c7344a164b38530a2
1,617
java
Java
src/main/java/com/ampro/robinhood/endpoint/account/data/BasicAccountHolderInfoElement.java
albanoj2/robinhood-api
73aac7d7d2b4290c58867c174ed76c79f456fc75
[ "MIT" ]
null
null
null
src/main/java/com/ampro/robinhood/endpoint/account/data/BasicAccountHolderInfoElement.java
albanoj2/robinhood-api
73aac7d7d2b4290c58867c174ed76c79f456fc75
[ "MIT" ]
null
null
null
src/main/java/com/ampro/robinhood/endpoint/account/data/BasicAccountHolderInfoElement.java
albanoj2/robinhood-api
73aac7d7d2b4290c58867c174ed76c79f456fc75
[ "MIT" ]
null
null
null
package com.ampro.robinhood.endpoint.account.data; import com.ampro.robinhood.endpoint.ApiElement; public class BasicAccountHolderInfoElement implements ApiElement { private String address; private String citizenship; private String city; private String country_of_residence; private String date_of_birth; private String marital_status; private int number_dependents; private long phone_number; private String state; private int tax_id_ssn; //TODO: updated_at private int zipcode; @Override public boolean requiresAuth() { return true; } /** * @return the address */ public String getAddress() { return address; } /** * @return the citizenship */ public String getCitizenship() { return citizenship; } /** * @return the city */ public String getCity() { return city; } /** * @return the country_of_residence */ public String getCountryOfResidence() { return country_of_residence; } /** * @return the date_of_birth */ public String getDateOfBirth() { return date_of_birth; } /** * @return the marital_status */ public String getMaritalStatus() { return marital_status; } /** * @return the number_dependents */ public int getNumberDependents() { return number_dependents; } /** * @return the phone_number */ public long getPhoneNumber() { return phone_number; } /** * @return the state */ public String getState() { return state; } /** * @return the tax_id_ssn */ public int getTaxIdSsn() { return tax_id_ssn; } /** * @return the zipcode */ public int getZipcode() { return zipcode; } }
15.548077
66
0.694496
20e0f153ea5ee186a22bf906f48e09cb16645f19
1,906
css
CSS
OceanLife/css/estilo.css
Danib0y97/OceanLife
3fab00a3e2a4e5319ed1c3e4e36427b424f8c064
[ "MIT" ]
1
2020-07-15T21:18:36.000Z
2020-07-15T21:18:36.000Z
OceanLife/css/estilo.css
Danib0y97/OceanLife
3fab00a3e2a4e5319ed1c3e4e36427b424f8c064
[ "MIT" ]
null
null
null
OceanLife/css/estilo.css
Danib0y97/OceanLife
3fab00a3e2a4e5319ed1c3e4e36427b424f8c064
[ "MIT" ]
null
null
null
@charset "UTF-8"; @import url(https://fonts.googleapis.com/css?family=Titillium+Web); @font-face { font-family: 'FonteLogo'; src:url('../fontes/bubblegum-sans-regular.otf'); } body { font-family: 'Montserrat', sans-serif; background-image: url("../imagens/background.jpg" ) ; background-attachment: fixed; background-position: center; background-repeat: no-repeat; background-size: cover; color: rgba(0,0,0,1); } div#interface{ color: #D3FFFF; width: 900px; background-color: #0A6AA6; margin: 0px auto 0px auto; box-shadow: 1px 1px 15px rgba(0,0,0,1); padding: 10px; } p{ text-align: justify; text-indent: 50px; } a { text-decoration: none; color:white; } a:hover { text-decoration: none; } header#cabecalho img#icone { position: absolute; left: 920px; top: 70px; } header#cabecalho { border-bottom: 1px #000000 solid; height: 55px; } header#cabecalho h1{ font-family: 'FonteLogo', sans-serif; font-size: 30pt; color: white; text-shadow: 1px 1px 1px rgba(0,0,0,.6); padding-left: 5px; margin: 5px; } header#cabecalho h2{ font-family: 'Titillium Web' , sans-serif; font-size: 15pt; color:#000000; padding: 0px; margin-top: 0px; } /*Formatação do Menu*/ nav#menu { display:block; } nav#menu ul{ list-style: none; text-transform: uppercase; position: absolute; top: 7px; left: 580px; } nav#menu li{ display: inline-block; background-color: #dddddd; padding: 10px; margin:2px; transition: background-color 1s; border-radius: 15px 30px 15px 30px; } nav#menu li:hover{ background-color: #606060; border-radius: 30px 15px 30px 15px; } nav#menu h1{ display: none; } nav#menu a{ color: #000000; text-decoration: none; } nav#menu a:hover{ color:#ffffff; text-decoration: underline; } footer#rodape { clear: both; border-top: 1px solid #000000; } footer#rodape p { text-align: center; } footer#rodape p#social{ margin-top: -15px; }
16.431034
67
0.691501
052389bdb5d48a4444bd0f2859ac577580e60676
296
dart
Dart
lib/src/plugins/aop/annotation/aspect.dart
soloxiao/aspectd
92b9d3a06558c8f96844ad174638469f46454384
[ "MIT" ]
811
2019-05-09T02:48:54.000Z
2021-03-14T16:11:48.000Z
lib/src/plugins/aop/annotation/aspect.dart
soloxiao/aspectd
92b9d3a06558c8f96844ad174638469f46454384
[ "MIT" ]
99
2019-06-19T06:05:07.000Z
2021-03-14T13:57:24.000Z
lib/src/plugins/aop/annotation/aspect.dart
soloxiao/aspectd
92b9d3a06558c8f96844ad174638469f46454384
[ "MIT" ]
95
2019-05-09T02:50:13.000Z
2021-02-24T07:26:17.000Z
/// Annotation indicating whether a class should be taken into consideration /// when searching for aspectd implementations like AOP. @pragma('vm:entry-point') class Aspect { /// Aspect default constructor const factory Aspect() = Aspect._; @pragma('vm:entry-point') const Aspect._(); }
26.909091
76
0.72973
3a10c4b433801e7fb0ecc1b2d975a210c0ef0f23
16,237
lua
Lua
SohighUI/modules/dps.lua
sativahigh/SohighUI
533e62c55ed46e54d40758e0c2b728be75e57adc
[ "MIT" ]
1
2021-05-18T15:06:30.000Z
2021-05-18T15:06:30.000Z
SohighUI/modules/dps.lua
sativahigh/SohighUI
533e62c55ed46e54d40758e0c2b728be75e57adc
[ "MIT" ]
null
null
null
SohighUI/modules/dps.lua
sativahigh/SohighUI
533e62c55ed46e54d40758e0c2b728be75e57adc
[ "MIT" ]
null
null
null
--* damage/healing/interrupt meter Allez local E, C, L, _ = select(2, shCore()):unpack() if C.main._dpsMeter ~= true then return end local _G = _G local select = select local unpack = unpack local type = type local band = bit.band local tinsert = table.insert local CreateFrame = CreateFrame local UnitExists = UnitExists local UnitIsPlayer = UnitIsPlayer local UnitClass = UnitClass local UnitGUID = UnitGUID local UnitAffectingCombat = UnitAffectingCombat local shDps = debugstack():match[[\AddOns\(.-)\]] local w, h = 160, M.barMax * (M.barHeight + M.barSpace) -M.barSpace local font_size = 13 local boss = LibStub('LibBossIDs-1.0') local dataobj = LibStub:GetLibrary('LibDataBroker-1.1'):NewDataObject('Dps', {type = 'data source', text = 'DPS: ', icon = '', iconCoords = {0.065, 0.935, 0.065, 0.935}}) local bossname, mobname = nil, nil local units, bar, barguids, owners = {}, {}, {}, {} local current, display, fights = {}, {}, {} local timer, num, offset = 0, 0, 0 local MainFrame local combatStart = false local filter = COMBATLOG_OBJECT_AFFILIATION_RAID + COMBATLOG_OBJECT_AFFILIATION_PARTY + COMBATLOG_OBJECT_AFFILIATION_MINE local displayMode = { 'Damage', 'Healing', 'Dispels', 'Interrupts', } local sMode = 'Damage' local menuFrame = CreateFrame('frame', 'alDamageMeterMenu', UIParent, 'UIDropDownMenuTemplate') local truncate = function(value) if value >= 1e6 then return string.format('%.2fm', value / 1e6) elseif value >= 1e4 then return string.format('%.1fk', value / 1e3) else return string.format('%.0f', value) end end function dataobj.OnLeave() GameTooltip:SetClampedToScreen(true) GameTooltip:Hide() end function dataobj.OnEnter(self) GameTooltip:SetOwner(self, 'ANCHOR_BOTTOMLEFT', 0, self:GetHeight()) GameTooltip:AddLine('DamageMeter') GameTooltip:AddLine('Hint: click to show/hide damage meter window.') GameTooltip:Show() end function dataobj.OnClick(self, button) if MainFrame:IsShown() then MainFrame:Hide() else MainFrame:Show() end end local IsFriendlyUnit = function(uGUID) if units[uGUID] or owners[uGUID] or uGUID == UnitGUID('player') then return true else return false end end local IsUnitInCombat = function(uGUID) unit = units[uGUID] if unit then return UnitAffectingCombat(unit.unit) end return false end local tcopy = function(src) local dest = {} for k, v in pairs(src) do dest[k] = v end return dest end local perSecond = function(cdata) return cdata[sMode] / cdata.combatTime end local report = function(channel, cn) local message = sMode..':' if (channel == 'Chat') then DEFAULT_CHAT_FRAME:AddMessage(message) else SendChatMessage(message, channel, nil, cn) end for i, v in pairs(barguids) do if i > M.maxReports then return end if (sMode == 'Damage' or sMode == 'Healing') then message = string.format('%2d. %s %s (%.0f)', i, display[v].name, truncate(display[v][sMode]), perSecond(display[v])) else message = string.format('%2d. %s %s', i, display[v].name, truncate(display[v][sMode])) end if (channel == 'Chat') then DEFAULT_CHAT_FRAME:AddMessage(message) else SendChatMessage(message, channel, nil, cn) end end end StaticPopupDialogs[shDps..'ReportDialog'] = { text = '', button1 = ACCEPT, button2 = CANCEL, hasEditBox = 1, timeout = 30, hideOnEscape = 1, } local reportList = { { text = 'Chat', func = function() report('Chat') end, }, { text = 'Say', func = function() report('SAY') end, }, { text = 'Party', func = function() report('PARTY') end, }, { text = 'Raid', func = function() report('RAID') end, }, { text = 'Officer', func = function() report('OFFICER') end, }, { text = 'Guild', func = function() report('GUILD') end, }, { text = 'Target', func = function() if UnitExists('target') and UnitIsPlayer('target') then report('WHISPER', UnitName('target')) end end, }, { text = 'Player..', func = function() StaticPopupDialogs[shDps..'ReportDialog'].OnAccept = function() report('WHISPER', _G[this:GetParent():GetName()..'EditBox']:GetText()) end StaticPopup_Show(shDps..'ReportDialog') end, }, { text = 'Channel..', func = function() StaticPopupDialogs[shDps..'ReportDialog'].OnAccept = function() report('CHANNEL', _G[this:GetParent():GetName()..'EditBox']:GetText()) end StaticPopup_Show(shDps..'ReportDialog') end, }, } local CreateBar = function() local newbar = CreateFrame('Statusbar', 'DamageMeterBar', MainFrame) newbar:SetStatusBarTexture(A.FetchMedia) newbar:SetMinMaxValues(0, 100) newbar:Size(MainFrame:GetWidth(), M.barHeight) newbar.left = E.SetFontString(newbar, font_size, 'OUTLINE') newbar.left:SetAnchor('LEFT', 2, 1) newbar.left:SetJustifyH('LEFT') newbar.right = E.SetFontString(newbar, font_size, 'OUTLINE') newbar.right:SetAnchor('RIGHT', -2, 1) newbar.right:SetJustifyH('RIGHT') return newbar end local Add = function(uGUID, ammount, mode, name) local unit = units[uGUID] if not current[uGUID] then local newdata = { name = unit.name, class = unit.class, combatTime = 1, } for _, v in pairs(displayMode) do newdata[v] = 0 end current[uGUID] = newdata tinsert(barguids, uGUID) end current[uGUID][mode] = current[uGUID][mode] + ammount end local SortMethod = function(a, b) return display[b][sMode] < display[a][sMode] end local UpdateBars = function() table.sort(barguids, SortMethod) local color, cur, max for i = 1, #barguids do cur = display[barguids[i+offset]] max = display[barguids[1]] if i > M.barMax or not cur then break end if cur[sMode] == 0 then break end if not bar[i] then bar[i] = CreateBar() bar[i]:SetAnchor('TOP', MainFrame, 'TOP', 0, -(M.barHeight + M.barSpace) * (i-1)) end bar[i]:Width(MainFrame:GetWidth()) bar[i]:SetValue(100 * cur[sMode] / max[sMode]) color = RAID_CLASS_COLORS[cur.class] bar[i]:SetStatusBarColor(color.r, color.g, color.b) if (sMode == 'Damage' or sMode == 'Healing') then --bar[i].right:SetFormattedText('%s (%.0f)', truncate(cur[sMode]), perSecond(cur)) --else bar[i].right:SetFormattedText('%s', truncate(cur[sMode])) end bar[i].left:SetText(cur.name) bar[i]:Show() end end local ResetDisplay = function(fight) for i, v in pairs(bar) do v:Hide() end display = fight wipe(barguids) for guid, v in pairs(display) do tinsert(barguids, guid) end offset = 0 UpdateBars() end local Clean = function() numfights = 0 wipe(current) wipe(fights) ResetDisplay(current) CombatLogClearEntries() end local SetMode = function(mode) sMode = mode for i, v in pairs(bar) do v:Hide() end UpdateBars() MainFrame.title:SetText('Current Mode: '..sMode) end local CreateMenu = function(self, level) level = level or 1 local info = {} if UIDROPDOWNMENU_MENU_LEVEL == 1 then info.isTitle = 1 info.text = 'Menu' info.notCheckable = 1 UIDropDownMenu_AddButton(info) wipe(info) info.text = 'Mode' info.hasArrow = 1 info.value = 'Mode' info.notCheckable = 1 UIDropDownMenu_AddButton(info) wipe(info) info.text = 'Report to' info.hasArrow = 1 info.value = 'Report' info.notCheckable = 1 UIDropDownMenu_AddButton(info, level) wipe(info) info.text = 'Fight' info.hasArrow = 1 info.value = 'Fight' info.notCheckable = 1 UIDropDownMenu_AddButton(info) wipe(info) info.text = 'Clean' info.func = Clean info.notCheckable = 1 UIDropDownMenu_AddButton(info) elseif UIDROPDOWNMENU_MENU_LEVEL == 2 then if UIDROPDOWNMENU_MENU_VALUE == 'Mode' then for i, v in pairs(displayMode) do wipe(info) info.text = v info.func = function() SetMode(v) end info.notCheckable = 1 UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL) end end if UIDROPDOWNMENU_MENU_VALUE == 'Report' then for i, v in pairs(reportList) do wipe(info) info.text = v.text info.func = v.func info.notCheckable = 1 UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL) end end if UIDROPDOWNMENU_MENU_VALUE == 'Fight' then wipe(info) info.text = 'Current' info.func = function() ResetDisplay(current) end info.notCheckable = 1 UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL) for i, v in pairs(fights) do wipe(info) info.text = v.name info.func = function() ResetDisplay(v.data) end info.notCheckable = 1 UIDropDownMenu_AddButton(info, UIDROPDOWNMENU_MENU_LEVEL) end end end end local EndCombat = function() MainFrame:SetScript('OnUpdate', nil) combatStart = false local fname = bossname or mobname if fname then if #fights >= M.maxFights then tremove(fights, 1) end tinsert(fights, {name = fname, data = tcopy(current)}) mobname, bossname = nil, nil end if C.main._dpsMeterCombat ~= false then MainFrame:FadeOut() end end local CheckPet = function(unit, pet) if UnitExists(pet) then owners[UnitGUID(pet)] = UnitGUID(unit) end end local CheckUnit = function(unit) if UnitExists(unit) then units[UnitGUID(unit)] = { name = UnitName(unit), class = select(2, UnitClass(unit)), unit = unit } pet = unit .. 'pet' CheckPet(unit, pet) end end local IsRaidInCombat = function() if GetNumRaidMembers() > 0 then for i = 1, GetNumRaidMembers(), 1 do if UnitExists('raid'..i) and UnitAffectingCombat('raid'..i) then return true end end elseif GetNumPartyMembers() > 0 then for i = 1, GetNumPartyMembers(), 1 do if UnitExists('party'..i) and UnitAffectingCombat('party'..i) then return true end end end return false end local OnUpdate = function(self, elapsed) timer = timer + elapsed if timer > 0.5 then for i, v in pairs(current) do if IsUnitInCombat(i) then v.combatTime = v.combatTime + timer end if i == UnitGUID('player') then dataobj.text = string.format('DPS: %.0f', v['Damage'] / v.combatTime) end end UpdateBars() if not InCombatLockdown() and not IsRaidInCombat() then EndCombat() end timer = 0 end end local OnMouseWheel = function(self, direction) num = 0 for i = 1, #barguids do if display[barguids[i]][sMode] > 0 then num = num + 1 end end if direction > 0 then if offset > 0 then offset = offset - 1 end else if num > M.barMax + offset then offset = offset + 1 end end UpdateBars() end local StartCombat = function() wipe(current) combatStart = true ResetDisplay(current) CombatLogClearEntries() MainFrame:SetScript('OnUpdate', OnUpdate) end local OnEvent = function(self, event, ...) if (event == 'COMBAT_LOG_EVENT_UNFILTERED') then local timestamp, eventType, sourceGUID, sourceName, sourceFlags, destGUID, destName, destFlags = select(1, ...) if band(sourceFlags, filter) == 0 then return end if (eventType == 'SWING_DAMAGE' or eventType == 'RANGE_DAMAGE' or eventType == 'SPELL_DAMAGE' or eventType == 'SPELL_PERIODIC_DAMAGE' or eventType == 'DAMAGE_SHIELD') then local ammount = select(eventType == 'SWING_DAMAGE' and 9 or 12, ...) if IsFriendlyUnit(sourceGUID) and not IsFriendlyUnit(destGUID) and combatStart then if ammount and ammount > 0 then sourceGUID = owners[sourceGUID] or sourceGUID Add(sourceGUID, ammount, 'Damage', sourceName) if not bossname and boss.BossIDs[tonumber(destGUID:sub(9, 12), 16)] then bossname = destName elseif not mobname then mobname = destName end end end elseif (eventType == 'SPELL_SUMMON') then if owners[sourceGUID] then owners[destGUID] = owners[sourceGUID] else owners[destGUID] = sourceGUID end elseif (eventType == 'SPELL_HEAL' or eventType == 'SPELL_PERIODIC_HEAL') then spellId, spellName, spellSchool, ammount, over, school, resist = select(9, ...) if IsFriendlyUnit(sourceGUID) and IsFriendlyUnit(destGUID) and combatStart then over = over or 0 if ammount and ammount > 0 then sourceGUID = owners[sourceGUID] or sourceGUID Add(sourceGUID, ammount - over, 'Healing') end end elseif (eventType == 'SPELL_DISPEL') then if IsFriendlyUnit(sourceGUID) and IsFriendlyUnit(destGUID) and combatStart then sourceGUID = owners[sourceGUID] or sourceGUID Add(sourceGUID, 1, 'Dispels') end elseif (eventType == 'SPELL_INTERRUPT') then if IsFriendlyUnit(sourceGUID) and not IsFriendlyUnit(destGUID) and combatStart then sourceGUID = owners[sourceGUID] or sourceGUID Add(sourceGUID, 1, 'Interrupts') end else return end elseif (event == 'ADDON_LOADED') then local addon = shDps if (addon == 'SohighUI') then self:UnregisterEvent(event) MainFrame = CreateFrame('frame', shDps..'DamageMeter', UIParent) MainFrame:SetAnchor(unpack(C.Anchors.dmeter)) MainFrame:SetSize(w, h) if C.main._dpsMeterLayout ~= false then MainFrame:SetLayout() MainFrame:SetShadow() end if C.main._dpsMeterLock ~= true then MainFrame:SetMovable(true) MainFrame:EnableMouse(true) MainFrame:EnableMouseWheel(true) MainFrame:SetUserPlaced(true) MainFrame:SetClampedToScreen(true) MainFrame:SetResizable(true) MainFrame:SetMinResize(128, 128) MainFrame:SetMaxResize(256, 312) MainFrame:RegisterForDrag('LeftButton') MainFrame:SetScript('OnDragStart', MainFrame.StartSizing) MainFrame:SetScript('OnDragStop', function(self, button) self:StopMovingOrSizing() UpdateBars() end); MainFrame:SetScript('OnMouseDown', function(self, button) if (button == 'LeftButton') and IsModifiedClick('SHIFT') then self:StartMoving() end end); MainFrame:SetScript('OnMouseUp', function(self, button) if (button == 'RightButton') then ToggleDropDownMenu(1, nil, menuFrame, 'cursor', 0, 0) end if (button == 'LeftButton') then self:StopMovingOrSizing() end end); end MainFrame:SetScript('OnMouseWheel', OnMouseWheel) MainFrame:Show() UIDropDownMenu_Initialize(menuFrame, CreateMenu, 'MENU') MainFrame.title = E.SetFontString(MainFrame, font_size, 'OUTLINE') MainFrame.title:SetAnchor('BOTTOMLEFT', MainFrame, 'TOPLEFT', 0, 1) MainFrame.title:SetText(L_DamageMeter..sMode) if C.main._dpsMeterFade ~= false then MainFrame:SetScript('OnEnter', function() MainFrame:FadeIn() end); MainFrame:SetScript('OnLeave', function() MainFrame:FadeOut() end); end if C.main._dpsMeterTitle ~= true then MainFrame.title:Hide() end if C.main._dpsMeterCombat ~= false then MainFrame:FadeOut() end end elseif (event == 'RAID_ROSTER_UPDATE' or event == 'PARTY_MEMBERS_CHANGED' or event == 'PLAYER_ENTERING_WORLD') then wipe(units) if GetNumRaidMembers() > 0 then for i = 1, GetNumRaidMembers(), 1 do CheckUnit('raid'..i) end elseif GetNumPartyMembers() > 0 then for i = 1, GetNumPartyMembers(), 1 do CheckUnit('party'..i) end end CheckUnit('player') elseif (event == 'PLAYER_REGEN_DISABLED') then if not combatStart then StartCombat() if C.main._dpsMeterCombat ~= false then MainFrame:FadeIn() end end elseif (event == 'UNIT_PET') then local unit = ... local pet = unit .. 'pet' CheckPet(unit, pet) end end local m = CreateFrame('frame', nil, UIParent) m:SetScript('OnEvent', OnEvent) m:RegisterEvent('COMBAT_LOG_EVENT_UNFILTERED') m:RegisterEvent('ADDON_LOADED') m:RegisterEvent('RAID_ROSTER_UPDATE') m:RegisterEvent('PARTY_MEMBERS_CHANGED') m:RegisterEvent('PLAYER_ENTERING_WORLD') m:RegisterEvent('PLAYER_REGEN_DISABLED') m:RegisterEvent('UNIT_PET') SlashCmdList['alDamage'] = function(msg) for i = 1, 20 do units[i] = {name = E.Name, class = E.Class, unit = '1'} Add(i, i*10000, 'Damage') units[i] = nil end display = current UpdateBars() end SLASH_alDamage1 = '/dmg'
27.803082
174
0.672107
567001e34ab1a08fb71c3769415213209a98294b
1,918
go
Go
internal/outpost/ldap/utils/utils_group.go
BeryJu/passbook
350f0d836580f4411524614f361a76c4f27b8a2d
[ "MIT" ]
15
2020-01-05T09:09:57.000Z
2020-11-28T05:27:39.000Z
internal/outpost/ldap/utils/utils_group.go
BeryJu/passbook
350f0d836580f4411524614f361a76c4f27b8a2d
[ "MIT" ]
302
2020-01-21T08:03:59.000Z
2020-12-04T05:04:57.000Z
internal/outpost/ldap/utils/utils_group.go
BeryJu/passbook
350f0d836580f4411524614f361a76c4f27b8a2d
[ "MIT" ]
3
2020-03-04T08:21:59.000Z
2020-08-01T20:37:18.000Z
package utils import ( "strings" goldap "github.com/go-ldap/ldap/v3" ber "github.com/nmcclain/asn1-ber" "github.com/nmcclain/ldap" "goauthentik.io/api/v3" "goauthentik.io/internal/outpost/ldap/constants" ) func ParseFilterForGroup(req api.ApiCoreGroupsListRequest, f *ber.Packet, skip bool) (api.ApiCoreGroupsListRequest, bool) { switch f.Tag { case ldap.FilterEqualityMatch: return parseFilterForGroupSingle(req, f) case ldap.FilterAnd: for _, child := range f.Children { r, s := ParseFilterForGroup(req, child, skip) skip = skip || s req = r } return req, skip } return req, skip } func parseFilterForGroupSingle(req api.ApiCoreGroupsListRequest, f *ber.Packet) (api.ApiCoreGroupsListRequest, bool) { // We can only handle key = value pairs here if len(f.Children) < 2 { return req, false } k := f.Children[0].Value // Ensure key is string if _, ok := k.(string); !ok { return req, false } v := f.Children[1].Value // Null values are ignored if v == nil { return req, false } // Switch on type of the value, then check the key switch vv := v.(type) { case string: switch strings.ToLower(k.(string)) { case "cn": return req.Name(vv), false case "member": fallthrough case "memberOf": userDN, err := goldap.ParseDN(vv) if err != nil { return req.MembersByUsername([]string{vv}), false } username := userDN.RDNs[0].Attributes[0].Value // If the DN's first ou is virtual-groups, ignore this filter if len(userDN.RDNs) > 1 { if strings.EqualFold(userDN.RDNs[1].Attributes[0].Value, constants.OUVirtualGroups) || strings.EqualFold(userDN.RDNs[1].Attributes[0].Value, constants.OUGroups) { // Since we know we're not filtering anything, skip this request return req, true } } return req.MembersByUsername([]string{username}), false } //TODO: Support int default: return req, false } return req, false }
26.638889
166
0.689781
a3a68fcc639c2ff261d216dccfba740eab3ffeb5
35
asm
Assembly
tests/data_simple/10.asm
NullMember/customasm
6e34d6432583a41278e6b3596f1817ae82149531
[ "Apache-2.0" ]
414
2016-10-14T22:39:20.000Z
2022-03-30T07:52:44.000Z
tests/data_simple/10.asm
NullMember/customasm
6e34d6432583a41278e6b3596f1817ae82149531
[ "Apache-2.0" ]
100
2018-03-22T16:12:24.000Z
2022-03-26T09:19:23.000Z
tests/data_simple/10.asm
NullMember/customasm
6e34d6432583a41278e6b3596f1817ae82149531
[ "Apache-2.0" ]
47
2017-06-29T15:12:13.000Z
2022-03-10T04:50:51.000Z
#d24 0x3, 0x4567 ; = 0x000003004567
35
35
0.742857
260a0e4753343d7f62acbbef8ae5851d88496e1c
2,321
swift
Swift
FluxWithRxSwiftSample/Views/LoadingView.swift
dekatotoro/FluxWithRxSwiftSample
794ce767f81234f5d83df9c866ed041115f80d38
[ "MIT" ]
128
2016-10-13T07:13:49.000Z
2021-06-03T18:42:55.000Z
FluxWithRxSwiftSample/Views/LoadingView.swift
fukami421/FluxWithRxSwiftSample
794ce767f81234f5d83df9c866ed041115f80d38
[ "MIT" ]
null
null
null
FluxWithRxSwiftSample/Views/LoadingView.swift
fukami421/FluxWithRxSwiftSample
794ce767f81234f5d83df9c866ed041115f80d38
[ "MIT" ]
12
2016-10-15T14:31:59.000Z
2020-01-05T12:36:27.000Z
// // LoadingView.swift // FluxWithRxSwiftSample // // Created by Yuji Hato on 2016/10/13. // Copyright © 2016年 dekatotoro. All rights reserved. // import UIKit import Cartography import SpringIndicator private let LaodingIndicatorSize: CGFloat = 32 class LoadingView: UIView { enum LoadingType { case fullScreen, fullGuard, point } fileprivate(set) var loadingType: LoadingType = .point let indicator = SpringIndicator(frame: CGRect(x: 0, y: 0, width: LaodingIndicatorSize, height: LaodingIndicatorSize)) override init(frame: CGRect) { super.init(frame: frame) initialize() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initialize() } func initialize() { indicator.lineColor = UIColor.gray indicator.lineWidth = 3 indicator.lineCap = true indicator.rotateDuration = 1.1 indicator.strokeDuration = 0.7 addSubview(indicator) isHidden = true } override func point(inside point: CGPoint, with event: UIEvent?) -> Bool { return loadingType == .fullGuard } @discardableResult func setType(_ loadingType: LoadingType) -> LoadingView { self.loadingType = loadingType backgroundColor = (loadingType == .fullGuard) ? UIColor.black.withAlphaComponent(0.5) : .clear let isFullScreen = (loadingType == .fullScreen || loadingType == .fullGuard) indicator.lineColor = isFullScreen ? UIColor.white : UIColor.gray constrain(indicator) { (view) in view.width == LaodingIndicatorSize view.height == LaodingIndicatorSize } constrain(indicator, self) { (view, superview) in if isFullScreen { let margin: CGFloat = 24 view.bottom == superview.bottom - margin view.right == superview.right - margin } else { view.center == superview.center } } return self } func hidden(_ hidden: Bool) { self.isHidden = hidden if hidden { indicator.stopAnimation(false) } else { indicator.startAnimation() } } }
27.305882
121
0.592848
456865ee3cbd84e3f1f2186796e19e1a2f3ec487
2,337
swift
Swift
RxLEO/RxLEODefaultAPIProvider.swift
isaac-weisberg/RxLEO
6652b57e914a4c83567ca6f5eb81ca25da1765e0
[ "Unlicense" ]
1
2018-11-17T06:07:52.000Z
2018-11-17T06:07:52.000Z
RxLEO/RxLEODefaultAPIProvider.swift
isaac-weisberg/RxLEO
6652b57e914a4c83567ca6f5eb81ca25da1765e0
[ "Unlicense" ]
null
null
null
RxLEO/RxLEODefaultAPIProvider.swift
isaac-weisberg/RxLEO
6652b57e914a4c83567ca6f5eb81ca25da1765e0
[ "Unlicense" ]
null
null
null
// // RxLEODefaultAPIProvider.swift // RxLEO // // Created by Isaac Weisberg on 11/10/18. // Copyright © 2018 Isaac Weisberg. All rights reserved. // import Foundation import RxSwift final public class RxLEODefaultAPIProvider: RxLEOAPIProvider { public init(session: URLSession = .shared) { nick = RxNick(session) } public let nick: RxNick public func request<Target: Decodable>(_ route: LEOBodyfulRoute<Target>) -> Single<RxNickResult<Response<Target>, RxLEOError>> { return nick .bodyfulRequest(route.method, route.url, body: route.body, headers: route.headers) .map { result in result .mapError { .failure(RxLEOError.nick($0)) } .map { fresh -> RxNickResult<Response<Target>, RxLEOError> in let errorResult: RxNickResult<Response<LEOErrorResponse>, NickError> = fresh.json() if case .success(let errorResp) = errorResult { return .failure(RxLEOError.businessProblem(errorResp.target)) } return fresh.json().mapError { .failure(RxLEOError.nick($0)) } } } } public func request<Target: Decodable>(_ route: LEOBodylessRoute<Target>) -> Single<RxNickResult<Response<Target>, RxLEOError>> { return nick .bodylessRequest( route.method, route.url, query: route.query, headers: route.headers ) .map { result in result .mapError { .failure(RxLEOError.nick($0)) } .map { fresh -> RxNickResult<Response<Target>, RxLEOError> in let errorResult: RxNickResult<Response<LEOErrorResponse>, NickError> = fresh.json() if case .success(let errorResp) = errorResult { return .failure(RxLEOError.businessProblem(errorResp.target)) } return fresh.json().mapError { .failure(RxLEOError.nick($0)) } } } } }
38.311475
133
0.515618
2728dbdea23397e72b65e697d6e824f5079e1885
250
kt
Kotlin
app/src/main/java/com/example/weather_android_app/util/ResourceList.kt
Jenil-Vekaria/Weather-Android-App
037c19222cff3e9fcaf7d5ec516a6d183daa0935
[ "MIT" ]
null
null
null
app/src/main/java/com/example/weather_android_app/util/ResourceList.kt
Jenil-Vekaria/Weather-Android-App
037c19222cff3e9fcaf7d5ec516a6d183daa0935
[ "MIT" ]
null
null
null
app/src/main/java/com/example/weather_android_app/util/ResourceList.kt
Jenil-Vekaria/Weather-Android-App
037c19222cff3e9fcaf7d5ec516a6d183daa0935
[ "MIT" ]
null
null
null
package com.example.weather_android_app.util sealed class ResourceList<T>(val data: List<T>?, val message: String?){ class Success<T>(data: List<T>): ResourceList<T>(data,null) class Error<T>(message: String): ResourceList<T>(null,message) }
41.666667
71
0.732
92946d631e8d4037366109179c6173249b9e1d84
160
h
C
WeChatGUI/WeChatDLL/public/Public.h
fjqisba/WeChatStudy
19facc7d722a3468be7ba8763fb6b157d1741d9d
[ "MIT" ]
7
2022-03-28T17:02:14.000Z
2022-03-29T12:59:29.000Z
WeChatGUI/WeChatDLL/public/Public.h
fjqisba/WeChatStudy
19facc7d722a3468be7ba8763fb6b157d1741d9d
[ "MIT" ]
null
null
null
WeChatGUI/WeChatDLL/public/Public.h
fjqisba/WeChatStudy
19facc7d722a3468be7ba8763fb6b157d1741d9d
[ "MIT" ]
5
2022-03-29T01:30:32.000Z
2022-03-30T01:40:29.000Z
#pragma once #include <vector> #include <string> #include <windows.h> std::string ReadFileToString(const char* filepath); unsigned int ReadUint(void*);
20
52
0.725
1690fbe701b16c30b6b42948967c835c2be092d6
444
sql
SQL
debezium/src/test/resources/mssql/setup.sql
Kanugula/hazelcast-jet-contrib
6467f01cf7b9e5ca4bb3702a89c2bb4b3521e854
[ "Apache-2.0" ]
null
null
null
debezium/src/test/resources/mssql/setup.sql
Kanugula/hazelcast-jet-contrib
6467f01cf7b9e5ca4bb3702a89c2bb4b3521e854
[ "Apache-2.0" ]
null
null
null
debezium/src/test/resources/mssql/setup.sql
Kanugula/hazelcast-jet-contrib
6467f01cf7b9e5ca4bb3702a89c2bb4b3521e854
[ "Apache-2.0" ]
null
null
null
CREATE DATABASE MyDB; GO USE MyDB GO EXEC sys.sp_cdc_enable_db GO USE MyDB GO CREATE SCHEMA inventory; GO CREATE TABLE inventory.customers( id INTEGER IDENTITY(1001,1) NOT NULL PRIMARY KEY, first_name VARCHAR(255) NOT NULL, last_name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL UNIQUE ); GO USE MyDB INSERT INTO inventory.customers (first_name, last_name, email) VALUES ('Anne', 'Kretchmar', 'annek@noanswer.org'); GO
16.444444
115
0.75
400ee33e16860ff9a624136708613a23a4a9ad7c
1,478
py
Python
python/lib/adaguc/mockCGIResponse.py
lukas-phaf/adaguc-server
aa5e267d6c5c15463035ff87d353707207374d1b
[ "Apache-2.0" ]
1
2019-08-21T11:03:09.000Z
2019-08-21T11:03:09.000Z
python/lib/adaguc/mockCGIResponse.py
ernstdevreede/adaguc-server
3516bf1a2ea6abb4f2e85e72944589dfcc990f7c
[ "Apache-2.0" ]
null
null
null
python/lib/adaguc/mockCGIResponse.py
ernstdevreede/adaguc-server
3516bf1a2ea6abb4f2e85e72944589dfcc990f7c
[ "Apache-2.0" ]
null
null
null
""" This python script acts like a tiny cgi program. It reads in cgidata.bin and outputs it on stdout. cgidata.bin contains CGI output, e.g. headers and content. This script can be used to write a python script which efficiently separates the headers from the content. To create cgidata.bin, do: export ADAGUC_DB="user=adaguc password=adaguc host=localhost dbname=adaguc" export ADAGUC_CONFIG=./Docker/adaguc-server-config-python-postgres.xml export ADAGUC_DATA_DIR=/data/adaguc-data export ADAGUC_AUTOWMS_DIR=/data/adaguc-autowms export ADAGUC_DATASET_DIR=/data/adaguc-datasets #export QUERY_STRING="source=testdata.nc&&service=WMS&request=getmap&format=image/png&layers=testdata&width=80&CRS=EPSG:4326&STYLES=&EXCEPTIONS=INIMAGE&showlegend=true&0.6600876848451054" export QUERY_STRING="source%3Dtestdata.nc&SERVICE=WMS&&SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=testdata&WIDTH=8000&CRS=EPSG%3A3857&BBOX=-1900028.4595329016,4186308.413385826,2753660.6953178523,9667705.962693866&STYLES=auto%2Fnearest&FORMAT=image/png&TRANSPARENT=TRUE&&0.8416868811008116" export ADAGUC_PATH=/home/plieger/code/github/KNMI/adaguc-server/ export ADAGUC_TMP=/tmp export ADAGUC_LOGFILE=/tmp/test.log rm -rf $ADAGUC_LOGFILE #./bin/adagucserver #cat /tmp/test.log ./bin/adagucserver > python/lib/adaguc/mockcgidata_headersandcontent80px.bin """ import shutil import sys with open(sys.argv[1], "rb") as f: sys.stdout.buffer.write(f.read())
49.266667
298
0.786874
f5dc62184abf6207476e35a77560e67b97fb099c
1,626
lua
Lua
data/scripts/prefabs/shadowtentacle.lua
GuLiPing-Hz/Dontstarve_m
c2f12c8c2b79ed6d5762b130f5702d70bc020596
[ "MIT" ]
4
2019-11-18T08:13:29.000Z
2021-04-02T00:08:35.000Z
data/scripts/prefabs/shadowtentacle.lua
GuLiPing-Hz/Dontstarve_m
c2f12c8c2b79ed6d5762b130f5702d70bc020596
[ "MIT" ]
null
null
null
data/scripts/prefabs/shadowtentacle.lua
GuLiPing-Hz/Dontstarve_m
c2f12c8c2b79ed6d5762b130f5702d70bc020596
[ "MIT" ]
2
2019-08-04T07:12:15.000Z
2019-12-24T03:34:16.000Z
require "stategraphs/SGshadowtentacle" local assets= { Asset("ANIM", "anim/tentacle_arm.zip"), Asset("ANIM", "anim/tentacle_arm_black_build.zip"), Asset("SOUND", "sound/tentacle.fsb"), } local function shouldKeepTarget(inst, target) return true end local function fn(Sim) local inst = CreateEntity() inst.entity:AddTransform() inst.entity:AddAnimState() inst.entity:AddPhysics() inst.Physics:SetCylinder(0.25,2) inst.Transform:SetScale(0.5, 0.5, 0.5) inst.AnimState:SetMultColour(1,1,1,0.5) inst.AnimState:SetBank("tentacle_arm") inst.AnimState:SetBuild("tentacle_arm_black_build") inst.AnimState:PlayAnimation("idle", true) inst.entity:AddSoundEmitter() inst:AddTag("shadow") inst:AddTag("notarget") inst:AddComponent("health") inst.components.health:SetMaxHealth(TUNING.TENTACLE_HEALTH) inst:AddComponent("combat") inst.components.combat:SetRange(2) inst.components.combat:SetDefaultDamage(TUNING.TENTACLE_DAMAGE) inst.components.combat:SetAttackPeriod(TUNING.TENTACLE_ATTACK_PERIOD) inst.components.combat:SetKeepTargetFunction(shouldKeepTarget) inst.components.combat.canbeattackedfn = function() return false end MakeLargeFreezableCharacter(inst) inst:AddComponent("sanityaura") inst.components.sanityaura.aura = -TUNING.SANITYAURA_MED inst:AddComponent("lootdropper") inst.components.lootdropper:SetLoot({}) inst:SetStateGraph("SGshadowtentacle") inst:DoTaskInTime(9, function() inst:Remove() end) return inst end return Prefab( "cave/ruins/shadowtentacle", fn, assets)
28.034483
73
0.737392