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
7dac0033b2f96be56d4f4e976827d9b29c9c3f27
1,933
sql
SQL
src/pg/sql/05_segmentation.sql
splashblot/docker-crankshaft
281fab0bb5e05e91f98aaefc4a5e2b3abefaf18d
[ "BSD-3-Clause" ]
1
2018-06-29T01:46:25.000Z
2018-06-29T01:46:25.000Z
src/pg/sql/05_segmentation.sql
splashblot/docker-crankshaft
281fab0bb5e05e91f98aaefc4a5e2b3abefaf18d
[ "BSD-3-Clause" ]
null
null
null
src/pg/sql/05_segmentation.sql
splashblot/docker-crankshaft
281fab0bb5e05e91f98aaefc4a5e2b3abefaf18d
[ "BSD-3-Clause" ]
1
2019-12-06T16:32:18.000Z
2019-12-06T16:32:18.000Z
CREATE OR REPLACE FUNCTION CDB_CreateAndPredictSegment( target NUMERIC[], features NUMERIC[], target_features NUMERIC[], target_ids NUMERIC[], n_estimators INTEGER DEFAULT 1200, max_depth INTEGER DEFAULT 3, subsample DOUBLE PRECISION DEFAULT 0.5, learning_rate DOUBLE PRECISION DEFAULT 0.01, min_samples_leaf INTEGER DEFAULT 1) RETURNS TABLE(cartodb_id NUMERIC, prediction NUMERIC, accuracy NUMERIC) AS $$ import numpy as np import plpy from crankshaft.segmentation import create_and_predict_segment_agg model_params = {'n_estimators': n_estimators, 'max_depth': max_depth, 'subsample': subsample, 'learning_rate': learning_rate, 'min_samples_leaf': min_samples_leaf} def unpack2D(data): dimension = data.pop(0) a = np.array(data, dtype=float) return a.reshape(len(a)/dimension, dimension) return create_and_predict_segment_agg(np.array(target, dtype=float), unpack2D(features), unpack2D(target_features), target_ids, model_params) $$ LANGUAGE plpythonu; CREATE OR REPLACE FUNCTION CDB_CreateAndPredictSegment ( query TEXT, variable_name TEXT, target_table TEXT, n_estimators INTEGER DEFAULT 1200, max_depth INTEGER DEFAULT 3, subsample DOUBLE PRECISION DEFAULT 0.5, learning_rate DOUBLE PRECISION DEFAULT 0.01, min_samples_leaf INTEGER DEFAULT 1) RETURNS TABLE (cartodb_id TEXT, prediction NUMERIC, accuracy NUMERIC) AS $$ from crankshaft.segmentation import create_and_predict_segment model_params = {'n_estimators': n_estimators, 'max_depth':max_depth, 'subsample' : subsample, 'learning_rate': learning_rate, 'min_samples_leaf' : min_samples_leaf} return create_and_predict_segment(query,variable_name,target_table, model_params) $$ LANGUAGE plpythonu;
35.796296
166
0.707191
e773179e38973a8288f6d18a85b3ce3208fd7f9f
5,909
js
JavaScript
src/renderer/dal/dbinit.js
Sindcs/electron-vue-Note
68975b9678e1a23a47935c1b0a920795cf4613ee
[ "MIT" ]
8
2018-06-08T01:32:40.000Z
2021-08-24T08:52:56.000Z
src/renderer/dal/dbinit.js
Sindcs/elevue-Note
68975b9678e1a23a47935c1b0a920795cf4613ee
[ "MIT" ]
null
null
null
src/renderer/dal/dbinit.js
Sindcs/elevue-Note
68975b9678e1a23a47935c1b0a920795cf4613ee
[ "MIT" ]
2
2019-03-10T16:47:38.000Z
2020-09-15T15:53:50.000Z
/** * 数据库初始化 */ import log from '../foundation/log' import sqlite from '../foundation/sqlitdb' var db = sqlite.sqliteDb const nedb = require('../foundation/nedb') const dbinit = {} dbinit.initDatabase = function () { return nedb.db } dbinit.initTable = function () { return new Promise((resolve, reject) => { let i = 0 if (db) { log.writeDebug('start to create sqlite table') // create resource db.run(`CREATE TABLE IF NOT EXISTS resource ( uuid VARCHAR(36) PRIMARY KEY, ownerId VARCHAR(36), mine VARCHAR(50), width integer, height integer, sourceUrl VARCHAR(200), dateCreated INTEGER, size INTEGER, md5 VARCHAR(32), data blob )`, function (err) { if (err) { log.writeErr(`FAIL on creating table resource:${err}`) reject(err) } else { i++ if (i === 10) { resolve() } } } ) // create cataLog db.run(`CREATE TABLE IF NOT EXISTS cataLog ( uuid VARCHAR(36) PRIMARY KEY, name VARCHAR(100), type VARCHAR(4), isMonitored integer, isChanged integer, cataLogChain VARCHAR(800), monitoredPath VARCHAR(2000), childNum integer, docNum integer, parentCataLogId VARCHAR(36), dateCreated integer )`, function (err) { if (err) { log.writeErr(`FAIL on creating table cataLog:${err}`) reject(err) } else { i++ if (i === 10) { resolve() } } } ) // create tag db.run(`CREATE TABLE IF NOT EXISTS tag ( uuid VARCHAR(36) PRIMARY KEY, name VARCHAR(100), isChanged integer, dateCreated integer )`, function (err) { if (err) { log.writeErr(`FAIL on creating table tag:${err}`) reject(err) } else { i++ if (i === 10) { resolve() } } } ) // create user db.run(`CREATE TABLE IF NOT EXISTS user ( uuid VARCHAR(36) PRIMARY KEY, name VARCHAR(100), fullName VARCHAR(100), dateCreated integer, email VARCHAR(50), notebookCount integer, literatureCount integer, documentMaterial integer )`, function (err) { if (err) { log.writeErr(`FAIL on creating table user:${err}`) reject(err) } else { i++ if (i === 10) { resolve() } } } ) // create document_document db.run(`CREATE TABLE IF NOT EXISTS document_document ( uuid VARCHAR(36), documentId VARCHAR(36), rdocumentId VARCHAR(36), isChanged integer, isDelete integer )`, function (err) { if (err) { log.writeErr(`FAIL on creating table document_document:${err}`) reject(err) } else { i++ if (i === 10) { resolve() } } } ) // create document_document db.run(`CREATE TABLE IF NOT EXISTS tag_document ( uuid VARCHAR(36), documentId VARCHAR(36), tagId VARCHAR(36), isChanged integer, isDelete integer )`, function (err) { if (err) { log.writeErr(`FAIL on creating table tag_document:${err}`) reject(err) } else { i++ if (i === 10) { resolve() } } } ) // create documentcontent db.run(`CREATE TABLE IF NOT EXISTS documentcontent ( uuid VARCHAR(32) PRIMARY KEY, content TEXT )`, function (err) { if (err) { log.writeErr(`FAIL on creating table documentcontent:${err}`) reject(err) } else { i++ if (i === 10) { resolve() } } } ) // create contentIndex db.run(`CREATE VIRTUAL TABLE IF NOT EXISTS contentIndex USING fts4 ( uuid VARCHAR(36) PRIMARY KEY, cataLogId VARCHAR(36), content TEXT )`, function (err) { if (err) { log.writeErr(`FAIL on creating table contentIndex:${err}`) reject(err) } else { i++ if (i === 10) { resolve() } } } ) // create chatMessage db.run(`CREATE TABLE IF NOT EXISTS chatmessage ( uuid VARCHAR(36) PRIMARY KEY, fromId VARCHAR(36), content TEXT, inputTime integer )`, function (err) { if (err) { log.writeErr(`FAIL on creating table chatmessage:${err}`) reject(err) } else { i++ if (i === 10) { resolve() } } } ) // create chatList db.run(`CREATE TABLE IF NOT EXISTS chatList ( friendId VARCHAR(36) PRIMARY KEY, type VARCHAR(20), inputTime integer )`, function (err) { if (err) { log.writeErr(`FAIL on creating table chatList:${err}`) reject(err) } else { i++ if (i === 10) { resolve() } } } ) } else { reject() } }) } export default dbinit
24.620833
75
0.442715
37a4488da734ba253b8d845b346eae193e3895d6
113
sql
SQL
src/test/resources/sql/_unknown/f69d6012.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
66
2018-06-15T11:34:03.000Z
2022-03-16T09:24:49.000Z
src/test/resources/sql/_unknown/f69d6012.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
13
2019-03-19T11:56:28.000Z
2020-08-05T04:20:50.000Z
src/test/resources/sql/_unknown/f69d6012.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
28
2019-01-05T19:59:02.000Z
2022-03-24T11:55:50.000Z
-- file:aggregates.sql ln:673 expect:false if state is null then if n is not null then new_state.total := n
22.6
42
0.716814
7d06407534899fe45fcb10155e79dd9a4ab1ef80
2,279
swift
Swift
Sources/SessionPlus/HTTP.swift
richardpiazza/SessionPlus
bae473594bfdb51d5c3983463aa4cda9b235e4ad
[ "MIT" ]
2
2020-06-19T13:00:47.000Z
2020-08-02T07:07:35.000Z
Sources/SessionPlus/HTTP.swift
richardpiazza/SessionPlus
bae473594bfdb51d5c3983463aa4cda9b235e4ad
[ "MIT" ]
null
null
null
Sources/SessionPlus/HTTP.swift
richardpiazza/SessionPlus
bae473594bfdb51d5c3983463aa4cda9b235e4ad
[ "MIT" ]
null
null
null
import Foundation #if canImport(FoundationNetworking) import FoundationNetworking #endif /// A Collection of methods/headers/values/types used during basic HTTP interactions. public struct HTTP { /// HTTP Headers as provided from HTTPURLResponse public typealias Headers = [AnyHashable : Any] /// General errors that may be encountered during HTTP request/response handling. public enum Error: Swift.Error, LocalizedError { case invalidURL case invalidRequest case invalidResponse public var errorDescription: String? { switch self { case .invalidURL: return "Invalid URL: URL is nil or invalid." case .invalidRequest: return "Invalid URL Request: URLRequest is nil or invalid." case .invalidResponse: return "Invalid URL Response: HTTPURLResponse is nil or invalid." } } } /// A general completion handler for HTTP requests. public typealias DataTaskCompletion = (_ statusCode: Int, _ headers: Headers?, _ data: Data?, _ error: Swift.Error?) -> Void #if swift(>=5.5) && canImport(ObjectiveC) /// The output of an async url request execution. public typealias AsyncDataTaskOutput = (statusCode: Int, headers: Headers, data: Data) #endif } public extension URLRequest { /// Sets a value for the header field. /// /// - parameters: /// - value: The new value for the header field. Any existing value for the field is replaced by the new value. /// - header: The header for which to set the value. (Headers are case sensitive) mutating func setValue(_ value: String, forHTTPHeader header: HTTP.Header) { self.setValue(value, forHTTPHeaderField: header.rawValue) } /// Sets a value for the header field. /// /// - parameters: /// - value: The new value for the header field. Any existing value for the field is replaced by the new value. /// - header: The header for which to set the value. (Headers are case sensitive) mutating func setValue(_ value: HTTP.MIMEType, forHTTPHeader header: HTTP.Header) { self.setValue(value.rawValue, forHTTPHeaderField: header.rawValue) } }
39.293103
128
0.661255
c684f3be73b2558f21388fd11326c75c197bcac7
200
swift
Swift
Example/REIAnalyticsKit/DummySwiftObject.swift
S0MMS/REIAnalyticsKit
b116e02ff9caba8b286f9fde987c2e28b68a7d7a
[ "MIT" ]
null
null
null
Example/REIAnalyticsKit/DummySwiftObject.swift
S0MMS/REIAnalyticsKit
b116e02ff9caba8b286f9fde987c2e28b68a7d7a
[ "MIT" ]
null
null
null
Example/REIAnalyticsKit/DummySwiftObject.swift
S0MMS/REIAnalyticsKit
b116e02ff9caba8b286f9fde987c2e28b68a7d7a
[ "MIT" ]
null
null
null
// // DummySwiftObject.swift // REIAnalyticsKit_Example // // Created by chris1 on 7/30/19. // Copyright © 2019 S0MMS. All rights reserved. // import UIKit class DummySwiftObject: NSObject { }
14.285714
48
0.705
0fe0730b24616f581dd827b97b19c8274ad91f07
466
ps1
PowerShell
Basic/Different-kinds-of-null/.test.ps1
ImportTaste/PowerShellTraps
f43c215b67073cb8f22be662aab5825f72658f5a
[ "Apache-2.0" ]
348
2015-04-09T19:04:40.000Z
2022-03-17T07:32:52.000Z
Basic/Different-kinds-of-null/.test.ps1
ImportTaste/PowerShellTraps
f43c215b67073cb8f22be662aab5825f72658f5a
[ "Apache-2.0" ]
12
2015-05-20T17:17:26.000Z
2021-04-06T09:19:28.000Z
Basic/Different-kinds-of-null/.test.ps1
ImportTaste/PowerShellTraps
f43c215b67073cb8f22be662aab5825f72658f5a
[ "Apache-2.0" ]
37
2015-05-25T08:08:51.000Z
2022-01-20T06:26:13.000Z
$v2 = $PSVersionTable.PSVersion.Major -eq 2 task Test-1-different-results { ($r = .\Test-1-different-results.ps1) if ($v2) { equals 'True|1|1' ($r -join '|') } else { equals 'True|0|1' ($r -join '|') } } task Test-2-not-exactly-null { ($r = .\Test-2-not-exactly-null.ps1) if ($v2) { equals 'PropertyNotFoundStrict|PropertyNotFoundStrict' ($r -join '|') } else { equals 'False|System.Management.Automation.PSCustomObject|True' ($r -join '|') } }
20.26087
80
0.630901
5b35facab14a9dba0d2b47cbc37bbef257bdf268
7,427
sql
SQL
mshopVgitsalah/eshop (2).sql
GITSALAHE/projet-fil-rouge-Youcode
36d09b7758cf46bebd401d04b41c232ee002124c
[ "MIT" ]
2
2020-07-09T21:40:34.000Z
2020-08-16T18:52:21.000Z
mshopVgitsalah/eshop (2).sql
GITSALAHE/projet-fil-rouge-Youcode
36d09b7758cf46bebd401d04b41c232ee002124c
[ "MIT" ]
null
null
null
mshopVgitsalah/eshop (2).sql
GITSALAHE/projet-fil-rouge-Youcode
36d09b7758cf46bebd401d04b41c232ee002124c
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 5.0.2 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Jul 18, 2020 at 03:15 AM -- Server version: 10.4.13-MariaDB -- PHP Version: 7.4.7 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `eshop` -- -- -------------------------------------------------------- -- -- Table structure for table `cart` -- CREATE TABLE `cart` ( `idCart` int(11) NOT NULL, `idP` int(11) NOT NULL, `idU` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `category` -- CREATE TABLE `category` ( `idC` int(11) NOT NULL, `nameCategory` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `category` -- INSERT INTO `category` (`idC`, `nameCategory`) VALUES (10, 'women'), (12, 'men'), (17, 'kids'); -- -------------------------------------------------------- -- -- Table structure for table `orders` -- CREATE TABLE `orders` ( `idOrder` int(11) NOT NULL, `idCart` int(11) NOT NULL, `status` varchar(255) NOT NULL, `payment` varchar(255) NOT NULL, `firstname` varchar(255) NOT NULL, `lastname` varchar(255) NOT NULL, `address` varchar(255) NOT NULL, `zip` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `product` -- CREATE TABLE `product` ( `idP` int(11) NOT NULL, `nameProduct` varchar(255) NOT NULL, `Price` varchar(255) NOT NULL, `Qte` varchar(255) NOT NULL, `Image` varchar(255) NOT NULL, `idC` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `product` -- INSERT INTO `product` (`idP`, `nameProduct`, `Price`, `Qte`, `Image`, `idC`) VALUES (6, 'Jacket', '1200', '23', '1594834578_4087400649_2_1_1-1-300x300.jpg', 12), (8, 'vest', '230', '23', '1594862114_7545310401_1_1_1-300x300.jpg', 12), (9, 'suite', '420', '20', '1595016527_0706406401_1_1_1-300x300.jpg', 12), (10, 'Costume', '1000', '234', '1595016593_7545310401_1_1_1-300x300.jpg', 12), (11, 'Costume premium', '2000', '50', '1595016628_9621450800_1_1_1-300x300.jpg', 12), (12, 'Tshirt', '120', '50', '1595019958_harajuku-t-shirt-women-clothes-2019-streetwear-korean-style-tee-shirt-femme-hip-hop-tops-Japanese__26740.1563312756.jpg', 10), (13, 'test', '1200', '23', '1595022538_82553745_2216498978652522_7352167503109292032_n.jpg', 10); -- -------------------------------------------------------- -- -- Table structure for table `size` -- CREATE TABLE `size` ( `idSize` int(11) NOT NULL, `nameSize` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `size` -- INSERT INTO `size` (`idSize`, `nameSize`) VALUES (1, 'S'), (3, 'M'), (4, 'L'), (7, 'XL'), (8, 'XXXL'); -- -------------------------------------------------------- -- -- Table structure for table `size_product` -- CREATE TABLE `size_product` ( `idPS` int(11) NOT NULL, `idP` int(11) NOT NULL, `idSize` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `size_product` -- INSERT INTO `size_product` (`idPS`, `idP`, `idSize`) VALUES (16, 6, 1), (25, 6, 3), (26, 6, 4), (28, 8, 1), (29, 8, 3), (30, 8, 4), (31, 8, 7), (32, 8, 8), (33, 6, 7), (34, 6, 8), (35, 9, 1), (36, 9, 3), (37, 9, 4), (38, 9, 7), (39, 9, 8), (40, 10, 1), (41, 10, 3), (42, 10, 4), (43, 10, 7), (44, 10, 8), (45, 11, 1), (46, 11, 3), (47, 11, 4), (48, 11, 7), (49, 11, 8), (50, 13, 1), (51, 13, 3), (52, 13, 4), (53, 13, 7), (54, 13, 8), (55, 12, 1), (56, 12, 3), (57, 12, 4), (58, 12, 7), (59, 12, 8); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `idU` int(11) NOT NULL, `fullname` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `phone_number` varchar(255) NOT NULL, `admin` tinyint(4) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `users` -- INSERT INTO `users` (`idU`, `fullname`, `email`, `password`, `phone_number`, `admin`) VALUES (5, 'gitsalah', 'test', '111', '064664872', 1), (6, 'SALAHEDDINE ', 'salah.bouanba2@gmail.com', '$2y$10$mNK3IMFoEiN5zzrxSLBd4.07pV82uxtKSavDTsRZSnFfJ4.gE9m8W', '0661263709', 0); -- -- Indexes for dumped tables -- -- -- Indexes for table `cart` -- ALTER TABLE `cart` ADD PRIMARY KEY (`idCart`), ADD KEY `fk_products` (`idP`), ADD KEY `fk_users` (`idU`); -- -- Indexes for table `category` -- ALTER TABLE `category` ADD PRIMARY KEY (`idC`); -- -- Indexes for table `orders` -- ALTER TABLE `orders` ADD PRIMARY KEY (`idOrder`), ADD KEY `fk_cart` (`idCart`); -- -- Indexes for table `product` -- ALTER TABLE `product` ADD PRIMARY KEY (`idP`), ADD KEY `FK_Categorie` (`idC`); -- -- Indexes for table `size` -- ALTER TABLE `size` ADD PRIMARY KEY (`idSize`); -- -- Indexes for table `size_product` -- ALTER TABLE `size_product` ADD PRIMARY KEY (`idPS`), ADD KEY `fk_sizeproduct` (`idP`), ADD KEY `fk_addSizeproduct` (`idSize`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`idU`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `cart` -- ALTER TABLE `cart` MODIFY `idCart` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `category` -- ALTER TABLE `category` MODIFY `idC` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18; -- -- AUTO_INCREMENT for table `orders` -- ALTER TABLE `orders` MODIFY `idOrder` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `product` -- ALTER TABLE `product` MODIFY `idP` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14; -- -- AUTO_INCREMENT for table `size` -- ALTER TABLE `size` MODIFY `idSize` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10; -- -- AUTO_INCREMENT for table `size_product` -- ALTER TABLE `size_product` MODIFY `idPS` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=60; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `idU` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; -- -- Constraints for dumped tables -- -- -- Constraints for table `cart` -- ALTER TABLE `cart` ADD CONSTRAINT `fk_products` FOREIGN KEY (`idP`) REFERENCES `product` (`idP`), ADD CONSTRAINT `fk_users` FOREIGN KEY (`idU`) REFERENCES `users` (`idU`); -- -- Constraints for table `orders` -- ALTER TABLE `orders` ADD CONSTRAINT `fk_cart` FOREIGN KEY (`idCart`) REFERENCES `cart` (`idCart`); -- -- Constraints for table `product` -- ALTER TABLE `product` ADD CONSTRAINT `FK_Categorie` FOREIGN KEY (`idC`) REFERENCES `category` (`idC`); -- -- Constraints for table `size_product` -- ALTER TABLE `size_product` ADD CONSTRAINT `fk_addSizeproduct` FOREIGN KEY (`idSize`) REFERENCES `size` (`idSize`), ADD CONSTRAINT `fk_sizeproduct` FOREIGN KEY (`idP`) REFERENCES `product` (`idP`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
22.438066
166
0.624748
9b88bc9de33f1e1f12d6c8d554e5b11e0f6b23fa
2,074
js
JavaScript
src/components/Main.js
jonasdk/Malvid
6a560e0ba5147e127f904b6bdd94d044c088a2d1
[ "MIT" ]
1
2019-02-06T07:55:31.000Z
2019-02-06T07:55:31.000Z
src/components/Main.js
jonasdk/Malvid
6a560e0ba5147e127f904b6bdd94d044c088a2d1
[ "MIT" ]
null
null
null
src/components/Main.js
jonasdk/Malvid
6a560e0ba5147e127f904b6bdd94d044c088a2d1
[ "MIT" ]
null
null
null
'use strict' const { bindActionCreators } = require('redux') const { connect } = require('react-redux') const { css } = require('glamor') const h = require('../utils/h') const enhanceState = require('../utils/enhanceState') const actions = require('../actions') const { SIZE_STATUS_ACTIVE } = require('../constants/size') const DocumentTitle = require('react-document-title') const ResizeOverlay = require('./ResizeOverlay') const Nav = require('./Nav') const Resizer = require('./Resizer') const Content = require('./Content') const Empty = require('./Empty') const mapStateToProps = (state) => enhanceState(state) const mapDispatchToProps = (dispatch) => bindActionCreators(actions, dispatch) const style = { self: css({ flexGrow: 1, display: 'flex', minWidth: 0, minHeight: 0 }) } const Main = (props) => { if (props.error != null) return ( h(DocumentTitle, { title: 'Malvid' }, h(Empty, { color: 'currentcolor', text: props.error }) ) ) // No currentComponent means that there are no components at all if (props.currentComponent == null) return ( h(DocumentTitle, { title: props.opts.title }, h(Empty, { color: 'currentcolor', text: 'No components found' }) ) ) return ( h(DocumentTitle, { title: `${ props.currentComponent.name } | ${ props.opts.title }` }, h('div', { className: style.self.toString(), style: { '--size-vertical': `${ props.size.vertical }px`, '--size-horizontal': `${ props.size.horizontal }px` } }, h(Nav, { statuses: props.opts.statuses, components: props.components, currentComponent: props.currentComponent, currentTab: props.currentTab, filter: props.filter, setFilter: props.setFilter }), h(Resizer, { direction: 'horizontal', setSize: props.setSizeHorizontal, setSizeStatus: props.setSizeStatus }), h(Content, props), h(ResizeOverlay, { visible: props.size.status === SIZE_STATUS_ACTIVE }) ) ) ) } module.exports = connect(mapStateToProps, mapDispatchToProps)(Main)
24.116279
89
0.650916
ad4a0a08eae188b1f9340956a389ee04d81e0636
3,634
asm
Assembly
env/zx/esxdos128/page2page.asm
pjshumphreys/querycsv
48453d8c81fb5fc6db495881c99046f7a7656cbc
[ "MIT" ]
18
2017-04-17T23:19:51.000Z
2022-02-09T00:26:21.000Z
env/zx/esxdos128/page2page.asm
pjshumphreys/querycsv
48453d8c81fb5fc6db495881c99046f7a7656cbc
[ "MIT" ]
null
null
null
env/zx/esxdos128/page2page.asm
pjshumphreys/querycsv
48453d8c81fb5fc6db495881c99046f7a7656cbc
[ "MIT" ]
null
null
null
include "../common/equs.inc" DIVMMC equ 0xe3 org 0xbce0 ;--------------------------------------- ; mypager2 - switch to the low bank specified in the accumulator. ; Interupts must be disabled before this function is called mypager2: push bc ld c, DIVMMC ; port used for switching low rom banks out (c), a ; do the switch pop bc or a ;cp 0 jr nz, divmmcExit divmmcDisable: push af ld a, (0x1ffa) cp 0xc9 jr nz, divmmcSkip call 0x1ffa divmmcSkip: pop af divmmcExit: ret defs 10, 0 ; 32 bytes total ;-------------------------------------------------------- ; page2page - copy data pointed to by the stack pointer into a location that ends at the value pointed to by hl. ; The amount of bytes to copy is specified indirectly via the value in the bc register di push af ld a, (bankm) ; get the current bankm state and 0xf8 ; filter out which RAM page is currently switched in at 0xc000-0xffff push hl ; backup hl ld hl, bankmBackup ; bankmBackup contains the number of the high bank (0-7) to return to after the data is copied (usually bank 0?) or (hl) ; add the value in bankmBackup to the accumulator ld (bankmBackup), a ; load the resultant acculumator value back into backmBackup. This will allow us to switch back to a particular high bank after the data copying has been completed and 0xf8 ld hl, destinationHighBank ; which high bank to copy the data into (usually bank 7?) or (hl) pop hl ; restore hl call switchPage di pop af Loop2: pop de ld (hl), e dec hl ld (hl), d dec hl djnz Loop2 dec c jr nz, Loop2 push af ld a, (bankmBackup) ; get bankm state to restore call switchPage pop af jp jumptoit ;--------------------------------------------------------------------------------------------------------- ;loadFromDisk2 - loads virtual pages into low banks during program startup so that they can be quickly retrieved later loadFromDisk2: ;; 5 pages can be preloaded into low banks. unrolled for simplicity di ld a, (bankm) and 0xf8 or 1 ; high ram bank 1 call switchPage di call loadFromDisk3 call loadFromDisk3 call loadFromDisk3 call loadFromDisk3 call loadFromDisk3 ld a, (bankm) and 0xf8 ; high ram bank 0 jp switchPage loadFromDisk3: push de ; de contains the virtual page number we want to load into the low bank push hl ; (hl) contains the low bank number we obtained from calling RESI_ALLOC ld a, e call dosload ; dosload re-enables interupts before it returns back to here... di ; ... so disable interrupts again pop hl push hl ld a, (hl) ; put the low bank number into the accumulator call mypager ; switch it in to $2000-$3fff ; copy the code to the right place ld hl, 0xc000 ; hl = source address for ldir ld de, 0x2000 ; de = destination address for ldir ld bc, 8192 ; bc = number of bytes to copy for ldir ldir pop hl push hl ld a, (hl) ; put the low bank number into the accumulator inc a call mypager ; switch it in to $2000-$3fff ; copy the code to the right place ld hl, 0xe000 ; hl = source address for ldir ld de, 0x2000 ; de = destination address for ldir ld bc, 8192 ; bc = number of bytes to copy for ldir ldir ld a, (basicBank) ; put the low bank number into the accumulator call mypager ; switch it in to $2000-$3fff pop hl pop de inc de inc hl ret ;--------------------------------------- ; pad the output binary out to the proper size. ; This is needed as the code above will be replaced by the interrupt mode 2 jump table after the program has started up. defs 0x101 - ASMPC, 0xbf
27.740458
187
0.660154
c6b33c22f9a9b72269f3d472eff87d6b8a093056
15,432
ps1
PowerShell
Public/Initialize-OSDBuilder.ps1
byteben/OSDBuilder
fbd53c0ad1e856f88450a534f30db81a60a473df
[ "MIT" ]
1
2021-07-20T23:29:50.000Z
2021-07-20T23:29:50.000Z
Public/Initialize-OSDBuilder.ps1
byteben/OSDBuilder
fbd53c0ad1e856f88450a534f30db81a60a473df
[ "MIT" ]
null
null
null
Public/Initialize-OSDBuilder.ps1
byteben/OSDBuilder
fbd53c0ad1e856f88450a534f30db81a60a473df
[ "MIT" ]
null
null
null
function Initialize-OSDBuilder { [CmdletBinding()] Param ( #Sets the OSDBuilder Path in the Registry [string]$SetHome ) #=================================================================================================== # GetOSDBuilderHome #=================================================================================================== if (! (Test-Path HKCU:\Software\OSDeploy)) { Try {New-Item HKCU:\Software -Name OSDeploy -Force | Out-Null} Catch {Write-Warning 'Unable to New-Item HKCU:\Software\OSDeploy'; Break} } if (Get-ItemProperty -Path 'HKCU:\Software\OSDeploy' -Name OSBuilderPath -ErrorAction SilentlyContinue) { Try {Rename-ItemProperty -Path 'HKCU:\Software\OSDeploy' -Name OSBuilderPath -NewName GetOSDBuilderHome -Force | Out-Null} Catch {Write-Warning 'Unable to Rename-ItemProperty HKCU:\Software\OSDeploy OSBuilderPath to GetOSDBuilderHome'; Break} } if (! (Get-ItemProperty -Path HKCU:\Software\OSDeploy -Name GetOSDBuilderHome -ErrorAction SilentlyContinue)) { Try {New-ItemProperty -Path HKCU:\Software\OSDeploy -Name GetOSDBuilderHome -Force | Out-Null} Catch {Write-Warning 'Unable to New-ItemProperty HKCU:\Software\OSDeploy GetOSDBuilderHome'; Break} } if ($SetHome) { Try {Set-ItemProperty -Path HKCU:\Software\OSDeploy -Name GetOSDBuilderHome -Value $SetHome -Force} Catch {Write-Warning "Unable to Set-ItemProperty HKCU:\Software\OSDeploy GetOSDBuilderHome to $SetHome"; Break} } $global:GetOSDBuilderHome = $(Get-ItemProperty "HKCU:\Software\OSDeploy").GetOSDBuilderHome if ($null -eq $global:GetOSDBuilderHome) {$global:GetOSDBuilderHome = "$env:SystemDrive\OSDBuilder"} #=================================================================================================== # Initialize OSDBuilder Variables #=================================================================================================== Write-Verbose "Initializing OSDBuilder ..." -Verbose $global:GetOSDBuilder = [ordered]@{ Home = $global:GetOSDBuilderHome Initialize = $true JsonLocal = Join-Path $global:GetOSDBuilderHome 'OSDBuilder.json' JsonGlobal = Join-Path $env:ProgramData 'OSDeploy\OSDBuilder.json' <# PathContentADK = Join-Path $global:GetOSDBuilderHome 'Content\ADK' PathContentDaRT = Join-Path $global:GetOSDBuilderHome 'Content\DaRT' PathContentDrivers = Join-Path $global:GetOSDBuilderHome 'Content\Drivers' PathContentExtraFiles = Join-Path $global:GetOSDBuilderHome 'Content\ExtraFiles' PathContentIsoExtract = Join-Path $global:GetOSDBuilderHome 'Content\IsoExtract' PathContentOneDrive = Join-Path $global:GetOSDBuilderHome 'Content\OneDrive' PathContentPackages = Join-Path $global:GetOSDBuilderHome 'Content\Packages' PathContentScripts = Join-Path $global:GetOSDBuilderHome 'Content\Scripts' PathContentStartLayout = Join-Path $global:GetOSDBuilderHome 'Content\StartLayout' PathContentUnattend = Join-Path $global:GetOSDBuilderHome 'Content\Unattend' #> } $global:SetOSDBuilder = [ordered]@{ AllowContentPacks = $true AllowGlobalOptions = $true #AllowLocalPriority = $false PathContent = Join-Path $global:GetOSDBuilderHome 'Content' PathContentPacks = Join-Path $global:GetOSDBuilderHome 'ContentPacks' PathFeatureUpdates = Join-Path $global:GetOSDBuilderHome 'FeatureUpdates' PathMount = Join-Path $global:GetOSDBuilderHome 'Mount' PathOSBuilds = Join-Path $global:GetOSDBuilderHome 'OSBuilds' PathOSImport = Join-Path $global:GetOSDBuilderHome 'OSImport' PathOSMedia = Join-Path $global:GetOSDBuilderHome 'OSMedia' PathPEBuilds = Join-Path $global:GetOSDBuilderHome 'PEBuilds' PathTasks = Join-Path $global:GetOSDBuilderHome 'Tasks' PathTemplates = Join-Path $global:GetOSDBuilderHome 'Templates' PathUpdates = Join-Path $global:GetOSDBuilderHome 'Updates' #Get-DownOSDBuilder #Get-OSBuilds #Get-OSDBuilder #Get-OSMedia #Get-PEBuilds #Import-OSMedia ImportOSMediaAllowUnsupporteOS = $false ImportOSMediaBuildNetFX = $false ImportOSMediaEditionId = $null ImportOSMediaImageIndex = $null ImportOSMediaImageName = $null ImportOSMediaShowInfo = $false ImportOSMediaSkipGrid = $false ImportOSMediaSkipFeatureUpdates = $false ImportOSMediaUpdate = $false #Initialize-OSDBuilder #New-OSBuild NewOSBuildByTaskName = $null NewOSBuildCreateISO = $false NewOSBuildDontUseNewestMedia = $false NewOSBuildDownload = $false NewOSBuildExecute = $false NewOSBuildEnableNetFX = $false NewOSBuildHideCleanupProgress = $false NewOSBuildPauseDismountOS = $false NewOSBuildPauseDismountPE = $false NewOSBuildSelectContentPacks = $false NewOSBuildSelectUpdates = $false NewOSBuildShowHiddenOSMedia = $false NewOSBuildSkipComponentCleanup = $false NewOSBuildSkipContentPacks = $false NewOSBuildSkipTask = $false NewOSBuildSkipTemplates = $false NewOSBuildSkipUpdates = $false #New-OSBuildMultiLang #New-OSBuildTask NewOSBuildTaskAddContentPacks = $false NewOSBuildTaskContentDrivers = $false NewOSBuildTaskContentExtraFiles = $false NewOSBuildTaskContentFeaturesOnDemand = $false NewOSBuildTaskContentLanguagePackages = $false NewOSBuildTaskContentPackages = $false NewOSBuildTaskContentScripts = $false NewOSBuildTaskContentStartLayout = $false NewOSBuildTaskContentUnattend = $false NewOSBuildTaskContentWinPEADK = $false NewOSBuildTaskContentWinPEDart = $false NewOSBuildTaskContentWinPEDrivers = $false NewOSBuildTaskContentWinPEExtraFiles = $false NewOSBuildTaskContentWinPEScripts = $false NewOSBuildTaskCustomName = $null NewOSBuildTaskDisableFeature = $false NewOSBuildTaskEnableFeature = $false NewOSBuildTaskEnableNetFX3 = $false NewOSBuildTaskRemoveAppx = $false NewOSBuildTaskRemoveCapability = $false NewOSBuildTaskRemovePackage = $false NewOSBuildTaskTaskName = $null NewOSBuildTaskWinPEAutoExtraFiles = $false #New-OSDBuilderContentPack #New-OSDBuilderISO #New-OSDBuilderUSB #New-OSDBuilderVHD #New-PEBuild NewPEBuildCreateISO = $false NewPEBuildExecute = $false NewPEBuildPauseDismount = $false NewPEBuildPauseMount = $false #New-PEBuildTask #Show-OSDBuilderInfo #Update-OSMedia UpdateOSMediaCreateISO = $false UpdateOSMediaDownload = $false UpdateOSMediaExecute = $false UpdateOSMediaHideCleanupProgress = $false UpdateOSMediaName = $null UpdateOSMediaPauseDismountOS = $false UpdateOSMediaPauseDismountPE = $false UpdateOSMediaSelectUpdates = $false UpdateOSMediaShowHiddenOSMedia = $false UpdateOSMediaSkipComponentCleanup = $false UpdateOSMediaSkipUpdates = $false } #=================================================================================================== # Import Local JSON #=================================================================================================== if (Test-Path $global:GetOSDBuilder.JsonLocal) { Write-Verbose "Importing OSDBuilder Local Settings $($global:GetOSDBuilder.JsonLocal)" Try { $global:GetOSDBuilder.LocalSettings = (Get-Content $global:GetOSDBuilder.JsonLocal -RAW | ConvertFrom-Json).PSObject.Properties | foreach {[ordered]@{Name = $_.Name; Value = $_.Value}} | ConvertTo-Json | ConvertFrom-Json $global:GetOSDBuilder.LocalSettings | foreach { Write-Verbose "$($_.Name) = $($_.Value)" $global:SetOSDBuilder.$($_.Name) = $($_.Value) } } Catch {Write-Warning "Unable to import $($global:GetOSDBuilder.JsonLocal)"} } if ($global:SetOSDBuilder.AllowGlobalOptions -eq $true) { if (Test-Path $global:GetOSDBuilder.JsonGlobal) { Write-Verbose "Importing OSDBuilder Global Settings $($global:GetOSDBuilder.JsonGlobal)" Try { $global:GetOSDBuilder.GlobalSettings = (Get-Content $global:GetOSDBuilder.JsonGlobal -RAW | ConvertFrom-Json).PSObject.Properties | foreach {[ordered]@{Name = $_.Name; Value = $_.Value}} | ConvertTo-Json | ConvertFrom-Json $global:GetOSDBuilder.GlobalSettings | foreach { Write-Verbose "$($_.Name) = $($_.Value)" $global:SetOSDBuilder.$($_.Name) = $($_.Value) } } Catch {Write-Warning "Unable to import $($global:GetOSDBuilder.JsonGlobal)"} } } <# if ($global:SetOSDBuilder.AllowLocalPriority -eq $true) { if (Test-Path $global:GetOSDBuilder.JsonLocal) { Write-Verbose "Importing OSDBuilder Local Priority $($global:GetOSDBuilder.JsonLocal) as Priority" Try { $global:GetOSDBuilder.LocalSettings = (Get-Content $global:GetOSDBuilder.JsonLocal -RAW | ConvertFrom-Json).PSObject.Properties | foreach {[ordered]@{Name = $_.Name; Value = $_.Value}} | ConvertTo-Json | ConvertFrom-Json $global:GetOSDBuilder.LocalSettings | foreach { Write-Verbose "$($_.Name) = $($_.Value)" $global:SetOSDBuilder.$($_.Name) = $($_.Value) } } Catch {Write-Warning "Unable to import $($global:GetOSDBuilder.JsonLocal)"} } } #> #=================================================================================================== # Set Content Paths #=================================================================================================== $global:GetOSDBuilder.PathContentADK = Join-Path $global:SetOSDBuilder.PathContent 'ADK' $global:GetOSDBuilder.PathContentDaRT = Join-Path $global:SetOSDBuilder.PathContent 'DaRT' $global:GetOSDBuilder.PathContentDrivers = Join-Path $global:SetOSDBuilder.PathContent 'Drivers' $global:GetOSDBuilder.PathContentExtraFiles = Join-Path $global:SetOSDBuilder.PathContent 'ExtraFiles' $global:GetOSDBuilder.PathContentIsoExtract = Join-Path $global:SetOSDBuilder.PathContent 'IsoExtract' $global:GetOSDBuilder.PathContentOneDrive = Join-Path $global:SetOSDBuilder.PathContent 'OneDrive' $global:GetOSDBuilder.PathContentPackages = Join-Path $global:SetOSDBuilder.PathContent 'Packages' $global:GetOSDBuilder.PathContentScripts = Join-Path $global:SetOSDBuilder.PathContent 'Scripts' $global:GetOSDBuilder.PathContentStartLayout = Join-Path $global:SetOSDBuilder.PathContent 'StartLayout' $global:GetOSDBuilder.PathContentUnattend = Join-Path $global:SetOSDBuilder.PathContent 'Unattend' #=================================================================================================== # Get Variables #=================================================================================================== $global:GetOSDBuilderHome = $global:GetOSDBuilder.Home $global:GetOSDBuilderPathContentADK = $global:GetOSDBuilder.PathContentADK $global:GetOSDBuilderPathContentDaRT = $global:GetOSDBuilder.PathContentDaRT $global:GetOSDBuilderPathContentDrivers = $global:GetOSDBuilder.PathContentDrivers $global:GetOSDBuilderPathContentExtraFiles = $global:GetOSDBuilder.PathContentExtraFiles $global:GetOSDBuilderPathContentIsoExtract = $global:GetOSDBuilder.PathContentIsoExtract $global:GetOSDBuilderPathContentOneDrive = $global:GetOSDBuilder.PathContentOneDrive $global:GetOSDBuilderPathContentPackages = $global:GetOSDBuilder.PathContentPackages $global:GetOSDBuilderPathContentScripts = $global:GetOSDBuilder.PathContentScripts $global:GetOSDBuilderPathContentStartLayout = $global:GetOSDBuilder.PathContentStartLayout $global:GetOSDBuilderPathContentUnattend = $global:GetOSDBuilder.PathContentUnattend #=================================================================================================== # Set Variables #=================================================================================================== $global:SetOSDBuilderPathContent = $global:SetOSDBuilder.PathContent $global:SetOSDBuilderPathContentPacks = $global:SetOSDBuilder.PathContentPacks $global:SetOSDBuilderPathMount = $global:SetOSDBuilder.PathMount $global:SetOSDBuilderPathOSBuilds = $global:SetOSDBuilder.PathOSBuilds $global:SetOSDBuilderPathFeatureUpdates = $global:SetOSDBuilder.PathFeatureUpdates $global:SetOSDBuilderPathOSImport = $global:SetOSDBuilder.PathOSImport $global:SetOSDBuilderPathOSMedia = $global:SetOSDBuilder.PathOSMedia $global:SetOSDBuilderPathPEBuilds = $global:SetOSDBuilder.PathPEBuilds $global:SetOSDBuilderPathTasks = $global:SetOSDBuilder.PathTasks $global:SetOSDBuilderPathTemplates = $global:SetOSDBuilder.PathTemplates $global:SetOSDBuilderPathUpdates = $global:SetOSDBuilder.PathUpdates #=================================================================================================== # Corrections #=================================================================================================== if (Test-Path "$GetOSDBuilderHome\Media") { Write-Warning "Renaming $GetOSDBuilderHome\Media to $SetOSDBuilderPathFeatureUpdates" Rename-Item "$GetOSDBuilderHome\Media" "$SetOSDBuilderPathFeatureUpdates" -Force | Out-Null } if (Test-Path "$GetOSDBuilderHome\OSDownload") { Write-Warning "Renaming $GetOSDBuilderHome\OSDownload to $SetOSDBuilderPathFeatureUpdates" Rename-Item "$GetOSDBuilderHome\OSDownload" "$SetOSDBuilderPathFeatureUpdates" -Force | Out-Null } if (Test-Path "$SetOSDBuilderPathContent\OSDUpdate") { Write-Warning "Moving $SetOSDBuilderPathContent\OSDUpdate to $SetOSDBuilderPathUpdates" if (! (Test-Path $SetOSDBuilderPathUpdates)) {New-Item $SetOSDBuilderPathUpdates -ItemType Directory -Force | Out-Null} Move-Item -Path "$SetOSDBuilderPathContent\OSDUpdate\*" -Destination $SetOSDBuilderPathUpdates -Force -ErrorAction SilentlyContinue | Out-Null Remove-Item "$SetOSDBuilderPathContent\OSDUpdate" -Recurse -Force -ErrorAction SilentlyContinue | Out-Null } if (Test-Path "$SetOSDBuilderPathContent\Mount") { Write-Warning "$SetOSDBuilderPathContent\Mount has been moved to $SetOSDBuilderPathMount" Write-Warning "Verify that you don't have any active mounted images and remove this directory" } }
59.583012
238
0.625778
81faa610d8ea86d1c19bd4b3b34d2fb80f6e9f41
74
go
Go
hpg/results.go
yosssi/hpg
d4decaa4c4d9740a141cc21cb78d256043413b4c
[ "MIT" ]
1
2015-02-04T09:56:17.000Z
2015-02-04T09:56:17.000Z
hpg/results.go
yosssi/go-hpg
d4decaa4c4d9740a141cc21cb78d256043413b4c
[ "MIT" ]
null
null
null
hpg/results.go
yosssi/go-hpg
d4decaa4c4d9740a141cc21cb78d256043413b4c
[ "MIT" ]
null
null
null
package hpg // Results はレスポンスデータを表すインターフェースである。 type Results interface{}
14.8
35
0.810811
63648070c34e60d16a512eaa6b673371ae782231
893
sql
SQL
db_setup/testing_schema.sql
williamscollege/eqreserve
91cf523481a8a7d1c0d12b1e5c2b864bffacef41
[ "MIT" ]
3
2015-01-06T21:39:42.000Z
2018-03-22T16:12:49.000Z
db_setup/testing_schema.sql
williamscollege/eqreserve
91cf523481a8a7d1c0d12b1e5c2b864bffacef41
[ "MIT" ]
null
null
null
db_setup/testing_schema.sql
williamscollege/eqreserve
91cf523481a8a7d1c0d12b1e5c2b864bffacef41
[ "MIT" ]
null
null
null
/* PROJECT: Equipment Reserve (eqreserve) SQL DESCR: This creates a table that is used by the testing suites to verify database connection functionality and to test the DB linking class NOTES: This is for development only! You do not need this on the production server (though it shouldn't hurt anything to have it there) FOR TESTING ONLY: DROP TABLE `dblinktest`; */ # ---------------------------- # IMPORTANT: Select which database you wish to run this script against # ---------------------------- # USE eqreserve; USE eqreservetest; CREATE TABLE IF NOT EXISTS `dblinktest` ( `dblinktest_id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, `charfield` VARCHAR(255) NULL, `intfield` INT NOT NULL, `flagfield` INT(1) NOT NULL DEFAULT 0 ) ENGINE=innodb DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT='used for testing based DB-link class';
30.793103
136
0.699888
f04d3f1d74f6c269738f89d87766211a982c25ba
3,926
py
Python
applications/ShapeOptimizationApplication/python_scripts/analyzer_internal.py
AndreaVoltan/MyKratos7.0
e977752722e8ef1b606f25618c4bf8fd04c434cc
[ "BSD-4-Clause" ]
2
2020-04-30T19:13:08.000Z
2021-04-14T19:40:47.000Z
applications/ShapeOptimizationApplication/python_scripts/analyzer_internal.py
AndreaVoltan/MyKratos7.0
e977752722e8ef1b606f25618c4bf8fd04c434cc
[ "BSD-4-Clause" ]
1
2020-04-30T19:19:09.000Z
2020-05-02T14:22:36.000Z
applications/ShapeOptimizationApplication/python_scripts/analyzer_internal.py
AndreaVoltan/MyKratos7.0
e977752722e8ef1b606f25618c4bf8fd04c434cc
[ "BSD-4-Clause" ]
1
2020-06-12T08:51:24.000Z
2020-06-12T08:51:24.000Z
# ============================================================================== # KratosShapeOptimizationApplication # # License: BSD License # license: ShapeOptimizationApplication/license.txt # # Main authors: Baumgaertner Daniel, https://github.com/dbaumgaertner # Geiser Armin, https://github.com/armingeiser # # ============================================================================== # Making KratosMultiphysics backward compatible with python 2.6 and 2.7 from __future__ import print_function, absolute_import, division # Kratos Core and Apps from KratosMultiphysics import * from KratosMultiphysics.StructuralMechanicsApplication import * # Additional imports import response_function_factory import time as timer # ============================================================================== class KratosInternalAnalyzer( (__import__("analyzer_base")).AnalyzerBaseClass ): # -------------------------------------------------------------------------- def __init__( self, optimization_settings, model_part_controller ): self.model_part_controller = model_part_controller self.response_function_list = response_function_factory.CreateListOfResponseFunctions(optimization_settings, self.model_part_controller.GetModel()) # -------------------------------------------------------------------------- def InitializeBeforeOptimizationLoop( self ): for response in self.response_function_list.values(): response.Initialize() # -------------------------------------------------------------------------- def AnalyzeDesignAndReportToCommunicator( self, currentDesign, optimizationIteration, communicator ): optimization_model_part = self.model_part_controller.GetOptimizationModelPart() time_before_analysis = optimization_model_part.ProcessInfo.GetValue(TIME) step_before_analysis = optimization_model_part.ProcessInfo.GetValue(STEP) delta_time_before_analysis = optimization_model_part.ProcessInfo.GetValue(DELTA_TIME) for identifier, response in self.response_function_list.items(): # Reset step/time iterators such that they match the optimization iteration after calling CalculateValue (which internally calls CloneTimeStep) optimization_model_part.ProcessInfo.SetValue(STEP, step_before_analysis-1) optimization_model_part.ProcessInfo.SetValue(TIME, time_before_analysis-1) optimization_model_part.ProcessInfo.SetValue(DELTA_TIME, 0) response.InitializeSolutionStep() # response values if communicator.isRequestingValueOf(identifier): response.CalculateValue() communicator.reportValue(identifier, response.GetValue()) # response gradients if communicator.isRequestingGradientOf(identifier): response.CalculateGradient() communicator.reportGradient(identifier, response.GetShapeGradient()) response.FinalizeSolutionStep() # Clear results or modifications on model part optimization_model_part.ProcessInfo.SetValue(STEP, step_before_analysis) optimization_model_part.ProcessInfo.SetValue(TIME, time_before_analysis) optimization_model_part.ProcessInfo.SetValue(DELTA_TIME, delta_time_before_analysis) self.model_part_controller.SetMeshToReferenceMesh() self.model_part_controller.SetDeformationVariablesToZero() # -------------------------------------------------------------------------- def FinalizeAfterOptimizationLoop( self ): for response in self.response_function_list.values(): response.Finalize() # ==============================================================================
50.333333
156
0.609272
38fd74038e12d2a8ca9a5d175e0d596ceda75696
756
sql
SQL
web400-3(swpu_ctf)/db.sql
mehrdad-shokri/CTF_web
206529603af3824fc8117166ff978af3495f5a58
[ "MIT" ]
664
2016-08-23T01:03:00.000Z
2022-03-20T17:02:45.000Z
web400-3(swpu_ctf)/db.sql
CTFshow/CTF_web
206529603af3824fc8117166ff978af3495f5a58
[ "MIT" ]
12
2016-09-09T07:25:12.000Z
2021-10-05T21:11:48.000Z
web400-3(swpu_ctf)/db.sql
CTFshow/CTF_web
206529603af3824fc8117166ff978af3495f5a58
[ "MIT" ]
203
2016-10-17T02:15:33.000Z
2021-10-17T06:36:37.000Z
CREATE DATABASE `ctf` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; use `ctf`; CREATE table `user` ( `userid` int(11) not null primary key auto_increment, `name` varchar(20) not null , `salt` varchar(40) not null , `passwd` varchar(40) not null , `check` varchar(40) not null , `role` int(2) not null DEFAULT 0 )ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE table `msg`( `id` int(11) not null primary key auto_increment, `userid` int(11) not null, `msg` varchar(100) not null )ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE table `flag`( `flag` varchar(40) not null )ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into flag(`flag`) values ('flag{37316894c36cb32d2ca3f7d3add88024}'); -- admin 自己注册吧,吧role修改未1就行了
25.2
75
0.698413
028ad2f334bbb0af34d2eb21dafe57fd52ade71a
3,875
ps1
PowerShell
ExpiringPasswordAudit.ps1
mmcglothern/PS_Utils
4ad99f7e37379b5224514072729235470d2d9ce7
[ "MIT" ]
null
null
null
ExpiringPasswordAudit.ps1
mmcglothern/PS_Utils
4ad99f7e37379b5224514072729235470d2d9ce7
[ "MIT" ]
null
null
null
ExpiringPasswordAudit.ps1
mmcglothern/PS_Utils
4ad99f7e37379b5224514072729235470d2d9ce7
[ "MIT" ]
null
null
null
#Script checks for AD accounts nearing expiration and emails reminders to the users. #Already-expired passwords also have a notification sent to the configured administrator email address. #This can be configured as a scheduled task to run at whatever interval is desired. #Written by Mike McGlothern 2/23/2016, version 1.0 #CONFIGURE THESE VARIABLES BEFORE USE $SMTPServerIP = "YOUR IP HERE" $FromAddress = "Your sending email address here" $AdminAddress = "Your address for expired account notifications" $maxPasswordAgeTimeSpan = (Get-ADDefaultDomainPasswordPolicy).MaxPasswordAge import-module ActiveDirectory; Get-ADUser -filter * -properties PasswordLastSet, PasswordExpired, PasswordNeverExpires, EmailAddress, GivenName, Name, SamAccountName | foreach { $today=get-date $UserName=$_.GivenName $Email=$_.EmailAddress if (!$_.PasswordExpired -and !$_.PasswordNeverExpires) { $ExpiryDate=$_.PasswordLastSet + $maxPasswordAgeTimeSpan $DaysLeft=($ExpiryDate-$today).days if ($DaysLeft -lt 7 -and $DaysLeft -gt 0){ $WarnMsg = " <p style='font-family:calibri'>Hi $UserName,</p> <p style='font-family:calibri'>Your Windows login password will expire in $DaysLeft days, please press CTRL-ALT-DEL and change your password. As a reminder, you will have to enter your new password into your mobile device if prompted.</p> <p style='font-family:calibri'>Requirements for the password are as follows:</p> <ul style='font-family:calibri'> <li>Must not contain the user's account name or parts of the user's full name that exceed two consecutive characters</li> <li>Must not be one of your last 5 passwords</li> <li>Contain characters from three of the following four categories:</li> <li>English uppercase characters (A through Z)</li> <li>English lowercase characters (a through z)</li> <li>Base 10 digits (0 through 9)</li> <li>Non-alphabetic characters (for example, !, $, #, %)</li> </ul> <p style='font-family:calibri'>For any assistance, visit the <a href='http://supportURL.com'>Help Desk</a></p> <p style='font-family:calibri'>-Your IT Department</p> " ForEach ($email in $_.EmailAddress) { Write-Host "...User with expiring password: $username ($expirydate; $Email)" -ForegroundColor Red #write-host $warnmsg #send-mailmessage -to $email -from $FromAddress -Subject "Password Reminder: Your password will expire in $DaysLeft days" -body $WarnMsg -smtpserver $SMTPServerIP -BodyAsHtml If ($DaysLeft -lt 3) {send-mailmessage -to $email -from $FromAddress -Subject "Password Reminder: Your password will expire in $DaysLeft days" -body $WarnMsg -smtpserver $SMTPServerIP -BodyAsHtml -Priority High} Else {send-mailmessage -to $email -from $FromAddress -Subject "Password Reminder: Your password will expire in $DaysLeft days" -body $WarnMsg -smtpserver $SMTPServerIP -BodyAsHtml} } } } ElseIf ($_.Enabled -and $_.PasswordExpired) { Write-host "Account $UserName ('$_.Name') is enabled but password is expired, please review" $ExpiryDate=$_.PasswordLastSet + $maxPasswordAgeTimeSpan $DaysLeft=($ExpiryDate-$today).days $ExpiredMsg = " <p style='font-family:calibri'>The user $UserName ('$_.Name') has an expired password but the account is still enabled.</p> <p style='font-family:calibri'>This account should be reviewed and password updated, or account disabled if not in use.</p> <li>Expiry date: $ExpiryDate</li> <li>Days Left: $DaysLeft</li> " send-mailmessage -to $AdminAddress -from $FromAddress -Subject "Account $UserName has expired password." -body $ExpiredMsg -smtpserver $SMTPServerIP -BodyAsHtml -Priority High } }
55.357143
240
0.698581
f0706f06dae68a2eb12befe8740b73ce25344c53
10,323
py
Python
tests/test_cli.py
redglue/brickops
77fbe0da295f69b2b8bfebd0ec2c8b3bfdb1046b
[ "BSD-3-Clause" ]
null
null
null
tests/test_cli.py
redglue/brickops
77fbe0da295f69b2b8bfebd0ec2c8b3bfdb1046b
[ "BSD-3-Clause" ]
3
2019-07-23T16:38:14.000Z
2021-06-02T03:55:23.000Z
tests/test_cli.py
aquicore/apparate
bc0d9a5db2ffb863ddde4ff61ac2ac0dbc8f1bad
[ "BSD-3-Clause" ]
null
null
null
import logging from os.path import expanduser, join from unittest import mock import pytest from click.testing import CliRunner from configparser import ConfigParser from apparate.configure import configure from apparate.cli_commands import upload, upload_and_update logging.basicConfig(level=logging.INFO) logger = logging.getLogger('apparate.cli_commands') def test_configure_no_existing_config(): expected_stdout = ( 'Databricks host (e.g. https://my-organization.cloud.databricks.com): ' 'https://test_host\n' 'Databricks API token: \n' 'Repeat for confirmation: \n' 'Databricks folder for production libraries: test_folder\n' ) filename = join(expanduser('~'), '.apparatecfg') expected_call_list = [ mock.call(filename, encoding=None), mock.call(filename, 'w+'), mock.call().write('[DEFAULT]\n'), mock.call().write('host = https://test_host\n'), mock.call().write('token = test_token\n'), mock.call().write('prod_folder = test_folder\n'), mock.call().write('\n'), ] with mock.patch('builtins.open', mock.mock_open(read_data='')) as m_open: runner = CliRunner() result = runner.invoke( configure, input=( 'https://test_host\n' 'test_token\n' 'test_token\n' 'test_folder\n' ), ) m_open.assert_has_calls(expected_call_list, any_order=True) assert not result.exception assert result.output == expected_stdout def test_configure_extra_slash_in_host(): expected_stdout = ( 'Databricks host (e.g. https://my-organization.cloud.databricks.com): ' 'https://test_host/\n' 'Databricks API token: \n' 'Repeat for confirmation: \n' 'Databricks folder for production libraries: test_folder\n' ) filename = join(expanduser('~'), '.apparatecfg') expected_call_list = [ mock.call(filename, encoding=None), mock.call(filename, 'w+'), mock.call().write('[DEFAULT]\n'), mock.call().write('host = https://test_host\n'), mock.call().write('token = test_token\n'), mock.call().write('prod_folder = test_folder\n'), mock.call().write('\n'), ] with mock.patch('builtins.open', mock.mock_open(read_data='')) as m_open: runner = CliRunner() result = runner.invoke( configure, input=( 'https://test_host/\n' 'test_token\n' 'test_token\n' 'test_folder\n' ), ) m_open.assert_has_calls(expected_call_list, any_order=True) assert not result.exception assert result.output == expected_stdout def test_configure_extra_slash_in_folder(): expected_stdout = ( 'Databricks host (e.g. https://my-organization.cloud.databricks.com): ' 'https://test_host\n' 'Databricks API token: \n' 'Repeat for confirmation: \n' 'Databricks folder for production libraries: test_folder/\n' ) filename = join(expanduser('~'), '.apparatecfg') expected_call_list = [ mock.call(filename, encoding=None), mock.call(filename, 'w+'), mock.call().write('[DEFAULT]\n'), mock.call().write('host = https://test_host\n'), mock.call().write('token = test_token\n'), mock.call().write('prod_folder = test_folder\n'), mock.call().write('\n'), ] with mock.patch('builtins.open', mock.mock_open(read_data='')) as m_open: runner = CliRunner() result = runner.invoke( configure, input=( 'https://test_host\n' 'test_token\n' 'test_token\n' 'test_folder/\n' ), ) m_open.assert_has_calls(expected_call_list, any_order=True) assert not result.exception assert result.output == expected_stdout def test_configure_no_http_in_host(): expected_stdout = ( 'Databricks host (e.g. https://my-organization.cloud.databricks.com): ' 'test_host\n' "looks like there's an issue - make sure the host name starts " 'with http: https://test_host\n' 'Databricks API token: \n' 'Repeat for confirmation: \n' 'Databricks folder for production libraries: test_folder\n' ) filename = join(expanduser('~'), '.apparatecfg') expected_call_list = [ mock.call(filename, encoding=None), mock.call(filename, 'w+'), mock.call().write('[DEFAULT]\n'), mock.call().write('host = https://test_host\n'), mock.call().write('token = test_token\n'), mock.call().write('prod_folder = test_folder\n'), mock.call().write('\n'), ] with mock.patch('builtins.open', mock.mock_open(read_data='')) as m_open: runner = CliRunner() result = runner.invoke( configure, input=( 'test_host\n' 'https://test_host\n' 'test_token\n' 'test_token\n' 'test_folder\n' ), ) m_open.assert_has_calls(expected_call_list, any_order=True) assert not result.exception assert result.output == expected_stdout @pytest.mark.fixture('existing_config') @mock.patch('apparate.cli_commands._load_config') @mock.patch('apparate.cli_commands.update_databricks') def test_upload(update_databricks_mock, config_mock, existing_config): config_mock.return_value = existing_config runner = CliRunner() result = runner.invoke( upload, ['--path', '/path/to/egg'] ) config_mock.assert_called_once() update_databricks_mock.assert_called_with( logger, '/path/to/egg', 'test_token', 'test_folder', cleanup=False, update_jobs=False, ) assert not result.exception @pytest.mark.fixture('existing_config') @mock.patch('apparate.cli_commands._load_config') @mock.patch('apparate.cli_commands.update_databricks') def test_upload_all_options( update_databricks_mock, config_mock, existing_config ): config_mock.return_value = existing_config runner = CliRunner() result = runner.invoke( upload, [ '--path', '/path/to/egg', '--token', 'new_token', '--folder', 'new_folder' ] ) config_mock.assert_called_once() update_databricks_mock.assert_called_with( logger, '/path/to/egg', 'new_token', 'new_folder', cleanup=False, update_jobs=False, ) assert not result.exception @pytest.mark.fixture('empty_config') @mock.patch('apparate.cli_commands._load_config') def test_upload_missing_token(config_mock, empty_config): config_mock.return_value = empty_config runner = CliRunner() result = runner.invoke( upload, ['--path', '/path/to/egg', '--folder', 'test_folder'] ) assert str(result.exception) == ( 'no token found - either provide a command line argument or set up' ' a default by running `apparate configure`' ) @pytest.mark.fixture('empty_config') @mock.patch('apparate.cli_commands._load_config') def test_upload_missing_folder(config_mock, empty_config): config_mock.return_value = empty_config runner = CliRunner() result = runner.invoke( upload, ['--path', '/path/to/egg', '--token', 'test_token'] ) assert str(result.exception) == ( 'no folder found - either provide a command line argument or set up' ' a default by running `apparate configure`' ) @pytest.mark.fixture('existing_config') @mock.patch('apparate.cli_commands._load_config') @mock.patch('apparate.cli_commands.update_databricks') def test_upload_and_update_cleanup( update_databricks_mock, config_mock, existing_config ): config_mock.return_value = existing_config runner = CliRunner() result = runner.invoke( upload_and_update, ['--path', '/path/to/egg'] ) config_mock.assert_called_once() update_databricks_mock.assert_called_with( logger, '/path/to/egg', 'test_token', 'test_folder', cleanup=True, update_jobs=True, ) assert not result.exception @pytest.mark.fixture('existing_config') @mock.patch('apparate.cli_commands._load_config') @mock.patch('apparate.cli_commands.update_databricks') def test_upload_and_update_no_cleanup( update_databricks_mock, config_mock, existing_config ): config_mock.return_value = existing_config runner = CliRunner() result = runner.invoke( upload_and_update, ['--path', '/path/to/egg', '--no-cleanup'] ) config_mock.assert_called_once() update_databricks_mock.assert_called_with( logger, '/path/to/egg', 'test_token', 'test_folder', cleanup=False, update_jobs=True, ) assert not result.exception @mock.patch('apparate.cli_commands._load_config') def test_upload_and_update_missing_token(config_mock): existing_config = ConfigParser() existing_config['DEFAULT'] = {'prod_folder': 'test_folder'} config_mock.return_value = existing_config runner = CliRunner() result = runner.invoke( upload_and_update, ['--path', '/path/to/egg'] ) config_mock.assert_called_once() assert str(result.exception) == ( 'no token found - either provide a command line argument or set up' ' a default by running `apparate configure`' ) @pytest.mark.fixture('empty_config') @mock.patch('apparate.cli_commands._load_config') def test_upload_and_update_missing_folder(config_mock, empty_config): config_mock.return_value = empty_config runner = CliRunner() result = runner.invoke( upload_and_update, ['-p', '/path/to/egg', '--token', 'test_token'] ) config_mock.assert_called_once() assert str(result.exception) == ( 'no folder found - either provide a command line argument or set up' ' a default by running `apparate configure`' )
28.675
79
0.625303
ee063b9eea1e9ebcc3b2dfd3e37508b5a49daa22
10,737
lua
Lua
source_code/host_agents/windows/binaries_for_windows_host_agent/nmap_utils/nselib/dicom.lua
Doctor-Venom/Cyber-Oracle
0cc3475416ea552704f4b1086d850fa90117ccc6
[ "MIT" ]
16
2020-09-20T22:32:54.000Z
2021-04-02T17:14:25.000Z
source_code/host_agents/windows/binaries_for_windows_host_agent/nmap_utils/nselib/dicom.lua
Doctor-Venom/Cyber-Oracle
0cc3475416ea552704f4b1086d850fa90117ccc6
[ "MIT" ]
3
2020-09-30T11:41:49.000Z
2021-12-19T23:27:19.000Z
source_code/host_agents/windows/binaries_for_windows_host_agent/nmap_utils/nselib/dicom.lua
Doctor-Venom/Cyber-Oracle
0cc3475416ea552704f4b1086d850fa90117ccc6
[ "MIT" ]
1
2020-11-04T07:54:01.000Z
2020-11-04T07:54:01.000Z
--- -- DICOM library -- -- This library implements (partially) the DICOM protocol. This protocol is used to -- capture, store and distribute medical images. -- -- From Wikipedia: -- The core application of the DICOM standard is to capture, store and distribute -- medical images. The standard also provides services related to imaging such as -- managing imaging procedure worklists, printing images on film or digital media -- like DVDs, reporting procedure status like completion of an imaging acquisition, -- confirming successful archiving of images, encrypting datasets, removing patient -- identifying information from datasets, organizing layouts of images for review, -- saving image manipulations and annotations, calibrating image displays, encoding -- ECGs, encoding CAD results, encoding structured measurement data, and storing -- acquisition protocols. -- -- OPTIONS: -- *<code>called_aet</code> - If set it changes the called Application Entity Title -- used in the requests. Default: ANY-SCP -- *<code>calling_aet</code> - If set it changes the calling Application Entity Title -- used in the requests. Default: ECHOSCU -- -- @args dicom.called_aet Called Application Entity Title. Default: ANY-SCP -- @args dicom.calling_aet Calling Application Entity Title. Default: ECHOSCU -- -- @author Paulino Calderon <paulino@calderonpale.com> -- @copyright Same as Nmap--See https://nmap.org/book/man-legal.html --- local nmap = require "nmap" local stdnse = require "stdnse" local string = require "string" local table = require "table" _ENV = stdnse.module("dicom", stdnse.seeall) local MIN_SIZE_ASSOC_REQ = 68 local MAX_SIZE_PDU = 128000 local MIN_HEADER_LEN = 6 local PDU_NAMES = {} local PDU_CODES = {} PDU_CODES = { ASSOCIATE_REQUEST = 0x01, ASSOCIATE_ACCEPT = 0x02, ASSOCIATE_REJECT = 0x03, DATA = 0x04, RELEASE_REQUEST = 0x05, RELEASE_RESPONSE = 0x06, ABORT = 0x07 } for i, v in pairs(PDU_CODES) do PDU_NAMES[v] = i end --- -- start_connection(host, port) starts socket to DICOM service -- -- @param host Host object -- @param port Port table -- @return (status, socket) If status is true, socket of DICOM object is set. -- If status is false, socket is the error message. --- function start_connection(host, port) local dcm = {} local status, err dcm['socket'] = nmap.new_socket() status, err = dcm['socket']:connect(host, port, "tcp") if(status == false) then return false, "DICOM: Failed to connect to host: " .. err end return true, dcm end --- -- send(dcm, data) Sends DICOM packet over established socket -- -- @param dcm DICOM object -- @param data Data to send -- @return status True if data was sent correctly, otherwise false and error message is returned. --- function send(dcm, data) local status, err stdnse.debug2("DICOM: Sending DICOM packet (%d)", #data) if dcm['socket'] then status, err = dcm['socket']:send(data) if status == false then return false, err end else return false, "No socket found. Check your DICOM object" end return true end --- -- receive(dcm) Reads DICOM packets over an established socket -- -- @param dcm DICOM object -- @return (status, data) Returns data if status true, otherwise data is the error message. --- function receive(dcm) local status, data = dcm['socket']:receive() if status == false then return false, data end stdnse.debug1("DICOM: receive() read %d bytes", #data) return true, data end --- -- pdu_header_encode(pdu_type, length) encodes the DICOM PDU header -- -- @param pdu_type PDU type as ann unsigned integer -- @param length Length of the DICOM message -- @return (status, dcm) If status is true, the DICOM object with the header set is returned. -- If status is false, dcm is the error message. --- function pdu_header_encode(pdu_type, length) -- Some simple sanity checks, we do not check ranges to allow users to create malformed packets. if not(type(pdu_type)) == "number" then return false, "PDU Type must be an unsigned integer. Range:0-7" end if not(type(length)) == "number" then return false, "Length must be an unsigned integer." end local header = string.pack("<B >B I4", pdu_type, -- PDU Type ( 1 byte - unsigned integer in Big Endian ) 0, -- Reserved section ( 1 byte that should be set to 0x0 ) length) -- PDU Length ( 4 bytes - unsigned integer in Little Endian) if #header < MIN_HEADER_LEN then return false, "Header must be at least 6 bytes. Something went wrong." end return true, header end --- -- associate(host, port) Attempts to associate to a DICOM Service Provider by sending an A-ASSOCIATE request. -- -- @param host Host object -- @param port Port object -- @return (status, dcm) If status is true, the DICOM object is returned. -- If status is false, dcm is the error message. --- function associate(host, port, calling_aet, called_aet) local application_context = "" local presentation_context = "" local userinfo_context = "" local status, dcm = start_connection(host, port) if status == false then return false, dcm end local application_context_name = "1.2.840.10008.3.1.1.1" application_context = string.pack(">B B I2 c" .. #application_context_name, 0x10, 0x0, #application_context_name, application_context_name) local abstract_syntax_name = "1.2.840.10008.1.1" local transfer_syntax_name = "1.2.840.10008.1.2" presentation_context = string.pack(">B B I2 B B B B B B I2 c" .. #abstract_syntax_name .. "B B I2 c".. #transfer_syntax_name, 0x20, -- Presentation context type ( 1 byte ) 0x0, -- Reserved ( 1 byte ) 0x2e, -- Item Length ( 2 bytes ) 0x1, -- Presentation context id ( 1 byte ) 0x0,0x0,0x0, -- Reserved ( 3 bytes ) 0x30, -- Abstract Syntax Tree ( 1 byte ) 0x0, -- Reserved ( 1 byte ) 0x11, -- Item Length ( 2 bytes ) abstract_syntax_name, 0x40, -- Transfer Syntax ( 1 byte ) 0x0, -- Reserved ( 1 byte ) 0x11, -- Item Length ( 2 bytes ) transfer_syntax_name) local implementation_id = "1.2.276.0.7230010.3.0.3.6.2" local implementation_version = "OFFIS_DCMTK_362" userinfo_context = string.pack(">B B I2 B B I2 I4 B B I2 c" .. #implementation_id .. " B B I2 c".. #implementation_version, 0x50, -- Type 0x50 (1 byte) 0x0, -- Reserved ( 1 byte ) 0x3a, -- Length ( 2 bytes ) 0x51, -- Type 0x51 ( 1 byte) 0x0, -- Reserved ( 1 byte) 0x04, -- Length ( 2 bytes ) 0x4000, -- DATA ( 4 bytes ) 0x52, -- Type 0x52 (1 byte) 0x0, 0x1b, implementation_id, 0x55, 0x0, 0x0f, implementation_version) local called_ae_title = called_aet or stdnse.get_script_args("dicom.called_aet") or "ANY-SCP" local calling_ae_title = calling_aet or stdnse.get_script_args("dicom.calling_aet") or "ECHOSCU" if #called_ae_title > 16 or #calling_ae_title > 16 then return false, "Calling/Called Application Entity Title must be less than 16 bytes" end called_ae_title = called_ae_title .. string.rep(" ", 16 - #called_ae_title) calling_ae_title = calling_ae_title .. string.rep(" ", 16 - #calling_ae_title) -- ASSOCIATE request local assoc_request = string.pack(">I2 I2 c16 c16 c32 c" .. application_context:len() .. " c" .. presentation_context:len() .. " c" .. userinfo_context:len(), 0x1, -- Protocol version ( 2 bytes ) 0x0, -- Reserved section ( 2 bytes that should be set to 0x0 ) called_ae_title, -- Called AE title ( 16 bytes) calling_ae_title, -- Calling AE title ( 16 bytes) 0x0, -- Reserved section ( 32 bytes set to 0x0 ) application_context, presentation_context, userinfo_context) local status, header = pdu_header_encode(PDU_CODES["ASSOCIATE_REQUEST"], #assoc_request) -- Something might be wrong with our header if status == false then return false, header end assoc_request = header .. assoc_request stdnse.debug2("PDU len minus header:%d", #assoc_request-#header) if #assoc_request < MIN_SIZE_ASSOC_REQ then return false, string.format("ASSOCIATE request PDU must be at least %d bytes and we tried to send %d.", MIN_SIZE_ASSOC_REQ, #assoc_request) end local status, err = send(dcm, assoc_request) if status == false then return false, string.format("Couldn't send ASSOCIATE request:%s", err) end status, err = receive(dcm) if status == false then return false, string.format("Couldn't read ASSOCIATE response:%s", err) end local resp_type, _, resp_length = string.unpack(">B B I4", err) stdnse.debug1("PDU Type:%d Length:%d", resp_type, resp_length) if resp_type == PDU_CODES["ASSOCIATE_ACCEPT"] then stdnse.debug1("ASSOCIATE ACCEPT message found!") return true, dcm elseif resp_type == PDU_CODES["ASSOCIATE_REJECT"] then stdnse.debug1("ASSOCIATE REJECT message found!") return false, "ASSOCIATE REJECT received" else return false, "Received unknown response" end end function send_pdata(dicom, data) local status, header = pdu_header_encode(PDU_CODES["DATA"], #data) if status == false then return false, header end local err status, err = send(dicom, header .. data) if status == false then return false, err end end return _ENV
39.32967
160
0.602869
72f08ebc384d80a308e04377ea4b89b31a0b06f7
695
swift
Swift
SymbolExtractorAndRenamer/swift/test/Obfuscation/SymbolExtractor/SymbolExtractor.swift
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
427
2018-05-29T14:21:02.000Z
2022-03-16T03:17:54.000Z
SymbolExtractorAndRenamer/swift/test/Obfuscation/SymbolExtractor/SymbolExtractor.swift
PolideaPlayground/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
25
2018-07-23T08:34:15.000Z
2021-11-05T07:13:36.000Z
SymbolExtractorAndRenamer/swift/test/Obfuscation/SymbolExtractor/SymbolExtractor.swift
PolideaPlayground/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
52
2018-07-19T19:57:32.000Z
2022-03-11T16:05:38.000Z
//RUN: echo "{\"project\": {\"rootPath\": \"TestRootPath\", \"projectFilePath\": \"testProjectFilePath\"}, \"module\": {\"name\": \"TestModuleName\", \"triple\": \"x86_64-apple-macosx10.13\"}, \"sdk\": {\"name\": \"%target-sdk-name\", \"path\": \"%sdk\"}, \"sourceFiles\": [\"%S/Inputs\/ViewController.swift\", \"%S/Inputs\/AppDelegate.swift\"], \"layoutFiles\": [], \"explicitlyLinkedFrameworks\": [], \"implicitlyLinkedFrameworks\": [], \"frameworkSearchPaths\": [], \"headerSearchPaths\": [], \"bridgingHeader\": \"\", \"configurationFile\": \"\"}" > %T/files.json //RUN: obfuscator-symbol-extractor -filesjson %T/files.json -symbolsjson %t //RUN: diff -w %S/Inputs/expectedSymbols.json %t
115.833333
567
0.634532
60539830ef602723975280d772accf2a36022c98
1,024
html
HTML
manuscript/page-406/body.html
marvindanig/nicholas-nickleby
e522d21945b8128d468c54790ceb7937d51ad0b2
[ "BlueOak-1.0.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
manuscript/page-406/body.html
marvindanig/nicholas-nickleby
e522d21945b8128d468c54790ceb7937d51ad0b2
[ "BlueOak-1.0.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
manuscript/page-406/body.html
marvindanig/nicholas-nickleby
e522d21945b8128d468c54790ceb7937d51ad0b2
[ "BlueOak-1.0.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
<div class="leaf flex"><div class="inner justify"><p class="no-indent ">family hated him, and Smike paid for both. Nicholas saw it, and ground his teeth at every repetition of the savage and cowardly attack.</p><p>He had arranged a few regular lessons for the boys; and one night, as he paced up and down the dismal schoolroom, his swollen heart almost bursting to think that his protection and countenance should have increased the misery of the wretched being whose peculiar destitution had awakened his pity, he paused mechanically in a dark corner where sat the object of his thoughts.</p><p class=" stretch-last-line ">The poor soul was poring hard over a tattered book, with the traces of recent tears still upon his face; vainly endeavouring to master some task which a child of nine years old, possessed of ordinary powers, could have conquered with ease, but which, to the addled brain of the crushed boy of nineteen, was a sealed and hopeless mystery. Yet there he sat, patiently conning the page</p></div> </div>
1,024
1,024
0.783203
86ab6b1afed29c9ac086cd7888945c69d05a41fa
1,871
go
Go
common_test.go
photogabble/colour
a10e3c750d1b7156dd8a90e61a40184ba90acba3
[ "MIT" ]
null
null
null
common_test.go
photogabble/colour
a10e3c750d1b7156dd8a90e61a40184ba90acba3
[ "MIT" ]
null
null
null
common_test.go
photogabble/colour
a10e3c750d1b7156dd8a90e61a40184ba90acba3
[ "MIT" ]
null
null
null
package colour_test import ( "colour" "colour/test" "image/color" "testing" ) func Test_NumberToHex_should_return_uint_as_string(t *testing.T) { helpers.AssertStringEquals("00", colour.NumberToHexString(0), t) helpers.AssertStringEquals("ff", colour.NumberToHexString(255), t) } func Test_ReduceHexStringValue_should_return_shortened_hex_string(t *testing.T) { helpers.AssertStringEquals("f86", colour.ReduceHexStringValue("ff8866"), t) helpers.AssertStringEquals("fff", colour.ReduceHexStringValue("fff"), t) } func Test_ConvertToHex_should_return_shortened_hex_string(t *testing.T) { helpers.AssertStringEquals("f00", colour.ConvertToHex(255, 0, 0), t) helpers.AssertStringEquals("0f0", colour.ConvertToHex(0, 255, 0), t) helpers.AssertStringEquals("00f", colour.ConvertToHex(0, 0, 255), t) helpers.AssertStringEquals("fff", colour.ConvertToHex(255, 255, 255), t) helpers.AssertStringEquals("000", colour.ConvertToHex(0, 0, 0), t) } func Test_ConvertRGBToHex_should_return_shortened_hex_string(t *testing.T) { helpers.AssertStringEquals("f00", colour.ConvertRGBToHex(color.RGBA{R: 255}), t) helpers.AssertStringEquals("0f0", colour.ConvertRGBToHex(color.RGBA{G: 255}), t) helpers.AssertStringEquals("00f", colour.ConvertRGBToHex(color.RGBA{B: 255}), t) } // Come back to this one... //func Test_HSLToRGB_should_return_colour_type_from_hsl_input(t *testing.T) { // helpers.AssertColourEquals(color.RGBA{R: 255, G: 255, B: 255, A: 255}, colour.HSLToRGB(colour.HslColour{Lightness: 1.0, Hue: 0.0, Saturation: 1.0}, func(R, G, B uint8) color.RGBA { // return color.RGBA{R: R, G: G, B: B, A: 255} // }), t) // // helpers.AssertColourEquals(color.RGBA{R: 78, G: 78, B: 78, A: 255}, colour.HSLToRGB(colour.HslColour{Lightness: 0.3, Hue: 0, Saturation: 1.0}, func(R, G, B uint8) color.RGBA { // return color.RGBA{R: R, G: G, B: B, A: 255} // }), t) //}
42.522727
183
0.740246
8b0141ea302609d1fbab6a8b11aae4a4efc98602
1,086
dart
Dart
GuruCool_Mobile/quiz/Student/quizWidgets/bullets.dart
mandanshubham/GuruCool_UserInterface
aaf28d6d60a4e288ba50f0821be125d520ad5a38
[ "MIT" ]
null
null
null
GuruCool_Mobile/quiz/Student/quizWidgets/bullets.dart
mandanshubham/GuruCool_UserInterface
aaf28d6d60a4e288ba50f0821be125d520ad5a38
[ "MIT" ]
null
null
null
GuruCool_Mobile/quiz/Student/quizWidgets/bullets.dart
mandanshubham/GuruCool_UserInterface
aaf28d6d60a4e288ba50f0821be125d520ad5a38
[ "MIT" ]
9
2020-12-05T12:35:32.000Z
2021-01-19T12:42:48.000Z
import 'package:flutter/material.dart'; import '../SizeConfig.dart'; import '../quizConstants.dart'; class Bullets extends StatelessWidget { final String text; Bullets({@required this.text}); @override Widget build(BuildContext context) { SizeConfig().init(context); return Container( width: SizeConfig.screenWidth * 0.3056, alignment: Alignment.center, margin: EdgeInsets.symmetric( vertical: SizeConfig.screenHeight * 0.01, ), child: Row( children: [ Icon( Icons.fiber_manual_record, color: colorBlueText, size: SizeConfig.screenWidth * 0.04167, ), SizedBox(width: SizeConfig.screenWidth * 0.0278), Container( child: Text( text, style: TextStyle( fontSize: SizeConfig.screenWidth * 0.0389, fontWeight: FontWeight.w400, color: colorBlueText, ), ), ) ], ), ); } }
27.15
60
0.532228
a62fde8c8a62c31daa1185786947acf0e6063095
8,181
dart
Dart
lib/src/neuralnetwork.dart
Husssam12/neuraldart
8db01b9229d082ab3a6d6b91bb97c8de760a1c6e
[ "MIT" ]
null
null
null
lib/src/neuralnetwork.dart
Husssam12/neuraldart
8db01b9229d082ab3a6d6b91bb97c8de760a1c6e
[ "MIT" ]
null
null
null
lib/src/neuralnetwork.dart
Husssam12/neuraldart
8db01b9229d082ab3a6d6b91bb97c8de760a1c6e
[ "MIT" ]
null
null
null
import 'dataset.dart'; import 'layer.dart'; import 'neuron.dart'; import 'utils.dart' as utils; enum NeuralNetworkType { elman, normal, } class NeuralNetwork { late final NeuralNetworkType _networkType; List<Layer> layers = []; late int size; NeuralNetwork(int size) { _networkType = NeuralNetworkType.normal; this.size = size; for (int i = 0; i < size; i++) { layers.add(Layer([])); } } NeuralNetwork.elman() { _networkType = NeuralNetworkType.elman; } int getSize() { return this.size; } } void forward(NeuralNetwork nn, List<double> inputs) { // Bring the inputs into the input layer nn.layers[0] = Layer(inputs); // Forward propagation for (int i = 1; i < nn.layers.length; i++) { // Starts from 1st hidden layer for (int j = 0; j < nn.layers[i].neurons.length; j++) { double sum = 0; for (int k = 0; k < nn.layers[i - 1].neurons.length; k++) { sum += (nn.layers[i - 1].neurons[k].value * nn.layers[i].neurons[j].weights[k]); } sum -= (nn.layers[i].neurons[j].bias * nn.layers[i].neurons[j].weights.last); nn.layers[i].neurons[j].value = utils.sigmoid(sum); } } } void backward(NeuralNetwork nn, double learning_rate, Pair data) { int number_layers = nn.layers.length; int output_layer_index = number_layers - 1; // Update the output layers for (int i = 0; i < nn.layers[output_layer_index].neurons.length; i++) { // For each output final double output = nn.layers[output_layer_index].neurons[i].value; final double target = data.output_data[i]; final double outputError = target - output; final double delta = (output * (1 - output)) * outputError; nn.layers[output_layer_index].neurons[i].gradient = delta; for (int j = 0; j < nn.layers[output_layer_index].neurons[i].weights.length; j++) { late final double previous_output; if (j < nn.layers[output_layer_index].neurons[i].weights.length - 1) { previous_output = nn.layers[output_layer_index - 1].neurons[j].value; } else { previous_output = nn.layers[output_layer_index].neurons[i].bias; } final double error = delta * previous_output; nn.layers[output_layer_index].neurons[i].weights_old[j] = nn.layers[output_layer_index].neurons[i].weights[j] + learning_rate * error; } } // Update all the subsequent hidden layers for (int i = output_layer_index - 1; i > 0; i--) { // Backward for (int j = 0; j < nn.layers[i].neurons.length; j++) { // For all neurons in that layers double output = nn.layers[i].neurons[j].value; double gradient_sum = sumGradient(nn, j, i + 1); double delta = (gradient_sum) * (output * (1 - output)); nn.layers[i].neurons[j].gradient = delta; for (int k = 0; k < nn.layers[i].neurons[j].weights.length - 1; k++) { // And for all their weights double previous_output = nn.layers[i - 1].neurons[k].value; double error = delta * previous_output; nn.layers[i].neurons[j].weights_old[k] = nn.layers[i].neurons[j].weights[k] + learning_rate * error; } } } // Update all the weights for (int i = 0; i < nn.layers.length; i++) { for (int j = 0; j < nn.layers[i].neurons.length; j++) { nn.layers[i].neurons[j].updateWeights(); } } } // This function sums up all the gradient connecting a given neuron in a given layer double sumGradient(NeuralNetwork nn, int n_index, int l_index) { double gradient_sum = 0; Layer current_layer = nn.layers[l_index]; for (int i = 0; i < current_layer.neurons.length; i++) { Neuron current_neuron = current_layer.neurons[i]; gradient_sum += current_neuron.weights[n_index] * current_neuron.gradient; } return gradient_sum; } // This function is used to train void train(NeuralNetwork nn, DataSet dt, int iteration, double learning_rate) { for (int i = 0; i < iteration; i++) { for (int j = 0; j < dt.getLength(); j++) { forward(nn, dt.pairs[j].input_data); backward(nn, learning_rate, dt.pairs[j]); } } } // import 'dataset.dart'; // import 'layer.dart'; // import 'neuron.dart'; // import 'utils.dart' as utils; // // class NeuralNetwork { // List<Layer> layers = []; // late int size; // // NeuralNetwork(int size) { // this.size = size; // for (int i = 0; i < size; i++) { // layers.add(Layer([])); // } // } // // int getSize() { // return this.size; // } // } // // void forward(NeuralNetwork nn, List<double> inputs) { // // Bring the inputs into the input layer // nn.layers[0] = Layer(inputs); // // Forward propagation // for (int i = 1; i < nn.layers.length; i++) { // // Starts from 1st hidden layer // for (int j = 0; j < nn.layers[i].neurons.length; j++) { // double sum = 0; // for (int k = 0; k < nn.layers[i - 1].neurons.length; k++) { // sum += (nn.layers[i - 1].neurons[k].value * // nn.layers[i].neurons[j].weights[k]) - // nn.layers[i].neurons[j].bias; // } // nn.layers[i].neurons[j].value = utils.sigmoid(sum); // } // } // } // // void backward(NeuralNetwork nn, double learning_rate, Pair datas) { // int number_layers = nn.layers.length; // int output_layer_index = number_layers - 1; // // // Update the output layers // for (int i = 0; i < nn.layers[output_layer_index].neurons.length; i++) { // // For each output // double output = nn.layers[output_layer_index].neurons[i].value; // double target = datas.output_data[i]; // double derivative = output - target; // double delta = derivative * (output * (1 - output)); // nn.layers[output_layer_index].neurons[i].gradient = delta; // // for (int j = 0; // j < nn.layers[output_layer_index].neurons[i].weights.length; // j++) { // // and for each of their weights // double previous_output = // nn.layers[output_layer_index - 1].neurons[j].value; // double error = delta * previous_output; // nn.layers[output_layer_index].neurons[i].weights_old[j] = // nn.layers[output_layer_index].neurons[i].weights[j] - // learning_rate * error; // } // } // // // Update all the subsequent hidden layers // for (int i = output_layer_index - 1; i > 0; i--) { // // Backward // for (int j = 0; j < nn.layers[i].neurons.length; j++) { // // For all neurons in that layers // double output = nn.layers[i].neurons[j].value; // double gradient_sum = sumGradient(nn, j, i + 1); // double delta = (gradient_sum) * (output * (1 - output)); // nn.layers[i].neurons[j].gradient = delta; // // for (int k = 0; k < nn.layers[i].neurons[j].weights.length; k++) { // // And for all their weights // double previous_output = nn.layers[i - 1].neurons[k].value; // double error = delta * previous_output; // nn.layers[i].neurons[j].weights_old[k] = // nn.layers[i].neurons[j].weights[k] - learning_rate * error; // } // } // } // // // Update all the weights // for (int i = 0; i < nn.layers.length; i++) { // for (int j = 0; j < nn.layers[i].neurons.length; j++) { // nn.layers[i].neurons[j].updateWeights(); // } // } // } // // // This function sums up all the gradient connecting a given neuron in a given layer // double sumGradient(NeuralNetwork nn, int n_index, int l_index) { // double gradient_sum = 0; // Layer current_layer = nn.layers[l_index]; // for (int i = 0; i < current_layer.neurons.length; i++) { // Neuron current_neuron = current_layer.neurons[i]; // gradient_sum += current_neuron.weights[n_index] * current_neuron.gradient; // } // return gradient_sum; // } // // // This function is used to train // void train(NeuralNetwork nn, Dataset dt, int iteration, double learning_rate) { // for (int i = 0; i < iteration; i++) { // for (int j = 0; j < dt.getLength(); j++) { // forward(nn, dt.pairs[j].input_data); // backward(nn, learning_rate, dt.pairs[j]); // } // } // } //
33.666667
87
0.602127
cebf455e1faf2a9cd447f860668b6e460a2f1538
2,478
lua
Lua
containertool/nodes/common_defaults.lua
S-S-X/metatool
65eb90440fa9ce4714266f7b5204c32681eeb5d7
[ "MIT" ]
2
2020-06-17T19:07:01.000Z
2022-01-11T22:32:39.000Z
containertool/nodes/common_defaults.lua
S-S-X/metatool
65eb90440fa9ce4714266f7b5204c32681eeb5d7
[ "MIT" ]
82
2020-05-20T06:09:43.000Z
2022-02-17T15:17:51.000Z
containertool/nodes/common_defaults.lua
S-S-X/metatool
65eb90440fa9ce4714266f7b5204c32681eeb5d7
[ "MIT" ]
null
null
null
-- -- Register rest of compatible nodes for Container tool -- local ns = metatool.ns('containertool') -- Node feature checker local is_tubedevice = ns.is_tubedevice -- Base metadata reader local get_common_attributes = ns.get_common_attributes -- Special metadata setters local set_key_lock_secret = ns.set_key_lock_secret local set_digiline_meta = ns.set_digiline_meta local set_splitstacks = ns.set_splitstacks -- Blacklist some nodes local tubedevice_blacklist = { "^technic:.*_battery_box", "^technic:.*tool_workshop", "^pipeworks:dispenser", "^pipeworks:nodebreaker", "^pipeworks:deployer", "^digtron:", "^jumpdrive:", "^vacuum:", } local function blacklisted(name) for _,value in ipairs(tubedevice_blacklist) do if name:find(value) then return true end end end -- Collect nodes and on_receive_fields callback functions local nodes = {} local on_receive_fields = {} for nodename, nodedef in pairs(minetest.registered_nodes) do print(nodename) if is_tubedevice(nodename) and not blacklisted(nodename) then -- Match found, add to registration list table.insert(nodes, nodename) if nodedef.on_receive_fields then on_receive_fields[nodename] = nodedef.on_receive_fields end end end local definition = { name = 'common_container', nodes = nodes, group = 'container', protection_bypass_read = "interact", } function definition:before_write(pos, player) -- Stay safe and check both owner and protection for unknown nodes local meta = minetest.get_meta(pos) local owner = meta:get("owner") local owner_check = owner == nil or owner == player:get_player_name() if not owner_check then minetest.record_protection_violation(pos, player:get_player_name()) end return owner_check and metatool.before_write(self, pos, player) end function definition:copy(node, pos, player) -- Read common data like owner, splitstacks, channel etc. return get_common_attributes(minetest.get_meta(pos), node, pos, player) end function definition:paste(node, pos, player, data) local meta = minetest.get_meta(pos) set_key_lock_secret(meta, data, node) set_splitstacks(meta, data, node, pos) set_digiline_meta(meta, {channel = data.channel}, node) -- Yeah, sorry... everyone just keeps their internal stuff "protected" if on_receive_fields[node.name] then if not pcall(function()on_receive_fields[node.name](pos, "", {}, player)end) then pcall(function()on_receive_fields[node.name](pos, "", {quit=1}, player)end) end end end return definition
29.855422
83
0.766344
3581656993e1ae3f1c826fc90a0ab9ed27c58ce3
6,453
swift
Swift
test/Driver/bridging-pch.swift
calebkleveter/swift
7b0d10e2c762c5e3d4fb1ca1bef969db8a1cc536
[ "Apache-2.0" ]
2
2019-05-13T11:50:41.000Z
2019-05-13T11:50:42.000Z
test/Driver/bridging-pch.swift
calebkleveter/swift
7b0d10e2c762c5e3d4fb1ca1bef969db8a1cc536
[ "Apache-2.0" ]
null
null
null
test/Driver/bridging-pch.swift
calebkleveter/swift
7b0d10e2c762c5e3d4fb1ca1bef969db8a1cc536
[ "Apache-2.0" ]
null
null
null
// RUN: %empty-directory(%t) // RUN: %target-build-swift -typecheck -driver-print-actions -import-objc-header %S/Inputs/bridging-header.h %s 2>&1 | %FileCheck %s -check-prefix=YESPCHACT // YESPCHACT: 0: input, "{{.*}}Inputs/bridging-header.h", objc-header // YESPCHACT: 1: generate-pch, {0}, pch // YESPCHACT: 2: input, "{{.*}}bridging-pch.swift", swift // YESPCHACT: 3: compile, {2, 1}, none // RUN: %target-build-swift -typecheck -disable-bridging-pch -driver-print-actions -import-objc-header %S/Inputs/bridging-header.h %s 2>&1 | %FileCheck %s -check-prefix=NOPCHACT // NOPCHACT: 0: input, "{{.*}}bridging-pch.swift", swift // NOPCHACT: 1: compile, {0}, none // RUN: %target-build-swift -typecheck -driver-print-jobs -import-objc-header %S/Inputs/bridging-header.h %s 2>&1 | %FileCheck %s -check-prefix=YESPCHJOB // YESPCHJOB: {{.*}}swift{{c?(\.EXE)?"?}} -frontend {{.*}} -emit-pch -o {{.*}}bridging-header-{{.*}}.pch // YESPCHJOB: {{.*}}swift{{c?(\.EXE)?"?}} -frontend {{.*}} -import-objc-header {{.*}}bridging-header-{{.*}}.pch // RUN: %target-build-swift -typecheck -disable-bridging-pch -driver-print-jobs -import-objc-header %S/Inputs/bridging-header.h %s 2>&1 | %FileCheck %s -check-prefix=NOPCHJOB // NOPCHJOB: {{.*}}swift{{c?(\.EXE)?"?}} -frontend {{.*}} -import-objc-header {{.*}}Inputs/bridging-header.h // RUN: %target-build-swift -typecheck -driver-print-jobs -index-store-path %t/idx -import-objc-header %S/Inputs/bridging-header.h %s 2>&1 | %FileCheck %s -check-prefix=INDEXSTORE // INDEXSTORE: {{.*}}swift{{c?(\.EXE)?"?}} -frontend {{.*}} -index-store-path {{.*}}/idx{{"?}} -emit-pch -o {{.*}}bridging-header-{{.*}}.pch // RUN: echo "{\"\": {\"swift-dependencies\": \"%/t/master.swiftdeps\"}, \"%/s\": {\"swift-dependencies\": \"%/t/bridging-header.swiftdeps\"}}" > %t.json // RUN: %target-build-swift -typecheck -incremental -enable-bridging-pch -output-file-map %t.json -import-objc-header %S/Inputs/bridging-header.h %s // RUN: mkdir %t/tmp // RUN: env TMP="%t/tmp/" TMPDIR="%t/tmp/" not %target-build-swift -typecheck -import-objc-header %S/../Inputs/empty.h -driver-use-frontend-path "%{python};%S/Inputs/crash-after-generating-pch.py" -v %s // RUN: ls %/t/tmp/*.pch // Test persistent PCH // RUN: %target-build-swift -typecheck -driver-print-actions -import-objc-header %S/Inputs/bridging-header.h -pch-output-dir %t/pch %s 2>&1 | %FileCheck %s -check-prefix=PERSISTENT-YESPCHACT // PERSISTENT-YESPCHACT: 0: input, "{{.*}}Inputs/bridging-header.h", objc-header // PERSISTENT-YESPCHACT: 1: generate-pch, {0}, none // PERSISTENT-YESPCHACT: 2: input, "{{.*}}bridging-pch.swift", swift // PERSISTENT-YESPCHACT: 3: compile, {2, 1}, none // RUN: %target-build-swift -c -driver-print-actions -embed-bitcode -import-objc-header %S/Inputs/bridging-header.h -pch-output-dir %t/pch %s 2>&1 | %FileCheck %s -check-prefix=PERSISTENT-YESPCHACTBC // PERSISTENT-YESPCHACTBC: 0: input, "{{.*}}Inputs/bridging-header.h", objc-header // PERSISTENT-YESPCHACTBC: 1: generate-pch, {0}, none // PERSISTENT-YESPCHACTBC: 2: input, "{{.*}}bridging-pch.swift", swift // PERSISTENT-YESPCHACTBC: 3: compile, {2, 1}, llvm-bc // RUN: %target-build-swift -typecheck -disable-bridging-pch -driver-print-actions -import-objc-header %S/Inputs/bridging-header.h -pch-output-dir %t/pch %s 2>&1 | %FileCheck %s -check-prefix=NOPCHACT // RUN: %target-build-swift -typecheck -driver-print-jobs -import-objc-header %S/Inputs/bridging-header.h -pch-output-dir %t/pch -disable-bridging-pch %s 2>&1 | %FileCheck %s -check-prefix=PERSISTENT-DISABLED-YESPCHJOB // RUN: %target-build-swift -typecheck -driver-print-jobs -import-objc-header %S/Inputs/bridging-header.h -pch-output-dir %t/pch -whole-module-optimization -disable-bridging-pch %s 2>&1 | %FileCheck %s -check-prefix=PERSISTENT-DISABLED-YESPCHJOB // PERSISTENT-DISABLED-YESPCHJOB-NOT: -pch-output-dir // RUN: %target-build-swift -typecheck -driver-print-jobs -import-objc-header %S/Inputs/bridging-header.h -pch-output-dir %t/pch %s 2>&1 | %FileCheck %s -check-prefix=PERSISTENT-YESPCHJOB // PERSISTENT-YESPCHJOB: {{.*}}swift{{c?(\.EXE)?"?}} -frontend {{.*}} -emit-pch -pch-output-dir {{.*}}/pch // PERSISTENT-YESPCHJOB: {{.*}}swift{{c?(\.EXE)?"?}} -frontend {{.*}} -import-objc-header {{.*}}bridging-header.h -pch-output-dir {{.*}}/pch -pch-disable-validation // RUN: %target-build-swift -typecheck -driver-print-jobs -import-objc-header %S/Inputs/bridging-header.h -pch-output-dir %t/pch -serialize-diagnostics %s 2>&1 | %FileCheck %s -check-prefix=PERSISTENT-YESPCHJOB-DIAG1 // PERSISTENT-YESPCHJOB-DIAG1: {{.*}}swift{{c?(\.EXE)?"?}} -frontend {{.*}} -serialize-diagnostics-path {{.*}}bridging-header-{{.*}}.dia {{.*}} -emit-pch -pch-output-dir {{.*}}/pch // RUN: %target-build-swift -typecheck -driver-print-jobs -import-objc-header %S/Inputs/bridging-header.h -pch-output-dir %t/pch-out-dir -serialize-diagnostics %s -emit-module -emit-module-path /module-path-dir 2>&1 | %FileCheck %s -check-prefix=PERSISTENT-YESPCHJOB-DIAG2 // PERSISTENT-YESPCHJOB-DIAG2: {{.*}}swift{{c?(\.EXE)?"?}} -frontend {{.*}} -serialize-diagnostics-path {{.*}}/pch-out-dir/bridging-header-{{.*}}.dia {{.*}} -emit-pch -pch-output-dir {{.*}}/pch-out-dir // RUN: %target-build-swift -typecheck -import-objc-header %S/Inputs/bridging-header.h -pch-output-dir %t/pch -parseable-output -driver-skip-execution %s 2>&1 | %FileCheck %s -check-prefix=PERSISTENT-OUTPUT // PERSISTENT-OUTPUT-NOT: "outputs": [ // RUN: %target-build-swift -typecheck -driver-print-jobs -import-objc-header %S/Inputs/bridging-header.h -pch-output-dir %t/pch -whole-module-optimization %s 2>&1 | %FileCheck %s -check-prefix=PERSISTENT-WMO-YESPCHJOB --implicit-check-not pch-disable-validation // PERSISTENT-WMO-YESPCHJOB: {{.*}}swift{{c?(\.EXE)?"?}} -frontend {{.*}} -import-objc-header {{.*}}bridging-header.h -pch-output-dir {{.*}}/pch // RUN: %target-build-swift -typecheck -disable-bridging-pch -driver-print-jobs -import-objc-header %/S/Inputs/bridging-header.h -pch-output-dir %t/pch %/s 2>&1 | %FileCheck %s -check-prefix=NOPCHJOB // RUN: %target-build-swift -typecheck -incremental -enable-bridging-pch -output-file-map %t.json -import-objc-header %S/Inputs/bridging-header.h -pch-output-dir %t/pch %s // RUN: %target-build-swift -### -typecheck -O -import-objc-header %S/Inputs/bridging-header.h %s 2>&1 | %FileCheck %s -check-prefix=OPTPCH // OPTPCH: swift{{c?(\.EXE)?"?}} -frontend // OPTPCH-SAME: -O{{ }} // OPTPCH-SAME: -emit-pch
88.39726
272
0.687432
8773392cec0dc5aab5fa2b42a1255b0bf6648b96
3,475
html
HTML
modules/core/client/views/header.html
dcdrawk/paperCMS
883d97a55dc28ef89b083db6768f724461c01921
[ "MIT" ]
null
null
null
modules/core/client/views/header.html
dcdrawk/paperCMS
883d97a55dc28ef89b083db6768f724461c01921
[ "MIT" ]
null
null
null
modules/core/client/views/header.html
dcdrawk/paperCMS
883d97a55dc28ef89b083db6768f724461c01921
[ "MIT" ]
null
null
null
<section class="portfolio-header container" layout="row"> <div class="devin-pic"> <img alt="Devin Cook" src="/modules/core/client/img/devin.jpg" /> </div> <div class="header-text"> <h1 class="page-title md-display-1">Devin Cook</h1> <span class="page-title md-subhead">Front-End Developer / Interaction Designer {{$root.activeTab}}</span> </div> </section> <ddn-sticky-wrapper> <section class="navigation-bar" ng-controller="HeaderController"> <!-- {{currentState}} --> <div class="container"> <div class="user-menu" ng-show="authentication.user"> <!-- <span class="profile-pic"> <img ng-src="{{authentication.user.profileImageURL}}" /> </span> <span class="user-menu-text"> <span ng-bind="authentication.user.username"></span> </span> --> <md-menu md-position-mode="target-right target" md-offset="-216 64"> <md-button class="no-margin" md-menu-origin aria-label="open user menu" ng-click="openMenu($mdOpenMenu, $event)"> <!-- <md-icon class="material-icons">more_vert</md-icon> --> <span class="profile-pic"> <img ng-src="{{authentication.user.profileImageURL}}"/> </span> <span class="user-menu-text"> <span ng-bind="authentication.user.username"></span> </span> </md-button> <md-menu-content width="4" class="user-menu-dropdown"> <md-menu-item> <md-button ng-click="go('settings.profile')"> <md-icon class="material_icons" md-menu-align-target>person</md-icon> Edit Profile </md-button> </md-menu-item> <md-menu-item> <md-button ng-click="go('settings.picture')"> <md-icon class="material_icons" md-menu-align-target>photo</md-icon> Change Profile Picture </md-button> </md-menu-item> <md-menu-item> <md-button ng-click="go('settings.password')"> <md-icon class="material_icons" md-menu-align-target>security</md-icon> Change Password </md-button> </md-menu-item> <md-menu-item> <md-button ng-click="go('settings.accounts')"> <md-icon class="material_icons" md-menu-align-target>share</md-icon> Manage Social Accounts </md-button> </md-menu-item> <md-menu-divider></md-menu-divider> <md-menu-item> <md-button href="/api/auth/signout" target="_self"> <md-icon class="material_icons" md-menu-align-target>exit_to_app</md-icon> Sign Out </md-button> </md-menu-item> </md-menu-content> </md-menu> </div> <md-tabs md-stretch-tabs> <md-tab md-active="item.title === $root.activeTab" ng-repeat="item in menu.items | orderBy: 'position'" ng-if="item.shouldRender(authentication.user);">{{item.title}}</md-tab> <!--<md-tab md-active="item.title === $root.activeTab" ng-repeat="item in menu.items | orderBy: 'position'" ng-if="item.shouldRender(authentication.user);" ui-sref="{{item.state}}">{{item.title}}</md-tab>--> <!--<md-tab ui-sref="authentication.signup" ng-if="!authentication.user">Sign Up</md-tab> <md-tab ui-sref="authentication.signin" ng-if="!authentication.user">Sign In</md-tab>--> </md-tabs> </div> </section> <!-- <div>Header</div> --> </ddn-sticky-wrapper>
42.901235
213
0.584173
42b29aedb9249626159bc62e554a0f08f185130e
742
sql
SQL
pgwatch2/metrics/reco_superusers/9.1/metric_master.sql
pashagolub/pgwatch2
a0c54624cb0b9557bf253d129f1ab958675b501f
[ "BSD-3-Clause" ]
null
null
null
pgwatch2/metrics/reco_superusers/9.1/metric_master.sql
pashagolub/pgwatch2
a0c54624cb0b9557bf253d129f1ab958675b501f
[ "BSD-3-Clause" ]
1
2021-09-17T12:02:30.000Z
2021-09-17T12:16:35.000Z
pgwatch2/metrics/reco_superusers/9.1/metric_master.sql
pashagolub/pgwatch2
a0c54624cb0b9557bf253d129f1ab958675b501f
[ "BSD-3-Clause" ]
null
null
null
/* reco_* metrics have special handling - all results are stored actually under one 'recommendations' metric and following text columns are expected: reco_topic, object_name, recommendation, extra_info. */ with q_su as ( select count(*) from pg_roles where rolcanlogin and rolsuper ), q_total as ( select count(*) from pg_roles where rolcanlogin ) select /* pgwatch2_generated */ (extract(epoch from now()) * 1e9)::int8 as epoch_ns, 'superuser_count'::text as tag_reco_topic, '-'::text as tag_object_name, 'too many superusers detected - review recommended'::text as recommendation, format('%s active superusers, %s total active users', q_su.count, q_total.count) as extra_info from q_su, q_total where q_su.count >= 10 ;
37.1
113
0.749326
fbbf15a76beafac80e44ff9895d5777405373af2
4,665
java
Java
fairy/src/main/java/com/example/fairy/utils/property/PropertyUtils.java
snpmyn/MyApplication
df679bbfb2503e4b1a4a9a90105097ffef45bb13
[ "Apache-2.0" ]
null
null
null
fairy/src/main/java/com/example/fairy/utils/property/PropertyUtils.java
snpmyn/MyApplication
df679bbfb2503e4b1a4a9a90105097ffef45bb13
[ "Apache-2.0" ]
null
null
null
fairy/src/main/java/com/example/fairy/utils/property/PropertyUtils.java
snpmyn/MyApplication
df679bbfb2503e4b1a4a9a90105097ffef45bb13
[ "Apache-2.0" ]
null
null
null
package com.example.fairy.utils.property; import android.content.Context; import android.text.TextUtils; import com.example.fairy.utils.log.LogUtils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; /** * Created on 2020-09-11 * * @author zsp * @desc 属性工具类 */ public class PropertyUtils { private String line = ""; private final List<String> keysList = new ArrayList<>(); private final Map<String, String> keyValueMap = new LinkedHashMap<>(); private List<String> getKeysList() { return keysList; } private Map<String, String> getKeyValueMap() { return keyValueMap; } /** * 获取属性键或值集合 * * @param context 上下文 * @param fileName 文件名 * @param flag 标示(0 键、1 值) * @return 属性键或值集合 */ public List<String> getPropertyKeyOrValueList(Context context, String fileName, int flag) { List<String> stringList = new ArrayList<>(); if (TextUtils.isEmpty(fileName)) { return stringList; } loadProperty(context, fileName); if (flag == 0) { return getKeysList(); } else if (flag == 1) { Map<String, String> keyValueMap = getKeyValueMap(); for (String key : getKeysList()) { String value = keyValueMap.get(key); if (value != null) { stringList.add(value); } } } return stringList; } /** * 加载属性 * * @param context 上下文 * @param fileName 文件名 */ private void loadProperty(Context context, String fileName) { InputStream inputStream = null; try { inputStream = context.getAssets().open(fileName); load(inputStream); inputStream.close(); } catch (Exception e) { LogUtils.exception(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { LogUtils.exception(e); } } } } /** * 加载 * * @param inputStream 输入流 * @throws IOException 异常 */ private synchronized void load(InputStream inputStream) throws IOException { List<String> linesList = getLinesList(inputStream); for (String line : linesList) { // 处理注释外键值对 if (!line.trim().startsWith("#") && line.contains("=")) { String k = line.substring(0, line.indexOf("=")).trim(); String v = line.substring(line.indexOf("=") + 1).trim(); keysList.add(k); keyValueMap.put(k, v); } } } /** * 获取行集 * * @param inputStream 输入流 * @return 行集 * @throws IOException IO 异常 */ private List<String> getLinesList(InputStream inputStream) throws IOException { InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); List<String> linesList = new ArrayList<>(); while (read(bufferedReader) != null) { linesList.add(line); } bufferedReader.close(); inputStreamReader.close(); return linesList; } private String read(BufferedReader bufferedReader) throws IOException { line = bufferedReader.readLine(); return line; } /** * 获取属性 * * @param context 上下文 * @param fileName 文件名 * @return 属性 */ public Properties getProperties(Context context, String fileName) { InputStream inputStream = null; Properties properties = new Properties(); try { inputStream = context.getAssets().open(fileName); properties.load(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); inputStream.close(); } catch (Exception e) { LogUtils.exception(e); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { LogUtils.exception(e); } } } return properties; } @Override public String toString() { return keyValueMap.toString(); } }
27.934132
105
0.561415
6fcbdf7e54b104cb04e8f4038caf124e80ca7ca7
1,790
swift
Swift
Controller/Groups&Pages/GroupMoreController.swift
AgrinobleAGN/Agrinoble-Mobile-App-iOS
9c28c53b8f3b74afcf5ba1e280c2f7ac36de2403
[ "MIT" ]
1
2021-09-29T03:08:51.000Z
2021-09-29T03:08:51.000Z
Controller/Groups&Pages/GroupMoreController.swift
AgrinobleAGN/Agrinoble-Mobile-App-iOS
9c28c53b8f3b74afcf5ba1e280c2f7ac36de2403
[ "MIT" ]
null
null
null
Controller/Groups&Pages/GroupMoreController.swift
AgrinobleAGN/Agrinoble-Mobile-App-iOS
9c28c53b8f3b74afcf5ba1e280c2f7ac36de2403
[ "MIT" ]
null
null
null
import UIKit import WoWonderTimelineSDK class GroupMoreController: UIViewController { @IBOutlet weak var moreLabel: UILabel! @IBOutlet weak var copyLinkBtn: UIButton! @IBOutlet weak var shareBtn: UIButton! @IBOutlet weak var settingBtn: UIButton! @IBOutlet weak var closeBtn: UIButton! var groupUrl: String? = nil var delegate: GroupMoreDelegate? override func viewDidLoad() { super.viewDidLoad() self.copyLinkBtn.setTitle(NSLocalizedString("Copy Link", comment: "Copy Link"), for: .normal) self.shareBtn.setTitle(NSLocalizedString("Share", comment: "Share"), for: .normal) self.settingBtn.setTitle(NSLocalizedString("Setting", comment: "Setting"), for: .normal) self.closeBtn.setTitle(NSLocalizedString("Close", comment: "Close"), for: .normal) self.closeBtn.setTitleColor(UIColor.hexStringToUIColor(hex: ControlSettings.buttonColor), for: .normal) } @IBAction func Close(_ sender: Any) { self.dismiss(animated: true, completion: nil) } @IBAction func More(_ sender: UIButton) { switch sender.tag{ case 0: self.dismiss(animated: true) { self.delegate?.gotoSetting(type: "copy") } case 1: self.dismiss(animated: true) { self.delegate?.gotoSetting(type: "share") } case 2: self.dismiss(animated: true) { self.delegate?.gotoSetting(type: "setting") } default: print("noting") } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.dismiss(animated: true, completion: nil) } }
30.338983
111
0.603352
74cfe16b47b5684149a6062915f6a9e8c6af0318
16,567
rs
Rust
cargo/vendor/windows-sys-0.32.0/src/Windows/Win32/System/EventCollector/mod.rs
btwiuse/invctrl
b3b47ad75510bd48bb235f1813cc6eb391579a00
[ "MIT" ]
1
2020-01-15T09:33:02.000Z
2020-01-15T09:33:02.000Z
cargo/vendor/windows-sys-0.32.0/src/Windows/Win32/System/EventCollector/mod.rs
btwiuse/conntroll
39e426475a13a0610252dab8c030206a27a955fd
[ "MIT" ]
null
null
null
cargo/vendor/windows-sys-0.32.0/src/Windows/Win32/System/EventCollector/mod.rs
btwiuse/conntroll
39e426475a13a0610252dab8c030206a27a955fd
[ "MIT" ]
null
null
null
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" { #[doc = "*Required features: 'Win32_System_EventCollector', 'Win32_Foundation'*"] #[cfg(feature = "Win32_Foundation")] pub fn EcClose(object: isize) -> super::super::Foundation::BOOL; #[doc = "*Required features: 'Win32_System_EventCollector', 'Win32_Foundation'*"] #[cfg(feature = "Win32_Foundation")] pub fn EcDeleteSubscription(subscriptionname: super::super::Foundation::PWSTR, flags: u32) -> super::super::Foundation::BOOL; #[doc = "*Required features: 'Win32_System_EventCollector', 'Win32_Foundation'*"] #[cfg(feature = "Win32_Foundation")] pub fn EcEnumNextSubscription(subscriptionenum: isize, subscriptionnamebuffersize: u32, subscriptionnamebuffer: super::super::Foundation::PWSTR, subscriptionnamebufferused: *mut u32) -> super::super::Foundation::BOOL; #[doc = "*Required features: 'Win32_System_EventCollector', 'Win32_Foundation'*"] #[cfg(feature = "Win32_Foundation")] pub fn EcGetObjectArrayProperty(objectarray: isize, propertyid: EC_SUBSCRIPTION_PROPERTY_ID, arrayindex: u32, flags: u32, propertyvaluebuffersize: u32, propertyvaluebuffer: *mut EC_VARIANT, propertyvaluebufferused: *mut u32) -> super::super::Foundation::BOOL; #[doc = "*Required features: 'Win32_System_EventCollector', 'Win32_Foundation'*"] #[cfg(feature = "Win32_Foundation")] pub fn EcGetObjectArraySize(objectarray: isize, objectarraysize: *mut u32) -> super::super::Foundation::BOOL; #[doc = "*Required features: 'Win32_System_EventCollector', 'Win32_Foundation'*"] #[cfg(feature = "Win32_Foundation")] pub fn EcGetSubscriptionProperty(subscription: isize, propertyid: EC_SUBSCRIPTION_PROPERTY_ID, flags: u32, propertyvaluebuffersize: u32, propertyvaluebuffer: *mut EC_VARIANT, propertyvaluebufferused: *mut u32) -> super::super::Foundation::BOOL; #[doc = "*Required features: 'Win32_System_EventCollector', 'Win32_Foundation'*"] #[cfg(feature = "Win32_Foundation")] pub fn EcGetSubscriptionRunTimeStatus(subscriptionname: super::super::Foundation::PWSTR, statusinfoid: EC_SUBSCRIPTION_RUNTIME_STATUS_INFO_ID, eventsourcename: super::super::Foundation::PWSTR, flags: u32, statusvaluebuffersize: u32, statusvaluebuffer: *mut EC_VARIANT, statusvaluebufferused: *mut u32) -> super::super::Foundation::BOOL; #[doc = "*Required features: 'Win32_System_EventCollector', 'Win32_Foundation'*"] #[cfg(feature = "Win32_Foundation")] pub fn EcInsertObjectArrayElement(objectarray: isize, arrayindex: u32) -> super::super::Foundation::BOOL; #[doc = "*Required features: 'Win32_System_EventCollector', 'Win32_Foundation'*"] #[cfg(feature = "Win32_Foundation")] pub fn EcOpenSubscription(subscriptionname: super::super::Foundation::PWSTR, accessmask: u32, flags: u32) -> isize; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub fn EcOpenSubscriptionEnum(flags: u32) -> isize; #[doc = "*Required features: 'Win32_System_EventCollector', 'Win32_Foundation'*"] #[cfg(feature = "Win32_Foundation")] pub fn EcRemoveObjectArrayElement(objectarray: isize, arrayindex: u32) -> super::super::Foundation::BOOL; #[doc = "*Required features: 'Win32_System_EventCollector', 'Win32_Foundation'*"] #[cfg(feature = "Win32_Foundation")] pub fn EcRetrySubscription(subscriptionname: super::super::Foundation::PWSTR, eventsourcename: super::super::Foundation::PWSTR, flags: u32) -> super::super::Foundation::BOOL; #[doc = "*Required features: 'Win32_System_EventCollector', 'Win32_Foundation'*"] #[cfg(feature = "Win32_Foundation")] pub fn EcSaveSubscription(subscription: isize, flags: u32) -> super::super::Foundation::BOOL; #[doc = "*Required features: 'Win32_System_EventCollector', 'Win32_Foundation'*"] #[cfg(feature = "Win32_Foundation")] pub fn EcSetObjectArrayProperty(objectarray: isize, propertyid: EC_SUBSCRIPTION_PROPERTY_ID, arrayindex: u32, flags: u32, propertyvalue: *mut EC_VARIANT) -> super::super::Foundation::BOOL; #[doc = "*Required features: 'Win32_System_EventCollector', 'Win32_Foundation'*"] #[cfg(feature = "Win32_Foundation")] pub fn EcSetSubscriptionProperty(subscription: isize, propertyid: EC_SUBSCRIPTION_PROPERTY_ID, flags: u32, propertyvalue: *mut EC_VARIANT) -> super::super::Foundation::BOOL; } #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EC_CREATE_NEW: u32 = 1u32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EC_OPEN_ALWAYS: u32 = 0u32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EC_OPEN_EXISTING: u32 = 2u32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EC_READ_ACCESS: u32 = 1u32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub type EC_SUBSCRIPTION_CONFIGURATION_MODE = i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcConfigurationModeNormal: EC_SUBSCRIPTION_CONFIGURATION_MODE = 0i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcConfigurationModeCustom: EC_SUBSCRIPTION_CONFIGURATION_MODE = 1i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcConfigurationModeMinLatency: EC_SUBSCRIPTION_CONFIGURATION_MODE = 2i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcConfigurationModeMinBandwidth: EC_SUBSCRIPTION_CONFIGURATION_MODE = 3i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub type EC_SUBSCRIPTION_CONTENT_FORMAT = i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcContentFormatEvents: EC_SUBSCRIPTION_CONTENT_FORMAT = 1i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcContentFormatRenderedText: EC_SUBSCRIPTION_CONTENT_FORMAT = 2i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub type EC_SUBSCRIPTION_CREDENTIALS_TYPE = i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionCredDefault: EC_SUBSCRIPTION_CREDENTIALS_TYPE = 0i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionCredNegotiate: EC_SUBSCRIPTION_CREDENTIALS_TYPE = 1i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionCredDigest: EC_SUBSCRIPTION_CREDENTIALS_TYPE = 2i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionCredBasic: EC_SUBSCRIPTION_CREDENTIALS_TYPE = 3i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionCredLocalMachine: EC_SUBSCRIPTION_CREDENTIALS_TYPE = 4i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub type EC_SUBSCRIPTION_DELIVERY_MODE = i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcDeliveryModePull: EC_SUBSCRIPTION_DELIVERY_MODE = 1i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcDeliveryModePush: EC_SUBSCRIPTION_DELIVERY_MODE = 2i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub type EC_SUBSCRIPTION_PROPERTY_ID = i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionEnabled: EC_SUBSCRIPTION_PROPERTY_ID = 0i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionEventSources: EC_SUBSCRIPTION_PROPERTY_ID = 1i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionEventSourceAddress: EC_SUBSCRIPTION_PROPERTY_ID = 2i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionEventSourceEnabled: EC_SUBSCRIPTION_PROPERTY_ID = 3i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionEventSourceUserName: EC_SUBSCRIPTION_PROPERTY_ID = 4i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionEventSourcePassword: EC_SUBSCRIPTION_PROPERTY_ID = 5i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionDescription: EC_SUBSCRIPTION_PROPERTY_ID = 6i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionURI: EC_SUBSCRIPTION_PROPERTY_ID = 7i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionConfigurationMode: EC_SUBSCRIPTION_PROPERTY_ID = 8i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionExpires: EC_SUBSCRIPTION_PROPERTY_ID = 9i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionQuery: EC_SUBSCRIPTION_PROPERTY_ID = 10i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionTransportName: EC_SUBSCRIPTION_PROPERTY_ID = 11i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionTransportPort: EC_SUBSCRIPTION_PROPERTY_ID = 12i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionDeliveryMode: EC_SUBSCRIPTION_PROPERTY_ID = 13i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionDeliveryMaxItems: EC_SUBSCRIPTION_PROPERTY_ID = 14i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionDeliveryMaxLatencyTime: EC_SUBSCRIPTION_PROPERTY_ID = 15i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionHeartbeatInterval: EC_SUBSCRIPTION_PROPERTY_ID = 16i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionLocale: EC_SUBSCRIPTION_PROPERTY_ID = 17i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionContentFormat: EC_SUBSCRIPTION_PROPERTY_ID = 18i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionLogFile: EC_SUBSCRIPTION_PROPERTY_ID = 19i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionPublisherName: EC_SUBSCRIPTION_PROPERTY_ID = 20i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionCredentialsType: EC_SUBSCRIPTION_PROPERTY_ID = 21i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionCommonUserName: EC_SUBSCRIPTION_PROPERTY_ID = 22i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionCommonPassword: EC_SUBSCRIPTION_PROPERTY_ID = 23i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionHostName: EC_SUBSCRIPTION_PROPERTY_ID = 24i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionReadExistingEvents: EC_SUBSCRIPTION_PROPERTY_ID = 25i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionDialect: EC_SUBSCRIPTION_PROPERTY_ID = 26i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionType: EC_SUBSCRIPTION_PROPERTY_ID = 27i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionAllowedIssuerCAs: EC_SUBSCRIPTION_PROPERTY_ID = 28i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionAllowedSubjects: EC_SUBSCRIPTION_PROPERTY_ID = 29i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionDeniedSubjects: EC_SUBSCRIPTION_PROPERTY_ID = 30i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionAllowedSourceDomainComputers: EC_SUBSCRIPTION_PROPERTY_ID = 31i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionPropertyIdEND: EC_SUBSCRIPTION_PROPERTY_ID = 32i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub type EC_SUBSCRIPTION_RUNTIME_STATUS_ACTIVE_STATUS = i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcRuntimeStatusActiveStatusDisabled: EC_SUBSCRIPTION_RUNTIME_STATUS_ACTIVE_STATUS = 1i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcRuntimeStatusActiveStatusActive: EC_SUBSCRIPTION_RUNTIME_STATUS_ACTIVE_STATUS = 2i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcRuntimeStatusActiveStatusInactive: EC_SUBSCRIPTION_RUNTIME_STATUS_ACTIVE_STATUS = 3i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcRuntimeStatusActiveStatusTrying: EC_SUBSCRIPTION_RUNTIME_STATUS_ACTIVE_STATUS = 4i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub type EC_SUBSCRIPTION_RUNTIME_STATUS_INFO_ID = i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionRunTimeStatusActive: EC_SUBSCRIPTION_RUNTIME_STATUS_INFO_ID = 0i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionRunTimeStatusLastError: EC_SUBSCRIPTION_RUNTIME_STATUS_INFO_ID = 1i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionRunTimeStatusLastErrorMessage: EC_SUBSCRIPTION_RUNTIME_STATUS_INFO_ID = 2i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionRunTimeStatusLastErrorTime: EC_SUBSCRIPTION_RUNTIME_STATUS_INFO_ID = 3i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionRunTimeStatusNextRetryTime: EC_SUBSCRIPTION_RUNTIME_STATUS_INFO_ID = 4i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionRunTimeStatusEventSources: EC_SUBSCRIPTION_RUNTIME_STATUS_INFO_ID = 5i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionRunTimeStatusLastHeartbeatTime: EC_SUBSCRIPTION_RUNTIME_STATUS_INFO_ID = 6i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionRunTimeStatusInfoIdEND: EC_SUBSCRIPTION_RUNTIME_STATUS_INFO_ID = 7i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub type EC_SUBSCRIPTION_TYPE = i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionTypeSourceInitiated: EC_SUBSCRIPTION_TYPE = 0i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcSubscriptionTypeCollectorInitiated: EC_SUBSCRIPTION_TYPE = 1i32; #[repr(C)] #[doc = "*Required features: 'Win32_System_EventCollector', 'Win32_Foundation'*"] #[cfg(feature = "Win32_Foundation")] pub struct EC_VARIANT { pub Anonymous: EC_VARIANT_0, pub Count: u32, pub Type: u32, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for EC_VARIANT {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for EC_VARIANT { fn clone(&self) -> Self { *self } } #[repr(C)] #[doc = "*Required features: 'Win32_System_EventCollector', 'Win32_Foundation'*"] #[cfg(feature = "Win32_Foundation")] pub union EC_VARIANT_0 { pub BooleanVal: super::super::Foundation::BOOL, pub UInt32Val: u32, pub DateTimeVal: u64, pub StringVal: super::super::Foundation::PWSTR, pub BinaryVal: *mut u8, pub BooleanArr: *mut super::super::Foundation::BOOL, pub Int32Arr: *mut i32, pub StringArr: *mut super::super::Foundation::PWSTR, pub PropertyHandleVal: isize, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for EC_VARIANT_0 {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for EC_VARIANT_0 { fn clone(&self) -> Self { *self } } #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub type EC_VARIANT_TYPE = i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcVarTypeNull: EC_VARIANT_TYPE = 0i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcVarTypeBoolean: EC_VARIANT_TYPE = 1i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcVarTypeUInt32: EC_VARIANT_TYPE = 2i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcVarTypeDateTime: EC_VARIANT_TYPE = 3i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcVarTypeString: EC_VARIANT_TYPE = 4i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EcVarObjectArrayPropertyHandle: EC_VARIANT_TYPE = 5i32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EC_VARIANT_TYPE_ARRAY: u32 = 128u32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EC_VARIANT_TYPE_MASK: u32 = 127u32; #[doc = "*Required features: 'Win32_System_EventCollector'*"] pub const EC_WRITE_ACCESS: u32 = 2u32;
66.003984
340
0.78596
f99194f77fd8c0e77fa7418543d31b25edb0e1b8
2,203
go
Go
commands/auth_test.go
fantasticrabbit/faas-cli
b1c09c0243f69990b6c81a17d7337f0fd23e7542
[ "MIT" ]
670
2017-09-24T09:20:57.000Z
2022-03-31T07:56:58.000Z
commands/auth_test.go
fantasticrabbit/faas-cli
b1c09c0243f69990b6c81a17d7337f0fd23e7542
[ "MIT" ]
744
2017-09-24T10:09:16.000Z
2022-03-28T09:37:50.000Z
commands/auth_test.go
fantasticrabbit/faas-cli
b1c09c0243f69990b6c81a17d7337f0fd23e7542
[ "MIT" ]
243
2017-09-25T14:51:12.000Z
2022-03-03T10:50:27.000Z
// Copyright (c) OpenFaaS Ltd 2021. All rights reserved. // // Licensed for use with OpenFaaS Pro only // See EULA: https://github.com/openfaas/faas/blob/master/pro/EULA.md package commands import ( "testing" ) func Test_auth(t *testing.T) { testCases := []struct { name string authURL string eula bool clientID string wantErr string }{ { name: "Default parameters", authURL: "", clientID: "", wantErr: "--auth-url is required and must be a valid OIDC URL", eula: true, }, { name: "Invalid auth-url", authURL: "xyz", clientID: "", wantErr: "--auth-url is an invalid URL: xyz", eula: true, }, { name: "Invalid eula acceptance", authURL: "http://xyz", clientID: "id", wantErr: "the auth command is only licensed for OpenFaaS Pro customers, see: https://github.com/openfaas/faas/blob/master/pro/EULA.md", eula: false, }, { name: "Valid auth-url, invalid client-id", authURL: "http://xyz", clientID: "", wantErr: "--client-id is required", eula: true, }, { name: "Valid auth-url and client-id", authURL: "http://xyz", clientID: "abc", wantErr: "", eula: true, }, } for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { err := checkValues(testCase.authURL, testCase.clientID, testCase.eula) gotErr := "" if err != nil { gotErr = err.Error() } if testCase.wantErr != gotErr { t.Errorf("want %q, got %q", testCase.wantErr, gotErr) t.Fail() } }) } } func Test_makeRedirectURI_Valid(t *testing.T) { uri, err := makeRedirectURI("http://localhost", 31112) if err != nil { t.Fatal(err) } got := uri.String() want := "http://localhost:31112/oauth/callback" if got != want { t.Errorf("want %q, got %q", want, got) t.Fail() } } func Test_makeRedirectURI_NoSchemeIsInvalid(t *testing.T) { _, err := makeRedirectURI("localhost", 31112) if err == nil { t.Fatal("test should fail without a URL scheme") } got := err.Error() want := "a scheme is required for the URL, i.e. http://" if got != want { t.Errorf("want %q, got %q", want, got) t.Fail() } }
20.588785
139
0.603268
4fa6f7fb754a29687285cb5227a7219f58f69257
3,138
sql
SQL
my_mvc_db.sql
ucantseeme/p2
8e9734af6c0c6c7db247ae68d35517944a618b34
[ "MIT" ]
null
null
null
my_mvc_db.sql
ucantseeme/p2
8e9734af6c0c6c7db247ae68d35517944a618b34
[ "MIT" ]
null
null
null
my_mvc_db.sql
ucantseeme/p2
8e9734af6c0c6c7db247ae68d35517944a618b34
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 4.4.10 -- http://www.phpmyadmin.net -- -- Host: localhost:3306 -- Generation Time: Jan 26, 2016 at 08:29 AM -- Server version: 5.5.42 -- PHP Version: 5.6.10 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; -- -- Database: `my_mvc_db` -- -- -------------------------------------------------------- -- -- Table structure for table `posts` -- CREATE TABLE `posts` ( `id` int(10) NOT NULL, `title` varchar(50) NOT NULL, `image_name` varchar(50) NOT NULL, `content` varchar(500) NOT NULL, `file_name` varchar(50) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1; -- -- Dumping data for table `posts` -- INSERT INTO `posts` (`id`, `title`, `image_name`, `content`, `file_name`) VALUES (3, 'Trekking in Nepal', '3.jpg', 'A trek in Nepal is a special and rewarding mountain holiday. If you have the time and energy to trek don’t miss the opportunity to leave Kathmandu and see the country’s spectacular beauty and unique culture. Fortunately for the visitor, there are still only a few roads extending ...', 'issue.pdf'), (4, 'Tibet Tour with Everest Base Camp', '7.jpg', 'This adventure takes you to the historical city of Lhasa – the roof of the world – and then overland across the spectacular Tibetan Plateau to Mount Everest Base Camp. You will begin by exploring the magnificent city of Lhasa, situated in a stunning valley surrounded by mountains...', 'issue.pdf'), (5, 'Nepal Cooking Schools in Nepal', '6.jpg', 'Your guide to the best online cooking schools and " hands on" cooking classes. If you want to really understand a countries culture... take a cooking class! Book online for a great selection of cooking classes, food and general interest tours with knowlegeable local tour guides...', 'issue.pdf'), (6, '5 Reasons Why Choosing Healthy Food Seems Hard', '1.jpg', 'Most people want to eat better, feel better, and live longer. However, it seems that manufactured food is geared toward convenience and taste, regardless of the nutrient value. According to www.worldheart.org,...', 'issue.pdf'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `id` int(12) NOT NULL, `username` varchar(50) NOT NULL, `email` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, `fullname` varchar(50) NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1; -- -- Dumping data for table `users` -- INSERT INTO `users` (`id`, `username`, `email`, `password`, `fullname`) VALUES (3, 'Sarthak', 'sarthakjoshi977@gmail.com', 'c0288a8410353bd12cb3486092076984', ''); -- -- Indexes for dumped tables -- -- -- Indexes for table `posts` -- ALTER TABLE `posts` ADD PRIMARY KEY (`id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `posts` -- ALTER TABLE `posts` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=7; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `id` int(12) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=4;
34.108696
350
0.68515
565941a4fdad1122f02122ca19fcb9fa26891afd
1,390
kt
Kotlin
meet-app/app/src/main/java/com/example/alejandro/myapplication/controllers/chat/ChatController.kt
AlejandroFraga/meet-app
98fb27a86e2ffa4e22ce51d6135dd2996e65e86f
[ "MIT" ]
null
null
null
meet-app/app/src/main/java/com/example/alejandro/myapplication/controllers/chat/ChatController.kt
AlejandroFraga/meet-app
98fb27a86e2ffa4e22ce51d6135dd2996e65e86f
[ "MIT" ]
null
null
null
meet-app/app/src/main/java/com/example/alejandro/myapplication/controllers/chat/ChatController.kt
AlejandroFraga/meet-app
98fb27a86e2ffa4e22ce51d6135dd2996e65e86f
[ "MIT" ]
null
null
null
package com.example.alejandro.myapplication.controllers.chat import com.example.alejandro.myapplication.facades.DatabaseFacade import com.example.alejandro.myapplication.model.chat.Mensaxe import com.example.alejandro.myapplication.service.chat.ChatService import com.example.alejandro.myapplication.service.chat.ChatServiceImpl import io.realm.RealmResults // Controlador do paquete Chat class ChatController(databaseFacade: DatabaseFacade) { //Service private val chatService: ChatService = ChatServiceImpl(databaseFacade) //Functions fun getAllMensaxes(): RealmResults<Mensaxe> { return chatService.getAllMensaxes() } fun getPendingMensaxes(): RealmResults<Mensaxe> { return chatService.getPendingMensaxes() } fun getNumPendingMensaxes(): Long { return chatService.getNumPendingMensaxes() } fun getMensaxe(id: String): Mensaxe? { return chatService.getMensaxe(id) } fun removeMensaxe(id: String) { chatService.removeMensaxe(id) } fun updateDataEnvio(mensaxe: Mensaxe) { chatService.updateDataEnvio(mensaxe) } fun updateDataLectura(mensaxe: Mensaxe) { chatService.updateDataLectura(mensaxe) } fun saveLocal(mensaxe: Mensaxe) { chatService.saveLocal(mensaxe) } fun save(mensaxe: Mensaxe) { chatService.save(mensaxe) } }
26.226415
74
0.725899
22fd2d83a74b1317032431f1838d9bfdd10c0b82
988
cpp
C++
codeforces/A - Almost Equal/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/A - Almost Equal/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/A - Almost Equal/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Apr/20/2020 10:23 * solution_verdict: Accepted language: GNU C++14 * run_time: 46 ms memory_used: 3900 KB * problem: https://codeforces.com/contest/1205/problem/A ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e6; int aa[N+2]; int main() { ios_base::sync_with_stdio(0);cin.tie(0); int n;cin>>n; if(n%2==0)cout<<"NO\n",exit(0); cout<<"YES\n"; int sw=0,cnt=0; for(int i=1;i<=n;i++) { aa[i]=++cnt;aa[i+n]=++cnt; if(sw)(swap(aa[i],aa[n+i])); sw^=1; } for(int i=1;i<=n+n;i++)cout<<aa[i]<<" ";cout<<endl; return 0; }
36.592593
111
0.376518
6fd853b2b9b8e8db9d1620dd8195198a24aaad1d
7,320
rs
Rust
src/lib.rs
registreerocks/ripple-address-codec-rust
a1084a39add63e52ab413bc307d2ec32905486c9
[ "Apache-2.0" ]
null
null
null
src/lib.rs
registreerocks/ripple-address-codec-rust
a1084a39add63e52ab413bc307d2ec32905486c9
[ "Apache-2.0" ]
null
null
null
src/lib.rs
registreerocks/ripple-address-codec-rust
a1084a39add63e52ab413bc307d2ec32905486c9
[ "Apache-2.0" ]
1
2021-10-04T13:21:11.000Z
2021-10-04T13:21:11.000Z
//! Encodes/decodes base58 encoded XRP Ledger identifiers //! //! Functions for encoding and decoding XRP Ledger addresses and seeds. //! //! # Examples //! //! See [Functions][crate#functions] section #![deny( warnings, clippy::all, missing_debug_implementations, missing_copy_implementations, missing_docs, missing_crate_level_docs, missing_doc_code_examples, non_ascii_idents, unreachable_pub )] #![doc(test(attr(deny(warnings))))] #![doc(html_root_url = "https://docs.rs/ripple-address-codec/0.1.1")] use std::{convert::TryInto, result}; use base_x; use ring::digest::{digest, SHA256}; mod error; pub use self::error::{Error, Error::DecodeError}; pub use self::Algorithm::{Ed25519, Secp256k1}; const ALPHABET: &str = "rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz"; const CHECKSUM_LENGTH: usize = 4; const ENTROPY_LEN: usize = 16; /// Seed entropy array /// /// The entropy must be exactly 16 bytes (128 bits). pub type Entropy = [u8; ENTROPY_LEN]; /// Result with decoding error pub type Result<T> = result::Result<T, Error>; /// The elliptic curve digital signature algorithm /// with which the seed is intended to be used #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Algorithm { /// Elliptic Curve Digital Signature Algorithm (ECDSA): secp256k1 Secp256k1, /// Edwards-curve Digital Signature Algorithm (EdDSA): Ed25519 Ed25519, } impl Default for Algorithm { fn default() -> Self { Self::Secp256k1 } } /// Encode the given entropy as an XRP Ledger seed (secret) /// /// The entropy must be exactly 16 bytes (128 bits). The encoding /// includes which elliptic curve digital signature algorithm the /// seed is intended to be used with. The seed is used to produce /// the private key. /// /// # Examples /// /// ``` /// use ripple_address_codec::{encode_seed, Secp256k1, Ed25519}; /// /// // In the real world you **must** generate random entropy /// let naive_entropy = [0; 16]; /// /// assert_eq!(encode_seed(&naive_entropy, &Secp256k1), "sp6JS7f14BuwFY8Mw6bTtLKWauoUs"); /// assert_eq!(encode_seed(&naive_entropy, &Ed25519), "sEdSJHS4oiAdz7w2X2ni1gFiqtbJHqE"); /// ``` pub fn encode_seed(entropy: &Entropy, algorithm: &Algorithm) -> String { let prefix = match algorithm { Secp256k1 => SeedSecP256K1.prefix(), Ed25519 => SeedEd25519.prefix(), }; encode_bytes_with_prefix(prefix, entropy) } /// Decode a seed into a tuple with seed's entropy bytes and algorithm /// /// # Examples /// /// ``` /// use ripple_address_codec::{decode_seed, Secp256k1, Ed25519}; /// /// assert_eq!(decode_seed("sp6JS7f14BuwFY8Mw6bTtLKWauoUs"), Ok(([0; 16], &Secp256k1))); /// assert_eq!(decode_seed("sEdSJHS4oiAdz7w2X2ni1gFiqtbJHqE"), Ok(([0; 16], &Ed25519))); /// ``` /// /// # Errors /// /// Returns [`DecodeError`] if seed is invalid. pub fn decode_seed(seed: &str) -> Result<(Entropy, &'static Algorithm)> { decode_seed_secp256k1(seed).or(decode_seed_ed25519(seed)) } /// Encode bytes as a classic address (starting with r...) /// /// # Examples /// /// ``` /// use ripple_address_codec::encode_account_id; /// /// assert_eq!(encode_account_id(&[0; 20]), "rrrrrrrrrrrrrrrrrrrrrhoLvTp"); /// ``` pub fn encode_account_id(bytes: &[u8; Address::PAYLOAD_LEN]) -> String { encode_bytes_with_prefix(Address.prefix(), bytes) } /// Decode a classic address (starting with r...) to its raw bytes /// /// # Examples /// /// ``` /// use ripple_address_codec::decode_account_id; /// /// assert_eq!(decode_account_id("rrrrrrrrrrrrrrrrrrrrrhoLvTp"), Ok([0; 20])); /// ``` /// /// # Errors /// /// Returns [`DecodeError`] if account id string is invalid. pub fn decode_account_id(account_id: &str) -> Result<[u8; Address::PAYLOAD_LEN]> { let decoded_bytes = decode_with_xrp_alphabet(account_id)?; let payload = get_payload(decoded_bytes, Address)?; Ok(payload.try_into().unwrap()) } trait Settings { const PAYLOAD_LEN: usize; const PREFIX: &'static [u8] = &[]; fn prefix(&self) -> &'static [u8] { Self::PREFIX } fn prefix_len(&self) -> usize { Self::PREFIX.len() } fn payload_len(&self) -> usize { Self::PAYLOAD_LEN } } struct Address; impl Settings for Address { const PREFIX: &'static [u8] = &[0x00]; const PAYLOAD_LEN: usize = 20; } struct SeedSecP256K1; impl SeedSecP256K1 { const ALG: Algorithm = Secp256k1; } impl Settings for SeedSecP256K1 { const PREFIX: &'static [u8] = &[0x21]; const PAYLOAD_LEN: usize = ENTROPY_LEN; } struct SeedEd25519; impl SeedEd25519 { const ALG: Algorithm = Ed25519; } impl Settings for SeedEd25519 { const PREFIX: &'static [u8] = &[0x01, 0xE1, 0x4B]; const PAYLOAD_LEN: usize = ENTROPY_LEN; } fn decode_seed_secp256k1(s: &str) -> Result<(Entropy, &'static Algorithm)> { let decoded_bytes = decode_with_xrp_alphabet(s)?; let payload = get_payload(decoded_bytes, SeedSecP256K1)?; Ok((payload.try_into().unwrap(), &SeedSecP256K1::ALG)) } fn decode_seed_ed25519(s: &str) -> Result<(Entropy, &'static Algorithm)> { let decoded_bytes = decode_with_xrp_alphabet(s)?; let payload = get_payload(decoded_bytes, SeedEd25519)?; Ok((payload.try_into().unwrap(), &SeedEd25519::ALG)) } fn encode_bytes_with_prefix(prefix: &[u8], bytes: &[u8]) -> String { encode_bytes(&[prefix, bytes].concat()) } fn encode_bytes(bytes: &[u8]) -> String { let checked_bytes = [bytes, &calc_checksum(bytes)].concat(); base_x::encode(ALPHABET, &checked_bytes) } fn decode_with_xrp_alphabet(s: &str) -> Result<Vec<u8>> { Ok(base_x::decode(ALPHABET, s)?) } fn get_payload(bytes: Vec<u8>, settings: impl Settings) -> Result<Vec<u8>> { verify_payload_len(&bytes, settings.prefix_len(), settings.payload_len())?; verify_prefix(settings.prefix(), &bytes)?; let checked_bytes = get_checked_bytes(bytes)?; Ok(checked_bytes[settings.prefix_len()..].try_into().unwrap()) } fn verify_prefix(prefix: &[u8], bytes: &[u8]) -> Result<()> { if bytes.starts_with(prefix) { return Ok(()); } Err(DecodeError) } fn verify_payload_len(bytes: &[u8], prefix_len: usize, expected_len: usize) -> Result<()> { if bytes[prefix_len..bytes.len() - CHECKSUM_LENGTH].len() == expected_len { return Ok(()); } Err(DecodeError) } fn get_checked_bytes(mut bytes_with_checksum: Vec<u8>) -> Result<Vec<u8>> { verify_checksum_lenght(&bytes_with_checksum)?; //Split bytes with checksum to checked bytes and checksum let checksum = bytes_with_checksum.split_off(bytes_with_checksum.len() - CHECKSUM_LENGTH); let bytes = bytes_with_checksum; verify_checksum(&bytes, &checksum)?; Ok(bytes) } fn verify_checksum(input: &[u8], checksum: &[u8]) -> Result<()> { if calc_checksum(input) == checksum { Ok(()) } else { Err(DecodeError) } } fn verify_checksum_lenght(bytes: &[u8]) -> Result<()> { let len = bytes.len(); if len < CHECKSUM_LENGTH + 1 { return Err(DecodeError); } Ok(()) } fn calc_checksum(bytes: &[u8]) -> [u8; CHECKSUM_LENGTH] { sha256_digest(&sha256_digest(bytes))[..CHECKSUM_LENGTH] .try_into() .unwrap() } fn sha256_digest(data: &[u8]) -> Vec<u8> { digest(&SHA256, data).as_ref().to_vec() }
26.330935
94
0.670219
2650769820d2cf31009f7209689e33328c929489
8,247
java
Java
OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/project/hibernate-core/src/test/java/org/hibernate/test/collection/list/PersistentListTest.java
HerrB92/obp
31238554ec22a10e56892e987439ded36d671e1e
[ "MIT" ]
null
null
null
OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/project/hibernate-core/src/test/java/org/hibernate/test/collection/list/PersistentListTest.java
HerrB92/obp
31238554ec22a10e56892e987439ded36d671e1e
[ "MIT" ]
null
null
null
OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/project/hibernate-core/src/test/java/org/hibernate/test/collection/list/PersistentListTest.java
HerrB92/obp
31238554ec22a10e56892e987439ded36d671e1e
[ "MIT" ]
1
2022-01-06T09:05:56.000Z
2022-01-06T09:05:56.000Z
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2011, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.collection.list; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.hibernate.Session; import org.hibernate.collection.internal.PersistentList; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.jdbc.Work; import org.hibernate.persister.collection.CollectionPersister; import org.hibernate.persister.collection.QueryableCollection; import org.hibernate.sql.SimpleSelect; import org.hibernate.testing.TestForIssue; import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase; import org.junit.Test; /** * Tests related to operations on a PersistentList * * @author Steve Ebersole */ public class PersistentListTest extends BaseCoreFunctionalTestCase { @Override public String[] getMappings() { return new String[] { "collection/list/Mappings.hbm.xml" }; } @Test @TestForIssue( jiraKey = "HHH-5732" ) public void testInverseListIndex() { // make sure no one changes the mapping final CollectionPersister collectionPersister = sessionFactory().getCollectionPersister( ListOwner.class.getName() + ".children" ); assertTrue( collectionPersister.isInverse() ); // do some creations... Session session = openSession(); session.beginTransaction(); ListOwner root = new ListOwner( "root" ); ListOwner child1 = new ListOwner( "c1" ); root.getChildren().add( child1 ); child1.setParent( root ); ListOwner child2 = new ListOwner( "c2" ); root.getChildren().add( child2 ); child2.setParent( root ); session.save( root ); session.getTransaction().commit(); session.close(); // now, make sure the list-index column gotten written... final Session session2 = openSession(); session2.beginTransaction(); session2.doWork( new Work() { @Override public void execute(Connection connection) throws SQLException { final QueryableCollection queryableCollection = (QueryableCollection) collectionPersister; SimpleSelect select = new SimpleSelect( getDialect() ) .setTableName( queryableCollection.getTableName() ) .addColumn( "NAME" ) .addColumn( "LIST_INDEX" ) .addCondition( "NAME", "<>", "?" ); PreparedStatement preparedStatement = ((SessionImplementor)session2).getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().prepareStatement( select.toStatementString() ); preparedStatement.setString( 1, "root" ); ResultSet resultSet = ((SessionImplementor)session2).getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().extract( preparedStatement ); Map<String, Integer> valueMap = new HashMap<String, Integer>(); while ( resultSet.next() ) { final String name = resultSet.getString( 1 ); assertFalse( "NAME column was null", resultSet.wasNull() ); final int position = resultSet.getInt( 2 ); assertFalse( "LIST_INDEX column was null", resultSet.wasNull() ); valueMap.put( name, position ); } assertEquals( 2, valueMap.size() ); // c1 should be list index 0 assertEquals( Integer.valueOf( 0 ), valueMap.get( "c1" ) ); // c2 should be list index 1 assertEquals( Integer.valueOf( 1 ), valueMap.get( "c2" ) ); } } ); session2.delete( root ); session2.getTransaction().commit(); session2.close(); } @Test @TestForIssue( jiraKey = "HHH-5732" ) public void testInverseListIndex2() { // make sure no one changes the mapping final CollectionPersister collectionPersister = sessionFactory().getCollectionPersister( Order.class.getName() + ".lineItems" ); assertTrue( collectionPersister.isInverse() ); // do some creations... Session session = openSession(); session.beginTransaction(); Order order = new Order( "acme-1" ); order.addLineItem( "abc", 2 ); order.addLineItem( "def", 200 ); order.addLineItem( "ghi", 13 ); session.save( order ); session.getTransaction().commit(); session.close(); // now, make sure the list-index column gotten written... final Session session2 = openSession(); session2.beginTransaction(); session2.doWork( new Work() { @Override public void execute(Connection connection) throws SQLException { final QueryableCollection queryableCollection = (QueryableCollection) collectionPersister; SimpleSelect select = new SimpleSelect( getDialect() ) .setTableName( queryableCollection.getTableName() ) .addColumn( "ORDER_ID" ) .addColumn( "INDX" ) .addColumn( "PRD_CODE" ); PreparedStatement preparedStatement = ((SessionImplementor)session2).getTransactionCoordinator().getJdbcCoordinator().getStatementPreparer().prepareStatement( select.toStatementString() ); ResultSet resultSet = ((SessionImplementor)session2).getTransactionCoordinator().getJdbcCoordinator().getResultSetReturn().extract( preparedStatement ); Map<String, Integer> valueMap = new HashMap<String, Integer>(); while ( resultSet.next() ) { final int fk = resultSet.getInt( 1 ); assertFalse( "Collection key (FK) column was null", resultSet.wasNull() ); final int indx = resultSet.getInt( 2 ); assertFalse( "List index column was null", resultSet.wasNull() ); final String prodCode = resultSet.getString( 3 ); assertFalse( "Prod code column was null", resultSet.wasNull() ); valueMap.put( prodCode, indx ); } assertEquals( 3, valueMap.size() ); assertEquals( Integer.valueOf( 0 ), valueMap.get( "abc" ) ); assertEquals( Integer.valueOf( 1 ), valueMap.get( "def" ) ); assertEquals( Integer.valueOf( 2 ), valueMap.get( "ghi" ) ); } } ); session2.delete( order ); session2.getTransaction().commit(); session2.close(); } @Test public void testWriteMethodDirtying() { ListOwner parent = new ListOwner( "root" ); ListOwner child = new ListOwner( "c1" ); parent.getChildren().add( child ); child.setParent( parent ); ListOwner otherChild = new ListOwner( "c2" ); Session session = openSession(); session.beginTransaction(); session.save( parent ); session.flush(); // at this point, the list on parent has now been replaced with a PersistentList... PersistentList children = (PersistentList) parent.getChildren(); assertFalse( children.remove( otherChild ) ); assertFalse( children.isDirty() ); ArrayList otherCollection = new ArrayList(); otherCollection.add( child ); assertFalse( children.retainAll( otherCollection ) ); assertFalse( children.isDirty() ); otherCollection = new ArrayList(); otherCollection.add( otherChild ); assertFalse( children.removeAll( otherCollection ) ); assertFalse( children.isDirty() ); children.clear(); session.delete( child ); assertTrue( children.isDirty() ); session.flush(); children.clear(); assertFalse( children.isDirty() ); session.delete( parent ); session.getTransaction().commit(); session.close(); } }
37.486364
194
0.715897
518a12efe92d360fbf8c98949978ae249f84224a
19,515
dart
Dart
packages/flutter/lib/src/widgets/routes.dart
collinjackson/flutter
e2ab858202eba9aa0d874567a087b4b64a8ba3e0
[ "BSD-3-Clause" ]
null
null
null
packages/flutter/lib/src/widgets/routes.dart
collinjackson/flutter
e2ab858202eba9aa0d874567a087b4b64a8ba3e0
[ "BSD-3-Clause" ]
null
null
null
packages/flutter/lib/src/widgets/routes.dart
collinjackson/flutter
e2ab858202eba9aa0d874567a087b4b64a8ba3e0
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'basic.dart'; import 'focus.dart'; import 'framework.dart'; import 'modal_barrier.dart'; import 'navigator.dart'; import 'overlay.dart'; import 'page_storage.dart'; import 'pages.dart'; const Color _kTransparent = const Color(0x00000000); /// A route that displays widgets in the [Navigator]'s [Overlay]. abstract class OverlayRoute<T> extends Route<T> { /// Subclasses should override this getter to return the builders for the overlay. List<WidgetBuilder> get builders; /// The entries this route has placed in the overlay. @override List<OverlayEntry> get overlayEntries => _overlayEntries; final List<OverlayEntry> _overlayEntries = <OverlayEntry>[]; @override void install(OverlayEntry insertionPoint) { assert(_overlayEntries.isEmpty); for (WidgetBuilder builder in builders) _overlayEntries.add(new OverlayEntry(builder: builder)); navigator.overlay?.insertAll(_overlayEntries, above: insertionPoint); } /// A request was made to pop this route. If the route can handle it /// internally (e.g. because it has its own stack of internal state) then /// return false, otherwise return true. Returning false will prevent the /// default behavior of NavigatorState.pop(). /// /// If this is called, the Navigator will not call dispose(). It is the /// responsibility of the Route to later call dispose(). /// /// Subclasses shouldn't call this if they want to delay the finished() call. @override bool didPop(T result) { finished(); return true; } /// Clears out the overlay entries. /// /// This method is intended to be used by subclasses who don't call /// super.didPop() because they want to have control over the timing of the /// overlay removal. /// /// Do not call this method outside of this context. void finished() { for (OverlayEntry entry in _overlayEntries) entry.remove(); _overlayEntries.clear(); } @override void dispose() { finished(); } } /// A route with entrance and exit transitions. abstract class TransitionRoute<T> extends OverlayRoute<T> { TransitionRoute({ Completer<T> popCompleter, Completer<T> transitionCompleter }) : _popCompleter = popCompleter, _transitionCompleter = transitionCompleter; /// The same as the default constructor but callable with mixins. TransitionRoute.explicit( Completer<T> popCompleter, Completer<T> transitionCompleter ) : this(popCompleter: popCompleter, transitionCompleter: transitionCompleter); /// This future completes once the animation has been dismissed. For /// ModalRoutes, this will be after the completer that's passed in, since that /// one completes before the animation even starts, as soon as the route is /// popped. Future<T> get popped => _popCompleter?.future; final Completer<T> _popCompleter; /// This future completes only once the transition itself has finished, after /// the overlay entries have been removed from the navigator's overlay. Future<T> get completed => _transitionCompleter?.future; final Completer<T> _transitionCompleter; /// The duration the transition lasts. Duration get transitionDuration; /// Whether the route obscures previous routes when the transition is complete. /// /// When an opaque route's entrance transition is complete, the routes behind /// the opaque route will not be built to save resources. bool get opaque; /// The animation that drives the route's transition and the previous route's /// forward transition. Animation<double> get animation => _animation; Animation<double> _animation; AnimationController _controller; /// Called to create the animation controller that will drive the transitions to /// this route from the previous one, and back to the previous route from this /// one. AnimationController createAnimationController() { Duration duration = transitionDuration; assert(duration != null && duration >= Duration.ZERO); return new AnimationController(duration: duration, debugLabel: debugLabel); } /// Called to create the animation that exposes the current progress of /// the transition controlled by the animation controller created by /// [createAnimationController()]. Animation<double> createAnimation() { assert(_controller != null); return _controller.view; } T _result; void _handleStatusChanged(AnimationStatus status) { switch (status) { case AnimationStatus.completed: if (overlayEntries.isNotEmpty) overlayEntries.first.opaque = opaque; break; case AnimationStatus.forward: case AnimationStatus.reverse: if (overlayEntries.isNotEmpty) overlayEntries.first.opaque = false; break; case AnimationStatus.dismissed: assert(!overlayEntries.first.opaque); finished(); // clear the overlays assert(overlayEntries.isEmpty); break; } } Animation<double> get forwardAnimation => _forwardAnimation; final ProxyAnimation _forwardAnimation = new ProxyAnimation(kAlwaysDismissedAnimation); @override void install(OverlayEntry insertionPoint) { _controller = createAnimationController(); assert(_controller != null); _animation = createAnimation(); assert(_animation != null); super.install(insertionPoint); } @override void didPush() { _animation.addStatusListener(_handleStatusChanged); _controller.forward(); super.didPush(); } @override void didReplace(Route<dynamic> oldRoute) { if (oldRoute is TransitionRoute<dynamic>) _controller.value = oldRoute._controller.value; _animation.addStatusListener(_handleStatusChanged); super.didReplace(oldRoute); } @override bool didPop(T result) { _result = result; _controller.reverse(); _popCompleter?.complete(_result); return true; } @override void didPopNext(Route<dynamic> nextRoute) { _updateForwardAnimation(nextRoute); super.didPopNext(nextRoute); } @override void didChangeNext(Route<dynamic> nextRoute) { _updateForwardAnimation(nextRoute); super.didChangeNext(nextRoute); } void _updateForwardAnimation(Route<dynamic> nextRoute) { if (nextRoute is TransitionRoute<dynamic> && canTransitionTo(nextRoute) && nextRoute.canTransitionFrom(this)) { Animation<double> current = _forwardAnimation.parent; if (current != null) { if (current is TrainHoppingAnimation) { TrainHoppingAnimation newAnimation; newAnimation = new TrainHoppingAnimation( current.currentTrain, nextRoute.animation, onSwitchedTrain: () { assert(_forwardAnimation.parent == newAnimation); assert(newAnimation.currentTrain == nextRoute.animation); _forwardAnimation.parent = newAnimation.currentTrain; newAnimation.dispose(); } ); _forwardAnimation.parent = newAnimation; current.dispose(); } else { _forwardAnimation.parent = new TrainHoppingAnimation(current, nextRoute.animation); } } else { _forwardAnimation.parent = nextRoute.animation; } } else { _forwardAnimation.parent = kAlwaysDismissedAnimation; } } /// Whether this route can perform a transition to the given route. /// /// Subclasses can override this function to restrict the set of routes they /// need to coordinate transitions with. bool canTransitionTo(TransitionRoute<dynamic> nextRoute) => true; /// Whether this route can perform a transition from the given route. /// /// Subclasses can override this function to restrict the set of routes they /// need to coordinate transitions with. bool canTransitionFrom(TransitionRoute<dynamic> nextRoute) => true; @override void finished() { super.finished(); _transitionCompleter?.complete(_result); } @override void dispose() { _controller.stop(); super.dispose(); } String get debugLabel => '$runtimeType'; @override String toString() => '$runtimeType(animation: $_controller)'; } /// An entry in the history of a [LocalHistoryRoute]. class LocalHistoryEntry { LocalHistoryEntry({ this.onRemove }); /// Called when this entry is removed from the history of its associated [LocalHistoryRoute]. final VoidCallback onRemove; LocalHistoryRoute<dynamic> _owner; /// Remove this entry from the history of its associated [LocalHistoryRoute]. void remove() { _owner.removeLocalHistoryEntry(this); assert(_owner == null); } void _notifyRemoved() { if (onRemove != null) onRemove(); } } /// A route that can handle back navigations internally by popping a list. /// /// When a [Navigator] is instructed to pop, the current route is given an /// opportunity to handle the pop internally. A LocalHistoryRoute handles the /// pop internally if its list of local history entries is non-empty. Rather /// than being removed as the current route, the most recent [LocalHistoryEntry] /// is removed from the list and its [onRemove] is called. abstract class LocalHistoryRoute<T> extends Route<T> { List<LocalHistoryEntry> _localHistory; /// Adds a local history entry to this route. /// /// When asked to pop, if this route has any local history entries, this route /// will handle the pop internally by removing the most recently added local /// history entry. /// /// The given local history entry must not already be part of another local /// history route. void addLocalHistoryEntry(LocalHistoryEntry entry) { assert(entry._owner == null); entry._owner = this; _localHistory ??= <LocalHistoryEntry>[]; _localHistory.add(entry); } /// Remove a local history entry from this route. /// /// The entry's [onRemove] callback, if any, will be called synchronously. void removeLocalHistoryEntry(LocalHistoryEntry entry) { assert(entry != null); assert(entry._owner == this); assert(_localHistory.contains(entry)); _localHistory.remove(entry); entry._owner = null; entry._notifyRemoved(); } @override bool didPop(T result) { if (_localHistory != null && _localHistory.length > 0) { LocalHistoryEntry entry = _localHistory.removeLast(); assert(entry._owner == this); entry._owner = null; entry._notifyRemoved(); return false; } return super.didPop(result); } @override bool get willHandlePopInternally { return _localHistory != null && _localHistory.length > 0; } } class _ModalScopeStatus extends InheritedWidget { _ModalScopeStatus({ Key key, this.isCurrent, this.route, Widget child }) : super(key: key, child: child) { assert(isCurrent != null); assert(route != null); assert(child != null); } final bool isCurrent; final Route<dynamic> route; @override bool updateShouldNotify(_ModalScopeStatus old) { return isCurrent != old.isCurrent || route != old.route; } @override void debugFillDescription(List<String> description) { super.debugFillDescription(description); description.add('${isCurrent ? "active" : "inactive"}'); } } class _ModalScope extends StatefulWidget { _ModalScope({ Key key, this.route }) : super(key: key); final ModalRoute<dynamic> route; @override _ModalScopeState createState() => new _ModalScopeState(); } class _ModalScopeState extends State<_ModalScope> { @override void initState() { super.initState(); config.route.animation?.addStatusListener(_animationStatusChanged); config.route.forwardAnimation?.addStatusListener(_animationStatusChanged); } @override void didUpdateConfig(_ModalScope oldConfig) { assert(config.route == oldConfig.route); } @override void dispose() { config.route.animation?.removeStatusListener(_animationStatusChanged); config.route.forwardAnimation?.removeStatusListener(_animationStatusChanged); super.dispose(); } void _animationStatusChanged(AnimationStatus status) { setState(() { // The animation's states are our build state, and they changed already. }); } @override Widget build(BuildContext context) { Widget contents = new PageStorage( key: config.route._subtreeKey, bucket: config.route._storageBucket, child: new _ModalScopeStatus( route: config.route, isCurrent: config.route.isCurrent, child: config.route.buildPage(context, config.route.animation, config.route.forwardAnimation) ) ); if (config.route.offstage) { contents = new OffStage(child: contents); } else { contents = new IgnorePointer( ignoring: config.route.animation?.status == AnimationStatus.reverse, child: config.route.buildTransitions( context, config.route.animation, config.route.forwardAnimation, contents ) ); } contents = new Focus( key: new GlobalObjectKey(config.route), child: new RepaintBoundary(child: contents) ); return contents; } } /// A route that blocks interaction with previous routes. /// /// ModalRoutes cover the entire [Navigator]. They are not necessarily [opaque], /// however; for example, a pop-up menu uses a ModalRoute but only shows the menu /// in a small box overlapping the previous route. abstract class ModalRoute<T> extends TransitionRoute<T> with LocalHistoryRoute<T> { ModalRoute({ Completer<T> completer, this.settings: const RouteSettings() }) : super.explicit(completer, null); // The API for general users of this class /// The settings for this route. /// /// See [RouteSettings] for details. final RouteSettings settings; /// Returns the modal route most closely associated with the given context. /// /// Returns `null` if the given context is not associated with a modal route. static ModalRoute<dynamic> of(BuildContext context) { _ModalScopeStatus widget = context.inheritFromWidgetOfExactType(_ModalScopeStatus); return widget?.route; } // The API for subclasses to override - used by _ModalScope /// Override this function to build the primary content of this route. /// /// * [context] The context in which the route is being built. /// * [animation] The animation for this route's transition. When entering, /// the animation runs forward from 0.0 to 1.0. When exiting, this animation /// runs backwards from 1.0 to 0.0. /// * [forwardAnimation] The animation for the route being pushed on top of /// this route. This animation lets this route coordinate with the entrance /// and exit transition of routes pushed on top of this route. Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> forwardAnimation); /// Override this function to wrap the route in a number of transition widgets. /// /// For example, to create a fade entrance transition, wrap the given child /// widget in a [FadeTransition] using the given animation as the opacity. /// /// By default, the child is not wrapped in any transition widgets. /// /// * [context] The context in which the route is being built. /// * [animation] The animation for this route's transition. When entering, /// the animation runs forward from 0.0 to 1.0. When exiting, this animation /// runs backwards from 1.0 to 0.0. /// * [forwardAnimation] The animation for the route being pushed on top of /// this route. This animation lets this route coordinate with the entrance /// and exit transition of routes pushed on top of this route. Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> forwardAnimation, Widget child) { return child; } @override void didPush() { Focus.moveScopeTo(new GlobalObjectKey(this), context: navigator.context); super.didPush(); } // The API for subclasses to override - used by this class /// Whether you can dismiss this route by tapping the modal barrier. bool get barrierDismissable; /// The color to use for the modal barrier. If this is null, the barrier will /// be transparent. Color get barrierColor; // The API for _ModalScope and HeroController /// Whether this route is currently offstage. /// /// On the first frame of a route's entrance transition, the route is built /// [Offstage] using an animation progress of 1.0. The route is invisible and /// non-interactive, but each widget has its final size and position. This /// mechanism lets the [HeroController] determine the final local of any hero /// widgets being animated as part of the transition. bool get offstage => _offstage; bool _offstage = false; void set offstage (bool value) { if (_offstage == value) return; _offstage = value; _scopeKey.currentState?.setState(() { // _offstage is the value we're setting, but since there might not be a // state, we set it outside of this callback (which will only be called if // there's a state currently built). // _scopeKey is the key for the _ModalScope built in _buildModalScope(). // When we mark that state dirty, it'll rebuild itself, and use our // offstage (via their config.route.offstage) when building. }); } /// The build context for the subtree containing the primary content of this route. BuildContext get subtreeContext => _subtreeKey.currentContext; // Internals final GlobalKey<_ModalScopeState> _scopeKey = new GlobalKey<_ModalScopeState>(); final GlobalKey _subtreeKey = new GlobalKey(); final PageStorageBucket _storageBucket = new PageStorageBucket(); // one of the builders Widget _buildModalBarrier(BuildContext context) { Widget barrier; if (barrierColor != null) { assert(barrierColor != _kTransparent); Animation<Color> color = new ColorTween( begin: _kTransparent, end: barrierColor ).animate(new CurvedAnimation( parent: animation, curve: Curves.ease )); barrier = new AnimatedModalBarrier( color: color, dismissable: barrierDismissable ); } else { barrier = new ModalBarrier(dismissable: barrierDismissable); } assert(animation.status != AnimationStatus.dismissed); return new IgnorePointer( ignoring: animation.status == AnimationStatus.reverse, child: barrier ); } // one of the builders Widget _buildModalScope(BuildContext context) { return new _ModalScope( key: _scopeKey, route: this // calls buildTransitions() and buildPage(), defined above ); } @override List<WidgetBuilder> get builders => <WidgetBuilder>[ _buildModalBarrier, _buildModalScope ]; @override String toString() => '$runtimeType($settings, animation: $_animation)'; } /// A modal route that overlays a widget over the current route. abstract class PopupRoute<T> extends ModalRoute<T> { PopupRoute({ Completer<T> completer }) : super(completer: completer); @override bool get opaque => false; @override void didChangeNext(Route<dynamic> nextRoute) { assert(nextRoute is! PageRoute<dynamic>); super.didChangeNext(nextRoute); } }
32.743289
128
0.702741
9b9e89fdb47da71602a47fc086c3ffa856b07e9e
1,149
js
JavaScript
rvsscan2.0/WebContent/js/donuts.js
fangke-ray/RVS-OGZ
733365cb6af455c7bc977eb6867b21c41d25fc42
[ "Apache-2.0" ]
null
null
null
rvsscan2.0/WebContent/js/donuts.js
fangke-ray/RVS-OGZ
733365cb6af455c7bc977eb6867b21c41d25fc42
[ "Apache-2.0" ]
null
null
null
rvsscan2.0/WebContent/js/donuts.js
fangke-ray/RVS-OGZ
733365cb6af455c7bc977eb6867b21c41d25fc42
[ "Apache-2.0" ]
2
2019-03-01T02:27:57.000Z
2019-06-13T12:32:34.000Z
/* ============================================================ * donuts v1.0 by Larentis Mattia @spiritualGuru * http://www.larentis.eu/donuts/ * ============================================================ * Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 * ============================================================ */ $(function () { "use strict"; var colors = ['red', 'orange', 'yellow', 'green'] , segmentSize = 100.0 / colors.length; colors.push(colors[colors.length - 1]); var updateArrow = function ($this) { var percentage = $this.data('percentage'); if (percentage > 100) percentage = 100; else if (percentage < 0) percentage = 0; $this.css('transform', 'rotate(' + ((1.8 * percentage) - 90) + 'deg)'); $this.parent() .removeClass(colors.join(' ')) .addClass(colors[Math.floor(percentage / segmentSize)]); }; $('.donut-arrow') .each(function () { updateArrow($(this)) }) .bind('updatePercentage', function (e, amount) { $(this).data('percentage', amount); updateArrow($(this)); }); });
29.461538
75
0.497824
2df4e39cd88b646783d3c55c5a8d83f7bc329a4a
14,379
swift
Swift
CovidWatchTests/ExposureRiskModelTests.swift
AndreasInk/covidwatch-ios-en
9809305228e22c495f3ee16ef70d3011c62f4dc1
[ "Apache-2.0" ]
9
2020-07-09T04:34:35.000Z
2022-02-09T19:27:28.000Z
CovidWatchTests/ExposureRiskModelTests.swift
AndreasInk/covidwatch-ios-en
9809305228e22c495f3ee16ef70d3011c62f4dc1
[ "Apache-2.0" ]
28
2020-07-02T14:12:54.000Z
2020-10-12T00:53:20.000Z
CovidWatchTests/ExposureRiskModelTests.swift
AndreasInk/covidwatch-ios-en
9809305228e22c495f3ee16ef70d3011c62f4dc1
[ "Apache-2.0" ]
8
2020-07-07T14:19:23.000Z
2022-02-09T19:27:39.000Z
// // Created by Zsombor Szabo on 08/06/2020. // // import XCTest @testable import CovidWatch import ExposureNotification class ExposureRiskModelTests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func testAZExposureRiskModel() { let model = AZExposureRiskModel() let message = "Computed risk score does not match expected risk score" // ## Single exposure info tests ## // Scenario: "Sufficiently risky individual, 30 minutes close contact" XCTAssertEqual( model.computeRiskScore( forAttenuationDurations: [30.0 * 60.0, 0.0, 0.0], transmissionRiskLevel: 4 ), 1, // Expected message ) // Scenario: "Sufficiently risky individual, 30 minutes at med. attenuation" XCTAssertEqual( model.computeRiskScore( forAttenuationDurations: [0.0, 30.0 * 60.0, 0.0], transmissionRiskLevel: 4 ), 0, // Expected message ) // Scenario: "Sufficiently risky individual, 5 minutes close contact" XCTAssertEqual( model.computeRiskScore( forAttenuationDurations: [5.0 * 60.0, 0.0, 0.0], transmissionRiskLevel: 4 ), 0, // Expected message ) // Scenario: "Highest risk individual, 30 minutes at med. attenuation" XCTAssertEqual( model.computeRiskScore( forAttenuationDurations: [0.0, 30.0 * 60.0, 0.0], transmissionRiskLevel: 6 ), 0, // Expected message ) // Scenario: "Highest risk individual, 5 minutes close contact" XCTAssertEqual( model.computeRiskScore( forAttenuationDurations: [5.0 * 60.0, 0.0, 0.0], transmissionRiskLevel: 6 ), 0, // Expected message ) // Scenario: "Highest risk individual, 5 minutes at med attenuation" XCTAssertEqual( model.computeRiskScore( forAttenuationDurations: [0.0, 5.0 * 60.0, 0.0], transmissionRiskLevel: 6 ), 0, // Expected message ) // Scenario: "Highest risk individual, 30 minutes at long distance" XCTAssertEqual( model.computeRiskScore( forAttenuationDurations: [0.0, 0.0, 30.0 * 60.0], transmissionRiskLevel: 6 ), 0, // Expected message ) // Scenario: "Asymptomatic shedder at peak risk, 30 min at med. attenuation" XCTAssertEqual( model.computeRiskScore( forAttenuationDurations: [0.0, 30.0 * 60.0, 0.0], transmissionRiskLevel: 3 ), 0, // Expected message ) // Scenario: "Low shedder, 30 min at medium attenuation" XCTAssertEqual( model.computeRiskScore( forAttenuationDurations: [0.0, 30.0 * 60.0, 0.0], transmissionRiskLevel: 2 ), 0, // Expected message ) // Scenario: "Low shedder, 5 min at med. attenuation" XCTAssertEqual( model.computeRiskScore( forAttenuationDurations: [0.0, 5.0 * 60.0, 0.0], transmissionRiskLevel: 2 ), 0, // Expected message ) // Scenario: "Highest risk individual, 30 min in each bucket" XCTAssertEqual( model.computeRiskScore( forAttenuationDurations: [30.0 * 60.0, 30.0 * 60.0, 30.0 * 60.0], transmissionRiskLevel: 6 ), 5, // Expected message ) // Scenario: "Highest risk individual, 30 min in each bucket" XCTAssertEqual( model.computeRiskScore( forAttenuationDurations: [30.0 * 60.0, 30.0 * 60.0, 30.0 * 60.0], transmissionRiskLevel: 1 ), 0, // Expected message ) // Scenario: "Highest risk individual 15 minutes close contact" XCTAssertEqual( model.computeRiskScore( forAttenuationDurations: [15.0 * 60.0, 0.0, 0.0], transmissionRiskLevel: 6 ), 1, // Expected message ) // Scenario: "Lowest risk individual 15 minutes close contact" XCTAssertEqual( model.computeRiskScore( forAttenuationDurations: [15.0 * 60.0, 0.0, 0.0], transmissionRiskLevel: 1 ), 0, // Expected message ) // Scenario: "Highest risk individual 15 minutes long distance" XCTAssertEqual( model.computeRiskScore( forAttenuationDurations: [0.0, 0.0, 15.0 * 60.0], transmissionRiskLevel: 6 ), 0, // Expected message ) // Scenario: "Lowest risk individual 15 minutes long distance" XCTAssertEqual( model.computeRiskScore( forAttenuationDurations: [0.0, 0.0, 15.0 * 60.0], transmissionRiskLevel: 1 ), 0, // Expected message ) // ## Date risk level tests ## // Current date let day0 = Date() let day2 = Calendar.current.date(byAdding: .day, value: 2, to: day0)! let day3 = Calendar.current.date(byAdding: .day, value: 3, to: day0)! let day4 = Calendar.current.date(byAdding: .day, value: 4, to: day0)! let day18 = Calendar.current.date(byAdding: .day, value: 18, to: day0)! var exposures = [ ENExposureInfo( attenuationDurations: [5 * 60.0, 10 * 60.0, 5 * 60.0], attenuationValue: 0, date: day0, duration: 0, totalRiskScore: 0, transmissionRiskLevel: 6 ), ENExposureInfo( attenuationDurations: [10 * 60.0, 0.0, 0.0], attenuationValue: 0, date: day3, duration: 0, totalRiskScore: 0, transmissionRiskLevel: 6 ) ] XCTAssertEqual( model.computeRiskLevelValue(forExposureInfos: exposures, computeDate: day2), 0.689657, // Expected accuracy: 0.0001, message ) XCTAssertEqual( model.computeRiskLevelValue(forExposureInfos: exposures, computeDate: day3), 1.395461, // Expected accuracy: 0.0001, message ) XCTAssertEqual( model.computeRiskLevelValue(forExposureInfos: exposures, computeDate: day18), 0.436539, // Expected accuracy: 0.0001, message ) exposures = [ ENExposureInfo( attenuationDurations: [0.0, 0.0, 25 * 60.0], attenuationValue: 0, date: day3, duration: 0, totalRiskScore: 0, transmissionRiskLevel: 6 ), ENExposureInfo( attenuationDurations: [5 * 60.0, 20 * 60.0, 5 * 60.0], attenuationValue: 0, date: day3, duration: 0, totalRiskScore: 0, transmissionRiskLevel: 6 ), ENExposureInfo( attenuationDurations: [5 * 60.0, 0.0, 0.0], attenuationValue: 0, date: day3, duration: 0, totalRiskScore: 0, transmissionRiskLevel: 6 ) ] XCTAssertEqual( model.computeRiskLevelValue(forExposureInfos: exposures, computeDate: day2), 0.0, // Expected accuracy: 0.0001, message ) XCTAssertEqual( model.computeRiskLevelValue(forExposureInfos: exposures, computeDate: day4), 1.527189, // Expected accuracy: 0.0001, message ) XCTAssertEqual( model.computeRiskLevelValue(forExposureInfos: exposures, computeDate: day18), 0.520678, // Expected accuracy: 0.0001, message ) // ## Tranmission risk level tests ## let key = ENTemporaryExposureKey() key.keyData = Data(base64Encoded: "z2Cx9hdz2SlxZ8GEgqTYpA==")! key.rollingPeriod = 144 key.rollingStartNumber = day0.intervalNumber XCTAssertEqual( model.computeTransmissionRiskLevel(forTemporaryExposureKey: key, symptomsStartDate: Date().intervalNumber.date, testDate: nil, possibleInfectionDate: nil ), 6 // Expected ) key.rollingStartNumber = day2.intervalNumber XCTAssertEqual( model.computeTransmissionRiskLevel(forTemporaryExposureKey: key, symptomsStartDate: Date().intervalNumber.date, testDate: nil, possibleInfectionDate: nil), 6 // Expected ) key.rollingStartNumber = day3.intervalNumber XCTAssertEqual( model.computeTransmissionRiskLevel(forTemporaryExposureKey: key, symptomsStartDate: Date().intervalNumber.date, testDate: nil, possibleInfectionDate: nil), 5 // Expected ) key.rollingStartNumber = day18.intervalNumber XCTAssertEqual( model.computeTransmissionRiskLevel(forTemporaryExposureKey: key, symptomsStartDate: Date().intervalNumber.date, testDate: nil, possibleInfectionDate: nil), 0 // Expected ) let day2Ago = Calendar.current.date(byAdding: .day, value: -2, to: day0)! let day3Ago = Calendar.current.date(byAdding: .day, value: -3, to: day0)! let day4Ago = Calendar.current.date(byAdding: .day, value: -4, to: day0)! let day18Ago = Calendar.current.date(byAdding: .day, value: -18, to: day0)! key.rollingStartNumber = day2Ago.intervalNumber XCTAssertEqual( model.computeTransmissionRiskLevel(forTemporaryExposureKey: key, symptomsStartDate: Date().intervalNumber.date, testDate: nil, possibleInfectionDate: nil), 5 // Expected ) key.rollingStartNumber = day3Ago.intervalNumber XCTAssertEqual( model.computeTransmissionRiskLevel(forTemporaryExposureKey: key, symptomsStartDate: Date().intervalNumber.date, testDate: nil, possibleInfectionDate: nil), 3 // Expected ) key.rollingStartNumber = day4Ago.intervalNumber XCTAssertEqual( model.computeTransmissionRiskLevel(forTemporaryExposureKey: key, symptomsStartDate: Date().intervalNumber.date, testDate: nil, possibleInfectionDate: nil), 2 // Expected ) key.rollingStartNumber = day18Ago.intervalNumber XCTAssertEqual( model.computeTransmissionRiskLevel(forTemporaryExposureKey: key, symptomsStartDate: Date().intervalNumber.date, testDate: nil, possibleInfectionDate: nil), 0 // Expected ) key.rollingStartNumber = day0.intervalNumber XCTAssertEqual( model.computeTransmissionRiskLevel(forTemporaryExposureKey: key, symptomsStartDate: nil, testDate: Date().intervalNumber.date, possibleInfectionDate: nil ), 3 // Expected ) key.rollingStartNumber = day2Ago.intervalNumber XCTAssertEqual( model.computeTransmissionRiskLevel(forTemporaryExposureKey: key, symptomsStartDate: nil, testDate: Date().intervalNumber.date, possibleInfectionDate: nil), 2 // Expected ) key.rollingStartNumber = day3Ago.intervalNumber XCTAssertEqual( model.computeTransmissionRiskLevel(forTemporaryExposureKey: key, symptomsStartDate: nil, testDate: Date().intervalNumber.date, possibleInfectionDate: nil), 2 // Expected ) key.rollingStartNumber = day18Ago.intervalNumber XCTAssertEqual( model.computeTransmissionRiskLevel(forTemporaryExposureKey: key, symptomsStartDate: nil, testDate: Date().intervalNumber.date, possibleInfectionDate: nil), 0 // Expected ) key.rollingStartNumber = day0.intervalNumber XCTAssertEqual( model.computeTransmissionRiskLevel(forTemporaryExposureKey: key, symptomsStartDate: nil, testDate: day0, possibleInfectionDate: day3Ago ), 3 // Expected ) key.rollingStartNumber = day0.intervalNumber XCTAssertEqual( model.computeTransmissionRiskLevel(forTemporaryExposureKey: key, symptomsStartDate: nil, testDate: day2, possibleInfectionDate: day4Ago), 2 // Expected ) key.rollingStartNumber = day0.intervalNumber XCTAssertEqual( model.computeTransmissionRiskLevel(forTemporaryExposureKey: key, symptomsStartDate: nil, testDate: day3, possibleInfectionDate: day18Ago), 2 // Expected ) key.rollingStartNumber = day0.intervalNumber XCTAssertEqual( model.computeTransmissionRiskLevel(forTemporaryExposureKey: key, symptomsStartDate: nil, testDate: day18Ago, possibleInfectionDate: nil), 0 // Expected ) key.rollingStartNumber = day3Ago.intervalNumber XCTAssertEqual( model.computeTransmissionRiskLevel(forTemporaryExposureKey: key, symptomsStartDate: nil, testDate: day0, possibleInfectionDate: day4Ago ), 0 // Expected ) key.rollingStartNumber = day3Ago.intervalNumber XCTAssertEqual( model.computeTransmissionRiskLevel(forTemporaryExposureKey: key, symptomsStartDate: nil, testDate: day0, possibleInfectionDate: day3Ago ), 0 // Expected ) } }
35.857855
168
0.578343
2da2b1974cd398d19d6cdc7f2b3aed8d85592b7e
36,647
html
HTML
docs/_build/html/_modules/openassembly/pirate_topics/models.html
fragro/Open-Assembly
e9679ff5e7ae9881fa5781d763288ed2f40b014d
[ "BSD-3-Clause" ]
1
2015-11-05T08:22:19.000Z
2015-11-05T08:22:19.000Z
docs/_build/html/_modules/openassembly/pirate_topics/models.html
fragro/Open-Assembly
e9679ff5e7ae9881fa5781d763288ed2f40b014d
[ "BSD-3-Clause" ]
null
null
null
docs/_build/html/_modules/openassembly/pirate_topics/models.html
fragro/Open-Assembly
e9679ff5e7ae9881fa5781d763288ed2f40b014d
[ "BSD-3-Clause" ]
1
2018-02-03T18:25:41.000Z
2018-02-03T18:25:41.000Z
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>openassembly.pirate_topics.models &mdash; OA documentation</title> <link rel="stylesheet" href="../../../_static/default.css" type="text/css" /> <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../../../', VERSION: '', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../../../_static/jquery.js"></script> <script type="text/javascript" src="../../../_static/underscore.js"></script> <script type="text/javascript" src="../../../_static/doctools.js"></script> <link rel="author" title="About these documents" href="../../../about.html" /> <link rel="top" title="OA documentation" href="../../../index.html" /> <link rel="up" title="Module code" href="../../index.html" /> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../../../genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="../../../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li><a href="../../../index.html">OA documentation</a> &raquo;</li> <li><a href="../../index.html" accesskey="U">Module code</a> &raquo;</li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <h1>Source code for openassembly.pirate_topics.models</h1><div class="highlight"><pre> <span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">models</span> <span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">template</span> <span class="kn">from</span> <span class="nn">django.contrib</span> <span class="kn">import</span> <span class="n">admin</span> <span class="kn">from</span> <span class="nn">django.contrib.auth.models</span> <span class="kn">import</span> <span class="n">User</span> <span class="kn">from</span> <span class="nn">django.utils.translation</span> <span class="kn">import</span> <span class="n">ugettext</span> <span class="k">as</span> <span class="n">_</span> <span class="kn">from</span> <span class="nn">django.contrib.contenttypes.models</span> <span class="kn">import</span> <span class="n">ContentType</span> <span class="kn">from</span> <span class="nn">pirate_core.middleware</span> <span class="kn">import</span> <span class="n">TYPE_KEY</span><span class="p">,</span> <span class="n">OBJ_KEY</span><span class="p">,</span> <span class="n">START_KEY</span><span class="p">,</span> <span class="n">END_KEY</span><span class="p">,</span> <span class="n">DIM_KEY</span> <span class="kn">from</span> <span class="nn">django.template</span> <span class="kn">import</span> <span class="n">Context</span><span class="p">,</span> <span class="n">Template</span> <span class="kn">from</span> <span class="nn">celery.task</span> <span class="kn">import</span> <span class="n">task</span> <span class="kn">from</span> <span class="nn">tagging.models</span> <span class="kn">import</span> <span class="n">Tag</span><span class="p">,</span> <span class="n">TaggedItem</span> <span class="c"># First, define the Manager subclass.</span> <div class="viewcode-block" id="TopicManager"><a class="viewcode-back" href="../../../openassembly.pirate_topics.html#openassembly.pirate_topics.models.TopicManager">[docs]</a><span class="k">class</span> <span class="nc">TopicManager</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Manager</span><span class="p">):</span> <div class="viewcode-block" id="TopicManager.get_query_set"><a class="viewcode-back" href="../../../openassembly.pirate_topics.html#openassembly.pirate_topics.models.TopicManager.get_query_set">[docs]</a> <span class="k">def</span> <span class="nf">get_query_set</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="nb">super</span><span class="p">(</span><span class="n">TopicManager</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">get_query_set</span><span class="p">()</span><span class="o">.</span><span class="n">exclude</span><span class="p">(</span><span class="n">summary</span><span class="o">=</span><span class="s">&quot;__NULL__&quot;</span><span class="p">)</span> </div></div> <div class="viewcode-block" id="NullManager"><a class="viewcode-back" href="../../../openassembly.pirate_topics.html#openassembly.pirate_topics.models.NullManager">[docs]</a><span class="k">class</span> <span class="nc">NullManager</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Manager</span><span class="p">):</span> <div class="viewcode-block" id="NullManager.null_dimension"><a class="viewcode-back" href="../../../openassembly.pirate_topics.html#openassembly.pirate_topics.models.NullManager.null_dimension">[docs]</a> <span class="k">def</span> <span class="nf">null_dimension</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_or_create</span><span class="p">(</span><span class="n">summary</span><span class="o">=</span><span class="s">&quot;__NULL__&quot;</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span> </div></div> <span class="k">class</span> <span class="nc">Topic</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span> <span class="c">#Topic: Category to place issues, includes parent and child for hierarchical topics</span> <span class="n">summary</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">200</span><span class="p">,</span> <span class="n">unique</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="n">shortname</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">23</span><span class="p">,</span> <span class="n">unique</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="n">description</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">2500</span><span class="p">,</span> <span class="n">unique</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="n">submit_date</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateTimeField</span><span class="p">(</span><span class="s">&#39;date published&#39;</span><span class="p">,</span> <span class="n">auto_now_add</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="n">parent</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="s">&#39;self&#39;</span><span class="p">,</span> <span class="n">null</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">blank</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="n">children</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">(</span><span class="n">_</span><span class="p">(</span><span class="s">&#39;Children&#39;</span><span class="p">),</span> <span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="n">solutions</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">(</span><span class="n">_</span><span class="p">(</span><span class="s">&#39;Solution&#39;</span><span class="p">),</span> <span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="n">decisions</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">(</span><span class="n">_</span><span class="p">(</span><span class="s">&#39;Solution&#39;</span><span class="p">),</span> <span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span> <span class="n">more_info</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">200</span><span class="p">,</span> <span class="n">blank</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">null</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="n">is_featured</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">BooleanField</span><span class="p">(</span><span class="n">default</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span> <span class="n">location</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">200</span><span class="p">,</span> <span class="n">blank</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">null</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="n">slug</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">200</span><span class="p">,</span> <span class="n">blank</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">null</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="n">group_members</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">IntegerField</span><span class="p">(</span><span class="n">default</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span> <span class="n">objects</span> <span class="o">=</span> <span class="n">NullManager</span><span class="p">()</span> <span class="n">clean_objects</span> <span class="o">=</span> <span class="n">TopicManager</span><span class="p">()</span> <span class="k">def</span> <span class="nf">__unicode__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">shortname</span> <span class="k">def</span> <span class="nf">get_verbose_name</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="s">&#39;topic&#39;</span> <span class="k">def</span> <span class="nf">is_root</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="bp">True</span> <span class="k">def</span> <span class="nf">get_absolute_url</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">t</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s">&quot;{</span><span class="si">% lo</span><span class="s">ad pp_url%}{% pp_url template=&#39;group.html&#39; object=object %}&quot;</span><span class="p">)</span> <span class="n">c</span> <span class="o">=</span> <span class="n">Context</span><span class="p">({</span><span class="s">&quot;object&quot;</span><span class="p">:</span> <span class="bp">self</span><span class="p">})</span> <span class="k">return</span> <span class="n">t</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="k">def</span> <span class="nf">get_absolute_list_url</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="n">t</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s">&quot;{</span><span class="si">% lo</span><span class="s">ad pp_url%}{% pp_url template=&#39;issues.html&#39; object=object start=0 end=10 dimension=&#39;n&#39; %}&quot;</span><span class="p">)</span> <span class="n">c</span> <span class="o">=</span> <span class="n">Context</span><span class="p">({</span><span class="s">&quot;object&quot;</span><span class="p">:</span> <span class="bp">self</span><span class="p">})</span> <span class="k">return</span> <span class="n">t</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">c</span><span class="p">)</span> <span class="k">class</span> <span class="nc">MyGroup</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span> <span class="n">topic</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Topic</span><span class="p">,</span> <span class="n">blank</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">null</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="n">user</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">User</span><span class="p">)</span> <span class="n">created_dt</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">DateTimeField</span><span class="p">(</span><span class="n">blank</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">null</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">auto_now_add</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="k">def</span> <span class="nf">__unicode__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="nb">str</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">topic</span><span class="p">)</span> <span class="o">+</span> <span class="s">&quot; : &quot;</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">user</span><span class="o">.</span><span class="n">username</span><span class="p">)</span> <span class="k">class</span> <span class="nc">GroupSettings</span><span class="p">(</span><span class="n">models</span><span class="o">.</span><span class="n">Model</span><span class="p">):</span> <span class="n">topic</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">ForeignKey</span><span class="p">(</span><span class="n">Topic</span><span class="p">,</span> <span class="n">blank</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">null</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="n">stream</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">30</span><span class="p">,</span> <span class="n">blank</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">null</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">help_text</span><span class="o">=</span><span class="s">&quot;Account name to Embed stream into navigation.&quot;</span><span class="p">)</span> <span class="n">stream_provider</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">CharField</span><span class="p">(</span><span class="n">max_length</span><span class="o">=</span><span class="mi">30</span><span class="p">,</span> <span class="n">blank</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">null</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">help_text</span><span class="o">=</span><span class="s">&quot;Provider of streaming service.&quot;</span><span class="p">)</span> <span class="n">open_group</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">BooleanField</span><span class="p">(</span><span class="n">default</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">help_text</span><span class="o">=</span><span class="s">&quot;If the group is open anyone can join, if it&#39;s closed they must be invited&quot;</span><span class="p">)</span> <span class="n">percent_reporting</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">FloatField</span><span class="p">(</span><span class="n">default</span><span class="o">=.</span><span class="mi">7</span><span class="p">,</span> <span class="n">help_text</span><span class="o">=</span><span class="s">&quot;Percentage of members required to vote for pushing a set of solutions/answers to a ranked vote. Value represents a percentage for instance .7 is 70</span><span class="si">% o</span><span class="s">f Members voting&quot;</span><span class="p">)</span> <span class="n">consensus_percentage</span> <span class="o">=</span> <span class="n">models</span><span class="o">.</span><span class="n">FloatField</span><span class="p">(</span><span class="n">default</span><span class="o">=.</span><span class="mi">8</span><span class="p">,</span> <span class="n">help_text</span><span class="o">=</span><span class="s">&quot;For policies or proposals, what percentage of votes constitutes consensus when no blocks are present?&quot;</span><span class="p">)</span> <span class="k">def</span> <span class="nf">__unicode__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">return</span> <span class="nb">str</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">topic</span><span class="p">)</span> <div class="viewcode-block" id="get_users"><a class="viewcode-back" href="../../../openassembly.pirate_topics.html#openassembly.pirate_topics.models.get_users">[docs]</a><span class="k">def</span> <span class="nf">get_users</span><span class="p">(</span><span class="n">parent</span><span class="p">,</span> <span class="n">start</span><span class="p">,</span> <span class="n">end</span><span class="p">,</span> <span class="n">dimension</span><span class="p">,</span> <span class="n">ctype_list</span><span class="p">):</span> <span class="c">#if this object is a topic, get group members</span> <span class="k">if</span> <span class="n">parent</span> <span class="o">!=</span> <span class="bp">None</span> <span class="ow">and</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">parent</span><span class="p">,</span> <span class="n">Topic</span><span class="p">):</span> <span class="n">user_list</span> <span class="o">=</span> <span class="n">MyGroup</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">topic</span><span class="o">=</span><span class="n">parent</span><span class="p">)</span> <span class="k">if</span> <span class="n">dimension</span> <span class="o">==</span> <span class="s">&#39;n&#39;</span><span class="p">:</span> <span class="n">user_list</span> <span class="o">=</span> <span class="n">user_list</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;-created_dt&#39;</span><span class="p">)</span> <span class="n">count</span> <span class="o">=</span> <span class="n">user_list</span><span class="o">.</span><span class="n">count</span><span class="p">()</span> <span class="k">if</span> <span class="n">start</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span> <span class="ow">and</span> <span class="n">end</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span> <span class="n">user_list</span> <span class="o">=</span> <span class="n">user_list</span><span class="p">[</span><span class="nb">int</span><span class="p">(</span><span class="n">start</span><span class="p">):</span><span class="nb">int</span><span class="p">(</span><span class="n">end</span><span class="p">)]</span> <span class="k">return</span> <span class="n">user_list</span><span class="p">,</span> <span class="n">count</span> <span class="k">else</span><span class="p">:</span> <span class="n">user_list</span> <span class="o">=</span> <span class="n">User</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">is_active</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="n">count</span> <span class="o">=</span> <span class="n">user_list</span><span class="o">.</span><span class="n">count</span><span class="p">()</span> <span class="k">if</span> <span class="n">dimension</span> <span class="o">==</span> <span class="s">&#39;n&#39;</span><span class="p">:</span> <span class="n">user_list</span> <span class="o">=</span> <span class="n">user_list</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;-date_joined&#39;</span><span class="p">)</span> <span class="k">if</span> <span class="n">dimension</span> <span class="o">==</span> <span class="s">&#39;j&#39;</span><span class="p">:</span> <span class="n">user_list</span> <span class="o">=</span> <span class="n">user_list</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;-last_login&#39;</span><span class="p">)</span> <span class="k">if</span> <span class="n">dimension</span> <span class="o">==</span> <span class="s">&#39;a&#39;</span><span class="p">:</span> <span class="n">user_list</span> <span class="o">=</span> <span class="n">user_list</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;username&#39;</span><span class="p">)</span> <span class="k">if</span> <span class="n">start</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span> <span class="ow">and</span> <span class="n">end</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span> <span class="n">user_list</span> <span class="o">=</span> <span class="n">user_list</span><span class="p">[</span><span class="nb">int</span><span class="p">(</span><span class="n">start</span><span class="p">):</span><span class="nb">int</span><span class="p">(</span><span class="n">end</span><span class="p">)]</span> <span class="k">return</span> <span class="n">user_list</span><span class="p">,</span> <span class="n">count</span> </div> <div class="viewcode-block" id="get_topics"><a class="viewcode-back" href="../../../openassembly.pirate_topics.html#openassembly.pirate_topics.models.get_topics">[docs]</a><span class="k">def</span> <span class="nf">get_topics</span><span class="p">(</span><span class="n">parent</span><span class="p">,</span> <span class="n">start</span><span class="p">,</span> <span class="n">end</span><span class="p">,</span> <span class="n">dimension</span><span class="p">,</span> <span class="n">ctype_list</span><span class="p">):</span> <span class="c">#dimension can be children or number of group members</span> <span class="k">if</span> <span class="n">parent</span> <span class="o">!=</span> <span class="bp">None</span> <span class="ow">and</span> <span class="nb">isinstance</span><span class="p">(</span><span class="n">parent</span><span class="p">,</span> <span class="n">Topic</span><span class="p">):</span> <span class="n">topic_list</span> <span class="o">=</span> <span class="n">Topic</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">parent</span><span class="o">=</span><span class="n">parent</span><span class="p">)</span> <span class="k">else</span><span class="p">:</span> <span class="n">topic_list</span> <span class="o">=</span> <span class="n">Topic</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="n">parent</span><span class="o">=</span><span class="n">Topic</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">null_dimension</span><span class="p">())</span> <span class="k">if</span> <span class="n">dimension</span> <span class="o">==</span> <span class="s">&#39;c&#39;</span><span class="p">:</span> <span class="n">topic_list</span> <span class="o">=</span> <span class="n">topic_list</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;-children&#39;</span><span class="p">)</span> <span class="k">elif</span> <span class="n">dimension</span> <span class="o">==</span> <span class="s">&#39;n&#39;</span><span class="p">:</span> <span class="n">topic_list</span> <span class="o">=</span> <span class="n">topic_list</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;-submit_date&#39;</span><span class="p">)</span> <span class="k">elif</span> <span class="n">dimension</span> <span class="o">==</span> <span class="s">&#39;o&#39;</span><span class="p">:</span> <span class="n">topic_list</span> <span class="o">=</span> <span class="n">topic_list</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;submit_date&#39;</span><span class="p">)</span> <span class="k">elif</span> <span class="n">dimension</span> <span class="o">==</span> <span class="s">&#39;h&#39;</span><span class="p">:</span> <span class="n">topic_list</span> <span class="o">=</span> <span class="n">topic_list</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;-group_members&#39;</span><span class="p">)</span> <span class="k">elif</span> <span class="n">dimension</span> <span class="o">==</span> <span class="s">&#39;a&#39;</span><span class="p">:</span> <span class="n">topic_list</span> <span class="o">=</span> <span class="n">topic_list</span><span class="o">.</span><span class="n">order_by</span><span class="p">(</span><span class="s">&#39;-summary&#39;</span><span class="p">)</span> <span class="n">count</span> <span class="o">=</span> <span class="n">topic_list</span><span class="o">.</span><span class="n">count</span><span class="p">()</span> <span class="k">print</span> <span class="n">dimension</span> <span class="k">if</span> <span class="n">start</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span> <span class="ow">and</span> <span class="n">end</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span> <span class="n">topic_list</span> <span class="o">=</span> <span class="n">topic_list</span><span class="p">[</span><span class="nb">int</span><span class="p">(</span><span class="n">start</span><span class="p">):</span><span class="nb">int</span><span class="p">(</span><span class="n">end</span><span class="p">)]</span> <span class="k">return</span> <span class="n">topic_list</span><span class="p">,</span> <span class="n">count</span> </div> <span class="nd">@task</span><span class="p">(</span><span class="n">ignore_result</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="k">def</span> <span class="nf">add_group_tag</span><span class="p">(</span><span class="n">obj_pk</span><span class="p">,</span> <span class="n">ctype_pk</span><span class="p">,</span> <span class="n">tag</span><span class="p">):</span> <span class="n">ctype</span> <span class="o">=</span> <span class="n">ContentType</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="n">ctype_pk</span><span class="p">)</span> <span class="n">obj</span> <span class="o">=</span> <span class="n">ctype</span><span class="o">.</span><span class="n">get_object_for_this_type</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="n">obj_pk</span><span class="p">)</span> <span class="n">root</span> <span class="o">=</span> <span class="n">get_root</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span> <span class="c">#also add to the objects group so we can display group specific tags</span> <span class="n">Tag</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">add_tag</span><span class="p">(</span><span class="n">root</span><span class="p">,</span> <span class="n">tag</span><span class="p">)</span> <span class="nd">@task</span><span class="p">(</span><span class="n">ignore_result</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span> <span class="k">def</span> <span class="nf">del_group_tag</span><span class="p">(</span><span class="n">obj_pk</span><span class="p">,</span> <span class="n">ctype_pk</span><span class="p">,</span> <span class="n">tag</span><span class="p">):</span> <span class="n">ctype</span> <span class="o">=</span> <span class="n">ContentType</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="n">ctype_pk</span><span class="p">)</span> <span class="n">obj</span> <span class="o">=</span> <span class="n">ctype</span><span class="o">.</span><span class="n">get_object_for_this_type</span><span class="p">(</span><span class="n">pk</span><span class="o">=</span><span class="n">obj_pk</span><span class="p">)</span> <span class="n">root</span> <span class="o">=</span> <span class="n">get_root</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span> <span class="c">#also add to the objects group so we can display group specific tags</span> <span class="n">taggedobj</span> <span class="o">=</span> <span class="n">TaggedItem</span><span class="o">.</span><span class="n">objects</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="n">tag_name</span><span class="o">=</span><span class="n">tag</span><span class="p">,</span> <span class="n">object_id</span><span class="o">=</span><span class="n">root</span><span class="o">.</span><span class="n">pk</span><span class="p">)</span> <span class="n">taggedobj</span><span class="o">.</span><span class="n">delete</span><span class="p">()</span> <div class="viewcode-block" id="get_root"><a class="viewcode-back" href="../../../openassembly.pirate_topics.html#openassembly.pirate_topics.models.get_root">[docs]</a><span class="k">def</span> <span class="nf">get_root</span><span class="p">(</span><span class="n">root</span><span class="p">):</span> <span class="k">if</span> <span class="n">root</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span> <span class="k">try</span><span class="p">:</span> <span class="n">parent</span> <span class="o">=</span> <span class="n">root</span><span class="o">.</span><span class="n">parent</span> <span class="k">except</span><span class="p">:</span> <span class="k">try</span><span class="p">:</span> <span class="n">parent</span> <span class="o">=</span> <span class="n">root</span><span class="o">.</span><span class="n">content_object</span> <span class="k">except</span><span class="p">:</span> <span class="k">return</span> <span class="bp">None</span> <span class="k">while</span> <span class="n">parent</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span> <span class="k">if</span> <span class="n">parent</span><span class="o">.</span><span class="n">summary</span> <span class="o">==</span> <span class="s">&#39;__NULL__&#39;</span><span class="p">:</span> <span class="k">return</span> <span class="n">root</span> <span class="n">root</span> <span class="o">=</span> <span class="n">parent</span> <span class="n">parent</span> <span class="o">=</span> <span class="n">parent</span><span class="o">.</span><span class="n">parent</span> </pre></div></div> </div> </div> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="../../../search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="../../../genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="../../../py-modindex.html" title="Python Module Index" >modules</a> |</li> <li><a href="../../../index.html">OA documentation</a> &raquo;</li> <li><a href="../../index.html" >Module code</a> &raquo;</li> </ul> </div> <div class="footer"> &copy; Copyright 2012, Frank Grove. Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3. </div> </body> </html>
141.494208
645
0.624717
b34f749b4a3ec4cb163501e15b78d770303983dd
3,479
swift
Swift
swift-owner/Extensions/UIImageExtension.swift
chrronger/swift-owner
a88735ac848fbed15d48607d9fd0ae24dcebdb30
[ "Apache-2.0" ]
null
null
null
swift-owner/Extensions/UIImageExtension.swift
chrronger/swift-owner
a88735ac848fbed15d48607d9fd0ae24dcebdb30
[ "Apache-2.0" ]
null
null
null
swift-owner/Extensions/UIImageExtension.swift
chrronger/swift-owner
a88735ac848fbed15d48607d9fd0ae24dcebdb30
[ "Apache-2.0" ]
null
null
null
// // UIImageExtension.swift // swift-owner // // Created by sen on 16/9/18. // Copyright © 2016年 sen. All rights reserved. // import UIKit extension UIImage { /* 指定宽度等比缩放 - parameter newWidth: 需要缩放的宽度 - returns: 返回缩放后的图片 */ func equalScaleWithWidth(newWidth: CGFloat) -> CGSize { // 新的高度 / 新的宽度 = 原来的高度 / 原来的宽度 let newHeight = newWidth * (size.height * scale) / (size.width * scale) let newSize = CGSize(width: newWidth, height: newHeight) return newSize } /** 指定高度等比缩放 - parameter newHeight: 需要缩放的高度 - returns: 返回缩放后的图片 */ func equalScaleWithWHeight(newHeight: CGFloat) -> CGSize { // 新的高度 / 新的宽度 = 原来的高度 / 原来的宽度 let newWidth = newHeight / (size.height * scale) * (size.width * scale) let newSize = CGSize(width: newWidth, height: newHeight) return newSize } /** 缩放图片到指定的尺寸 - parameter newSize: 需要缩放的尺寸 - returns: 返回缩放后的图片 */ func resizeImageWithNewSize(newSize: CGSize) -> UIImage { var rect = CGRect.zero let oldSize = self.size if newSize.width / newSize.height > oldSize.width / oldSize.height { rect.size.width = newSize.height * oldSize.width / oldSize.height rect.size.height = newSize.height rect.origin.x = (newSize.width - rect.size.width) * 0.5 rect.origin.y = 0 } else { rect.size.width = newSize.width rect.size.height = newSize.width * oldSize.height / oldSize.width rect.origin.x = 0 rect.origin.y = (newSize.height - rect.size.height) * 0.5 } UIGraphicsBeginImageContext(newSize) let context = UIGraphicsGetCurrentContext() context!.setFillColor(UIColor.clear.cgColor) UIRectFill(CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height)) self.draw(in: rect) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage! } /** 等比例缩小, 缩小到宽度等于300 - returns: 缩小的图片 */ func scaleImage() -> UIImage { var newWidth: CGFloat = 700 if size.width < 400 { return self } else if size.width < 500 { newWidth = 500 } else if size.width < 600 { newWidth = 600 } // 等比例缩放 // newHeight / newWidth = 原来的高度 / 原来的宽度 let newHeight = newWidth * size.height / size.width let newSize = CGSize(width: newWidth, height: newHeight) // 准备图片的上下文 UIGraphicsBeginImageContext(newSize) // 将当前图片绘制到rect上面 draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight)) // 从上下文获取绘制好的图片 let newImage = UIGraphicsGetImageFromCurrentImageContext() // 关闭上下文 UIGraphicsEndImageContext() return newImage! } // UIImage with downloadable content class func contentOfURL(link: String) -> UIImage { let url = URL.init(string: link)! var image = UIImage() do{ let data = try Data.init(contentsOf: url) image = UIImage.init(data: data)! } catch _ { print("error downloading images") } return image } }
27.179688
84
0.556769
ee67ea423720a28d7b3d4f8bf6bcef19f226191f
35
dart
Dart
frontend/base/app/lib/feature/video/model/model.dart
nicelogic/warmth
e60bfd0f183c3d5971be6eceb26f24cff8284fb6
[ "Apache-2.0" ]
null
null
null
frontend/base/app/lib/feature/video/model/model.dart
nicelogic/warmth
e60bfd0f183c3d5971be6eceb26f24cff8284fb6
[ "Apache-2.0" ]
null
null
null
frontend/base/app/lib/feature/video/model/model.dart
nicelogic/warmth
e60bfd0f183c3d5971be6eceb26f24cff8284fb6
[ "Apache-2.0" ]
null
null
null
export 'media_stream_state.dart';
11.666667
33
0.8
9109f56f001c3e1aee516522f808ed40739ea799
472
sql
SQL
query/ram/ram_password_policy_expire_90.sql
turbot/steampipe-mod-alicloud-compliance
4a71c25dcd73545d385cb28479a0eb37c6ae90d0
[ "Apache-2.0" ]
6
2021-07-04T12:00:35.000Z
2022-02-20T07:47:50.000Z
query/ram/ram_password_policy_expire_90.sql
turbot/steampipe-mod-alicloud-compliance
4a71c25dcd73545d385cb28479a0eb37c6ae90d0
[ "Apache-2.0" ]
14
2021-06-18T00:35:30.000Z
2021-08-11T10:43:57.000Z
query/ram/ram_password_policy_expire_90.sql
turbot/steampipe-mod-alicloud-compliance
4a71c25dcd73545d385cb28479a0eb37c6ae90d0
[ "Apache-2.0" ]
1
2022-02-17T04:48:36.000Z
2022-02-17T04:48:36.000Z
select -- Required Columns 'acs:ram::' || a.account_id as resource, case when max_password_age <= 90 then 'ok' else 'alarm' end as status, case when max_password_age is null then 'Password expiration not set.' else 'Password expiration set to ' || max_password_age || ' days.' end as reason, -- Additional Dimensions a.account_id from alicloud_account as a left join alicloud_ram_password_policy as pol on a.account_id = pol.account_id;
29.5
81
0.713983
ddd7514880fded6ff409390a7243064fb494627c
2,748
php
PHP
app/Exports/AWB/RedeemRewardExport.php
stevenheryanto/thriveApi
0795e8f96ceacfbea0f5455ad893a90328fabb5b
[ "MIT" ]
null
null
null
app/Exports/AWB/RedeemRewardExport.php
stevenheryanto/thriveApi
0795e8f96ceacfbea0f5455ad893a90328fabb5b
[ "MIT" ]
null
null
null
app/Exports/AWB/RedeemRewardExport.php
stevenheryanto/thriveApi
0795e8f96ceacfbea0f5455ad893a90328fabb5b
[ "MIT" ]
null
null
null
<?php namespace App\Exports\AWB; use Throwable; use App\Models\AWB\awb_trn_reward_claim; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Storage; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Support\Responsable; use Maatwebsite\Excel\Concerns\Exportable; use Maatwebsite\Excel\Concerns\FromQuery; use Maatwebsite\Excel\Concerns\WithHeadings; use Maatwebsite\Excel\Concerns\WithMapping; use Maatwebsite\Excel\Excel; class RedeemRewardExport implements Responsable, FromQuery, WithHeadings, WithMapping, ShouldQueue { use Exportable; private $fileName = 'report_redeem_reward.xlsx'; private $writerType = Excel::XLSX; private $headers = [ 'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ]; public function failed(Throwable $th): void { Storage::disk('s3')->put('learn/log/RedeemRewardExport_'.date('Ymdhms').'.txt', $th, 'public'); } public function headings(): array { return [ 'Log Id', 'User Id', 'User Account', 'User Name', 'User Email', 'Claim Date', 'Claim Points', 'Reward', ]; } public function map($result): array { return [ $result->id, $result->user_id, $result->user_account, $result->user_name, $result->user_email, $result->claim_date, $result->claim_point, $result->reward, ]; } public function __construct($platform_id, $filter_period_from, $filter_period_to) { $this->platform_id = $platform_id; $this->filter_period_from = $filter_period_from; $this->filter_period_to = $filter_period_to; } public function query() { return awb_trn_reward_claim::query() ->select( 'awb_trn_reward_claim.id', 'b.id as user_id', 'd.claim_point', 'd.title as reward', 'awb_trn_reward_claim.claim_date', 'b.name as user_name', 'b.account as user_account', 'b.email as user_email', 'b.directorate as user_function' ) ->join('users as b', 'b.id', '=', 'awb_trn_reward_claim.user_created') ->leftJoin('awb_trn_reward as d', 'd.id', '=', 'awb_trn_reward_claim.reward_id') ->where('awb_trn_reward_claim.platform_id', '=', $this->platform_id) ->when(isset($this->filter_period_from, $this->filter_period_to), function ($query) { $query->whereBetween(DB::raw('convert(awb_trn_reward_claim.claim_date,date)'), [$this->filter_period_from, $this->filter_period_to]); }); } }
32.714286
149
0.621543
4036ceec260476e38a6dd863482ac8a3999e73a5
374
py
Python
mialab/classifier/__init__.py
mrunibe/MIALab
82d3f0f4344620fd22384108b022730cde9c7215
[ "Apache-2.0" ]
2
2018-12-05T09:03:28.000Z
2019-01-02T15:31:35.000Z
mialab/classifier/__init__.py
riedj1/MIALab
82d3f0f4344620fd22384108b022730cde9c7215
[ "Apache-2.0" ]
null
null
null
mialab/classifier/__init__.py
riedj1/MIALab
82d3f0f4344620fd22384108b022730cde9c7215
[ "Apache-2.0" ]
1
2018-10-20T21:27:55.000Z
2018-10-20T21:27:55.000Z
""" ====================================== Classifier (:mod:`classifier` package) ====================================== This package provides supervised machine learning classifiers. The decision forest module (:mod:`classifier.decision_forest`) -------------------------------------------------------------- .. automodule:: classifier.decision_forest :members: """
26.714286
62
0.475936
0ccd4f9fbf2b5d4dda1cc40e475be33aa9ef28bc
320
py
Python
scraping/test001.py
flaviogf/Exemplos
fc666429f6e90c388e201fb7b7d5801e3c25bd25
[ "MIT" ]
null
null
null
scraping/test001.py
flaviogf/Exemplos
fc666429f6e90c388e201fb7b7d5801e3c25bd25
[ "MIT" ]
5
2019-12-29T04:58:10.000Z
2021-03-11T04:35:15.000Z
scraping/test001.py
flaviogf/Exemplos
fc666429f6e90c388e201fb7b7d5801e3c25bd25
[ "MIT" ]
null
null
null
import pandas import requests with open('avengers.csv', 'w') as file: file_url = 'https://raw.githubusercontent.com/fivethirtyeight/data/master/avengers/avengers.csv' response = requests.get(file_url) file.write(response.text) with open('avengers.csv', 'r') as file: data_frame = pandas.read_csv(file)
29.090909
100
0.73125
2705887b6a46d2c9d679cbe529157410f5a8f265
1,373
h
C
src/DescentEngine/src/SoundEngine/SoundEngineSDL.h
poseidn/KungFoo
35fa33bd5a9abb40ecf485db2fc038ca52c48a2d
[ "CC-BY-3.0", "CC0-1.0", "CC-BY-4.0" ]
7
2016-01-28T14:28:10.000Z
2021-09-03T17:33:37.000Z
src/DescentEngine/src/SoundEngine/SoundEngineSDL.h
poseidn/KungFoo
35fa33bd5a9abb40ecf485db2fc038ca52c48a2d
[ "CC-BY-3.0", "CC0-1.0", "CC-BY-4.0" ]
1
2016-03-19T11:34:36.000Z
2016-03-24T21:35:06.000Z
src/DescentEngine/src/SoundEngine/SoundEngineSDL.h
poseidn/KungFoo
35fa33bd5a9abb40ecf485db2fc038ca52c48a2d
[ "CC-BY-3.0", "CC0-1.0", "CC-BY-4.0" ]
3
2016-03-10T14:23:40.000Z
2019-03-17T16:21:21.000Z
/* Copyright (C) 2016 Thomas Hauth. All Rights Reserved. * Written by Thomas Hauth (Thomas.Hauth@web.de) This file is part of Kung Foo Barracuda. Kung Foo Barracuda is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Kung Foo Barracuda is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Kung Foo Barracuda. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "../Cpp11.h" #include "SoundEngineAbstract.h" class SoundEngineSDL: public SoundEngineAbstract { public: // todo: move to an intialize call SoundEngineSDL(); virtual ~SoundEngineSDL(); virtual PlayHandle playSound(SoundPtr snd, float direction = 0.0f) CPP11_OVERRIDE; virtual PlayHandle playMusic(MusicPtr msc) CPP11_OVERRIDE; virtual void stopPlay(PlayHandle const& ph, float fadeOutTime = -1.0f) CPP11_OVERRIDE; private: PlayHandle m_fixedMusicHandle; }; class SoundEngine CPP11_FINAL : public SoundEngineSDL { public: virtual ~SoundEngine() { } };
28.020408
87
0.775674
0c96e86ca1a15c8434d2cbc7e56c0f749d433cc7
2,885
py
Python
test/sca/test_rpa.py
scrambler-crypto/pyecsca
491abfb548455669abd470382a48dcd07b2eda87
[ "MIT" ]
null
null
null
test/sca/test_rpa.py
scrambler-crypto/pyecsca
491abfb548455669abd470382a48dcd07b2eda87
[ "MIT" ]
null
null
null
test/sca/test_rpa.py
scrambler-crypto/pyecsca
491abfb548455669abd470382a48dcd07b2eda87
[ "MIT" ]
null
null
null
from unittest import TestCase from parameterized import parameterized from pyecsca.ec.context import local from pyecsca.ec.mult import LTRMultiplier, BinaryNAFMultiplier, WindowNAFMultiplier, LadderMultiplier, \ DifferentialLadderMultiplier from pyecsca.ec.params import get_params from pyecsca.sca.re.rpa import MultipleContext class MultipleContextTests(TestCase): def setUp(self): self.secp128r1 = get_params("secg", "secp128r1", "projective") self.base = self.secp128r1.generator self.coords = self.secp128r1.curve.coordinate_model self.add = self.coords.formulas["add-1998-cmo"] self.dbl = self.coords.formulas["dbl-1998-cmo"] self.neg = self.coords.formulas["neg"] self.scale = self.coords.formulas["z"] @parameterized.expand([ ("10", 10), ("2355498743", 2355498743), ("325385790209017329644351321912443757746", 325385790209017329644351321912443757746), ("13613624287328732", 13613624287328732) ]) def test_basic(self, name, scalar): mult = LTRMultiplier(self.add, self.dbl, self.scale, always=False, complete=False, short_circuit=True) with local(MultipleContext()) as ctx: mult.init(self.secp128r1, self.base) mult.multiply(scalar) muls = list(ctx.points.values()) self.assertEqual(muls[-1], scalar) def test_precomp(self): bnaf = BinaryNAFMultiplier(self.add, self.dbl, self.neg, self.scale) with local(MultipleContext()) as ctx: bnaf.init(self.secp128r1, self.base) muls = list(ctx.points.values()) self.assertListEqual(muls, [1, -1]) wnaf = WindowNAFMultiplier(self.add, self.dbl, self.neg, 3, self.scale) with local(MultipleContext()) as ctx: wnaf.init(self.secp128r1, self.base) muls = list(ctx.points.values()) self.assertListEqual(muls, [1, 2, 3, 5]) def test_ladder(self): curve25519 = get_params("other", "Curve25519", "xz") base = curve25519.generator coords = curve25519.curve.coordinate_model ladd = coords.formulas["ladd-1987-m"] dadd = coords.formulas["dadd-1987-m"] dbl = coords.formulas["dbl-1987-m"] scale = coords.formulas["scale"] ladd_mult = LadderMultiplier(ladd, dbl, scale) with local(MultipleContext()) as ctx: ladd_mult.init(curve25519, base) ladd_mult.multiply(1339278426732672313) muls = list(ctx.points.values()) self.assertEqual(muls[-2], 1339278426732672313) dadd_mult = DifferentialLadderMultiplier(dadd, dbl, scale) with local(MultipleContext()) as ctx: dadd_mult.init(curve25519, base) dadd_mult.multiply(1339278426732672313) muls = list(ctx.points.values()) self.assertEqual(muls[-2], 1339278426732672313)
41.214286
110
0.664471
26150a9f577f67505e0b3617aed7f574dc20e647
3,781
java
Java
src/main/java/com/sap/dsc/aas/lib/aml/amlx/AmlxPackage.java
Daespen/aas-transformation-library
4399e4d770154b52c8d06edb211223e6bcd84d8d
[ "Apache-2.0" ]
1
2021-09-29T08:18:25.000Z
2021-09-29T08:18:25.000Z
src/main/java/com/sap/dsc/aas/lib/aml/amlx/AmlxPackage.java
Daespen/aas-transformation-library
4399e4d770154b52c8d06edb211223e6bcd84d8d
[ "Apache-2.0" ]
5
2021-10-19T15:00:07.000Z
2021-12-16T10:24:38.000Z
src/main/java/com/sap/dsc/aas/lib/aml/amlx/AmlxPackage.java
Daespen/aas-transformation-library
4399e4d770154b52c8d06edb211223e6bcd84d8d
[ "Apache-2.0" ]
4
2021-09-24T13:29:03.000Z
2022-02-27T18:53:32.000Z
/* SPDX-FileCopyrightText: (C)2021 SAP SE or an affiliate company and aas-transformation-library contributors. All rights reserved. SPDX-License-Identifier: Apache-2.0 */ package com.sap.dsc.aas.lib.aml.amlx; import java.util.List; import java.util.stream.Collectors; import java.util.stream.StreamSupport; import org.apache.poi.openxml4j.exceptions.InvalidFormatException; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackageRelationship; public class AmlxPackage { /** * The amlx file is an OPC (open packaging conventions) file */ private final OPCPackage opcPackage; private final List<AmlxPackagePart> listOfNonAmlFiles; public AmlxPackage(OPCPackage opcPackage) throws InvalidFormatException { this.opcPackage = opcPackage; this.listOfNonAmlFiles = this.loadNonAmlFiles(); } // @formatter:off /** * Searches the /_rels/.rels file for a list of files that are not any of the following types: .aml .xsd. * * For filtering, the relationship type URI in the .rels file is used. For example, consider a .amlx package with the following structure: * * <pre> * _rels/.rels --&gt; Not returned * root.aml --&gt; Not returned (this file can be retrieved by {@link #getRootAmlFile() getRootAmlFile}). * CAEX_ClassModel_V.3.0.xsd --&gt; Not returned * files/document.pdf --&gt; Returned * files/textFile.txt --&gt; Returned * lib/amlLibrary.aml --&gt; Not returned * </pre> * * @return List of content files, e.g. PDF, CAD, Step5 */ // @formatter:off public List<AmlxPackagePart> getNonAmlFiles() { return this.listOfNonAmlFiles; } /** * Gets the root .aml file as defined by the /_rels/.rels file * * @return The root element of the AMLX package */ public AmlxPackagePart getRootAmlFile() { PackagePart rootPart = opcPackage.getPartsByRelationshipType(AmlxRelationshipType.ROOT.getURI()).get(0); return AmlxPackagePart.fromPackagePart(rootPart); } protected OPCPackage getOpcPackage() { return opcPackage; } protected final List<AmlxPackagePart> loadNonAmlFiles() throws InvalidFormatException { try { return StreamSupport.stream(opcPackage.getRelationships().spliterator(), false) .filter(relationship -> !AmlxRelationshipType.isAmlType(relationship.getRelationshipType())) .map(this::getAmlxPackagePartByRelationship) .collect(Collectors.toList()); } catch (IllegalStateException ex) { final Throwable throwable = ex.getCause(); if (throwable instanceof InvalidFormatException) throw (InvalidFormatException) throwable; throw ex; } } protected AmlxPackagePart getAmlxPackagePartByRelationship(PackageRelationship relationship) { // We can't use opcPackage.getPart(relationship): // That function only checks the relationship type and returns the first match // Instead, check the complete URI // Target URI example: "/files/document.pdf" final String relationshipTargetUri = relationship.getTargetURI().toString(); try { return opcPackage.getParts().stream() // .filter(part -> part.getPartName().getName().equals(relationshipTargetUri)) // .findFirst() // .map(AmlxPackagePart::fromPackagePart).orElse(null); } catch (InvalidFormatException ex) { throw new IllegalStateException(ex); } } }
38.581633
142
0.658291
110febe57fd55f57e128bf3293f3f2b0598ef606
1,836
dart
Dart
lib/utils/image_provider.dart
winterdl/kinoko
9cb040e2efcbe08377826c4bb7518cfd0ced0564
[ "MIT" ]
119
2020-09-22T07:40:55.000Z
2022-03-28T18:28:02.000Z
lib/utils/image_provider.dart
winterdl/kinoko
9cb040e2efcbe08377826c4bb7518cfd0ced0564
[ "MIT" ]
32
2021-07-19T12:03:00.000Z
2022-03-25T06:39:04.000Z
lib/utils/image_provider.dart
winterdl/kinoko
9cb040e2efcbe08377826c4bb7518cfd0ced0564
[ "MIT" ]
14
2021-07-16T14:38:35.000Z
2022-03-06T00:25:37.000Z
import 'dart:convert'; import 'dart:io'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:flutter_svg_provider/flutter_svg_provider.dart'; import 'package:glib/main/project.dart'; import 'package:crypto/crypto.dart'; import 'neo_cache_manager.dart'; String generateMd5(String input) { return md5.convert(utf8.encode(input)).toString(); } ImageProvider makeImageProvider(String url) { Uri uri = Uri.parse(url); if (RegExp(r"\.svg", caseSensitive: false).hasMatch(uri.path)) { if (uri.scheme == "http" || uri.scheme == "https") { return Svg.network(url); } else if (url[0] == '/') { return Svg.file(url); } else { return Svg.asset(url); } } else { if (uri.scheme == "http" || uri.scheme == "https") { return NeoImageProvider( uri: uri, cacheManager: NeoCacheManager.defaultManager ); } else if (url[0] == '/') { return FileImage(File(url)); } else { return AssetImage(url); } } } ImageProvider projectImageProvider(Project project, [String defaultUrl]) { String icon = project?.icon; if (icon?.isNotEmpty == true) { return makeImageProvider(icon); } if (project?.isValidated == true) { String iconpath = project.fullpath + "/icon.png"; File icon = new File(iconpath); if (icon.existsSync()) { return FileImage(icon); } else if (project.icon.isNotEmpty) { return makeImageProvider(project.icon); } } if (defaultUrl?.isNotEmpty == true) { return makeImageProvider(defaultUrl); } return NeoImageProvider( uri: Uri.parse("https://www.tinygraphs.com/squares/${generateMd5(project?.url ?? "null")}?theme=bythepool&numcolors=3&size=180&fmt=jpg"), cacheManager: NeoCacheManager.defaultManager ); }
29.142857
143
0.662309
5e9937441f0c4614314037243cc6799caa1743fd
2,817
ps1
PowerShell
generate/definitions/VARIANTS.ps1
leojonathanoh/php7-fpm-mysqli-alpine
91a57f539b86461cb5ae17f8f506c2a70df85f97
[ "Apache-2.0" ]
1
2021-02-24T17:08:51.000Z
2021-02-24T17:08:51.000Z
generate/definitions/VARIANTS.ps1
leojonathanoh/php7-fpm-mysqli-alpine
91a57f539b86461cb5ae17f8f506c2a70df85f97
[ "Apache-2.0" ]
1
2021-02-15T16:42:52.000Z
2021-02-15T16:52:28.000Z
generate/definitions/VARIANTS.ps1
theohbrothers/docker-php
91a57f539b86461cb5ae17f8f506c2a70df85f97
[ "Apache-2.0" ]
1
2019-04-29T05:37:54.000Z
2019-04-29T05:37:54.000Z
# Docker image variants' definitions $local:VARIANTS_BASE_IMAGE_TAGS = @( '8.0.1-fpm-alpine3.13' '7.4.14-fpm-alpine3.13' '7.3.26-fpm-alpine3.13' '7.2.34-fpm-alpine3.12' ) $local:VARIANTS_MATRIX = @( $local:VARIANTS_BASE_IMAGE_TAGS | % { @{ base_image_tag = $_ subvariants = @( @{ components = @( 'opcache' ); tag_as_latest = if ($_ -eq $local:VARIANTS_BASE_IMAGE_TAGS[0]) { $true } else { $false } } @{ components = @( 'mysqli' ) } @{ components = @( 'gd' ) } @{ components = @( 'pdo' ) } @{ components = @( 'memcached' ) } @{ components = @( 'sockets' ) } @{ components = @( 'xdebug' ) } @{ components = @( 'opcache', 'mysqli', 'gd' ) } @{ components = @( 'opcache', 'mysqli', 'gd', 'pdo' ) } @{ components = @( 'opcache', 'mysqli', 'gd', 'pdo', 'memcached' ) } @{ components = @( 'opcache', 'mysqli', 'gd', 'pdo', 'memcached', 'sockets' ) } @{ components = @( 'opcache', 'mysqli', 'gd', 'xdebug' ) } @{ components = @( 'opcache', 'mysqli', 'gd', 'pdo', 'xdebug' ) } @{ components = @( 'opcache', 'mysqli', 'gd', 'pdo', 'memcached', 'xdebug' ) } @{ components = @( 'opcache', 'mysqli', 'gd', 'pdo', 'memcached', 'sockets', 'xdebug' ) } ) } } ) $VARIANTS = @( foreach ($variant in $VARIANTS_MATRIX){ foreach ($subVariant in $variant['subvariants']) { @{ # Metadata object _metadata = @{ base_image_tag = $variant['base_image_tag'] components = $subVariant['components'] } # Docker image tag. E.g. '7.2-fpm-alpine3.10-opcache', '7.2-fpm-alpine3.10-mysqli' tag = @( $variant['base_image_tag'] $subVariant['components'] | ? { $_ } ) -join '-' tag_as_latest = if ( $subVariant.Contains('tag_as_latest') ) { $subVariant['tag_as_latest'] } else { $false } } } } ) # Docker image variants' definitions (shared) $VARIANTS_SHARED = @{ buildContextFiles = @{ templates = @{ 'Dockerfile' = @{ common = $true includeHeader = $true includeFooter = $true passes = @( @{ variables = @{} } ) } } } } # Send definitions down the pipeline $VARIANTS
37.065789
138
0.423145
743688aa8eed6d4d6553c2734f583ee91cdb3512
13,594
html
HTML
themes/admin/nav/index.html
AesopL/isheying
721e990370aed72f5e1600d1a25c23188e83bc1a
[ "Apache-2.0" ]
null
null
null
themes/admin/nav/index.html
AesopL/isheying
721e990370aed72f5e1600d1a25c23188e83bc1a
[ "Apache-2.0" ]
null
null
null
themes/admin/nav/index.html
AesopL/isheying
721e990370aed72f5e1600d1a25c23188e83bc1a
[ "Apache-2.0" ]
null
null
null
{extend name="base" /} {block name="body"} <div class="panel"> <div class="panel-heading"> <h5>导航管理</h5> </div> <div class="panel-body"> <div class="pull-right"> <button class="btn btn-primary" data-toggle="modal" data-target="#addNav">添加导航</button> </div> <form action="#" method="post"> <div class="search"> 搜索名称: <input type="text" class="text" name="topic" placeholder="搜索名称" style="width:150px;"> &nbsp;搜索分类: <div class="btn-group btn-dropdown"> <button type="button" class="btn btn-default dropdown-toggle btn-sm" data-toggle="dropdown"> <span class="drop-topic">请选择类别</span> <span class="caret"></span> </button> <ul class="dropdown-menu"> <li> <a href="#">请选择类别</a> </li> <li class="divider"></li> <li> <a href="#">分类一</a> </li> <li> <a href="#">分类二</a> </li> </ul> </div> &nbsp;是否启用: <div class="btn-group btn-dropdown"> <button type="button" class="btn btn-default dropdown-toggle btn-sm" data-toggle="dropdown"> <span class="drop-topic">请选择</span> <span class="caret"></span> </button> <ul class="dropdown-menu"> <li> <a href="#">请选择</a> </li> <li class="divider"></li> <li> <a href="#">启用</a> </li> <li> <a href="#">禁用</a> </li> </ul> </div> &nbsp; <button type="submit" value="查询" class="btn btn-primary-outline btn-xs"> <i class="icon-search"></i>&nbsp;查询</button> </div> </form> <table class="table table-bordered table-hover table-striped"> <thead> <tr> <th width="40" class="text-center"> <input type="checkbox" name="checkbox"> </th> <th width="50" class="text-center">ID</th> <th width="200" class="text-center">名称</th> <th width="200" class="text-center">排序</th> <th width="100" class="text-center">状态</th> <th width="140" class="text-center">操作</th> </tr> </thead> <tbody> {foreach name="navs_level" item="vo"} <tr> <td class="text-center"> <input type="checkbox" name="BatchRemove" data-id="{$vo.id}"> </td> <td class="text-center">{$vo.id}</td> <td class="text-center">{neq name="vo.level" value="1"}|{php}for($i=1;$i <$vo[ 'level'];$i++)echo "--";{/php}{/neq}{$vo.name}</td> <td class="text-center">{$vo.sort}</td> <td class="text-center">{$vo.status}</td> <td class="text-center"> <button type="button" class="btn btn-sm btn-success btn_edit" data-id="{$vo.id}"> <i class="icon-edit"></i> 编辑 </button> <button type="button" class="btn btn-sm btn-danger btn-delete" data-id="{$vo.id}"> <i class="icon-trash"></i> 删除 </button> </td> </tr> {/foreach} </tbody> <tfoot> <tr> <!-- <th width="40" class="text-center"> <input type="checkbox" name="checkbox"> </th> --> <th colspan="8"> <button type="button" class="btn btn-danger btn-batch-remove"> <i class="icon-trash"></i> 批量删除</button> <div class="pull-right"> </div> </th> </tr> </tfoot> </table> </div> </div> <!-- 添加modal层 --> <div class="modal form-modal fade" id="addNav"> <div class="modal-dialog"> <div class="modal-content"> <form action="save" id="addForm" onsubmit="return false"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true">×</span> <span class="sr-only">关闭</span> </button> <h4 class="modal-title">添加导航</h4> </div> <div class="modal-body"> <div class="form-group"> <label for="">上级菜单</label> <select class="form-control" name="pid"> <option value="0">一级菜单</option> {foreach name="navs_level" item="vo"} <option value="{$vo.id}">{neq name="vo.level" value="1"}|{php}for($i=1;$i <$vo[ 'level'];$i++){echo ' ----';}{/php}{/neq} {$vo.name}</option> {/foreach} </select> </div> <div class="form-group"> <label for="name">名称</label> <input type="text" name="name" class="form-control" id="name" placeholder=""> </div> <div class="form-group"> <label for="alias">别名</label> <input type="text" name="alias" class="form-control" id="alias" placeholder=""> </div> <div class="form-group"> <label for="link">链接</label> <input type="text" name="link" class="form-control" id="link" placeholder=""> </div> <div class="form-group"> <label for="icon">图标</label> <input type="text" name="icon" class="form-control" id="icon" placeholder=""> </div> <div class="form-group"> <label for="target">跳转方式</label> <select name="target" id="" class="form-control"> <option value="_blank">新标签</option> <option value="_self">当前页</option> </select> </div> <div class="form-group"> <label for="status">启用 <input type="radio" name="status" value="1" id="status" title="显示" checked="checked"> </label> <label for="status">禁用 <input type="radio" name="status" value="0" id="status" title="隐藏"> </label> </div> <div class="form-group"> <label for="sort">排序</label> <input type="text" name="sort" class="form-control" id="sort" placeholder=""> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> <button type="button" class="btn btn-primary" id="addSubmit">保存</button> </div> </form> </div> </div> </div> <!-- 添加modal层 --> <div class="modal form-modal fade" id="editNav"> <div class="modal-dialog"> <div class="modal-content"> <form action="save" id="editForm" onsubmit="return false"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal"> <span aria-hidden="true">×</span> <span class="sr-only">关闭</span> </button> <h4 class="modal-title">编辑导航</h4> </div> <div class="modal-body"> <div class="form-group"> <label for="">上级菜单</label> <select class="form-control" name="pid" id="edit-pid"> <option value="0">一级菜单</option> {foreach name="navs_level" item="vo"} <option value="{$vo.id}">{neq name="vo.level" value="1"}|{php}for($i=1;$i <$vo[ 'level'];$i++){echo ' ----';}{/php}{/neq} {$vo.name}</option> {/foreach} </select> </div> <div class="form-group"> <label for="name">名称</label> <input type="text" name="name" class="form-control" id="edit-name" placeholder=""> </div> <div class="form-group"> <label for="alias">别名</label> <input type="text" name="alias" class="form-control" id="edit-alias" placeholder=""> </div> <div class="form-group"> <label for="link">链接</label> <input type="text" name="link" class="form-control" id="edit-link" placeholder=""> </div> <div class="form-group"> <label for="icon">图标</label> <input type="text" name="icon" class="form-control" id="edit-icon" placeholder=""> </div> <div class="form-group"> <label for="target">跳转方式</label> <select name="target" id="edit-target" class="form-control"> <option value="_blank">新标签</option> <option value="_self">当前页</option> </select> </div> <div class="form-group"> <label for="status">启用 <input type="radio" name="status" value="1" id="status" title="显示" checked="checked"> </label> <label for="status">禁用 <input type="radio" name="status" value="0" id="status" title="隐藏"> </label> </div> <div class="form-group"> <label for="sort">排序</label> <input type="text" name="sort" class="form-control" id="edit-sort" placeholder=""> </div> </div> <div class="modal-footer"> <input type="text" name="id" value="" id="edit-id" hidden> <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button> <button type="button" class="btn btn-primary" id="editSubmit">保存</button> </div> </form> </div> </div> </div> {/block} {block name="scriptnext"} <script type='text/javascript'> $(document).ready(function () { //按钮触发数据的修改 $(".btn_edit").on('click', function () { // 根据id通过ajax获取点击列的数据 var id = $(this).attr('data-id'); $.ajax({ url: 'edit', async: false,//同步,会阻塞操作 type: 'get',//GET data: { id: id }, complete: function (msg) { //console.log('完成了'); }, success: function (result) { // console.log(result); if (result.code == 200 && result.data !== '') { $("#editNav").modal('show'); $('#edit-pid option').each(function () { if ($(this).val() == result['data']['pid']) { $(this).prop('selected', true); } }); $('#edit-id').val(result['data']['id']); $("#edit-name").val(result['data']['name']); $("#edit-sort").val(result['data']['sort']); $("#edit-alias").val(result['data']['alias']); $("#edit-icon").attr("data-value", result['data']['icon']); console.log(result['data']['icon']); if (result['data']['status'] == 0) { $("#edit-status").attr("checked", true); } } else { $("#editNav").modal('hide'); layer.msg(result.msg, { icon: 2 }); } } }); }); }); </script> {/block}
44.717105
114
0.382816
99f2954e62a9242038cc058a9d89dc219409dfda
5,397
dart
Dart
lib/utils/utils_task_timeline.dart
msi-shamim/pendu_driver
45636f47f60afb97d61084916e21032dce8a3a5e
[ "BSD-3-Clause" ]
null
null
null
lib/utils/utils_task_timeline.dart
msi-shamim/pendu_driver
45636f47f60afb97d61084916e21032dce8a3a5e
[ "BSD-3-Clause" ]
null
null
null
lib/utils/utils_task_timeline.dart
msi-shamim/pendu_driver
45636f47f60afb97d61084916e21032dce8a3a5e
[ "BSD-3-Clause" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:pendu_driver/screen/screen.dart'; import 'package:pendu_driver/utils/utils.dart'; import 'package:timelines/timelines.dart'; // ignore: must_be_immutable class TaskTimeLineUtils extends StatefulWidget { int screenValue = 0; TaskTimeLineUtils({this.screenValue}); @override _TaskTimeLineUtilsState createState() => _TaskTimeLineUtilsState(); } class _TaskTimeLineUtilsState extends State<TaskTimeLineUtils> { final double hightValue = 12; @override Widget build(BuildContext context) { Widget _buildCheckBox({Color boxColor}) { return Container( padding: EdgeInsets.all(3.0), height: 20, width: 20, decoration: BoxDecoration( border: Border.all(color: boxColor, width: 2.5), borderRadius: BorderRadius.circular(4.0), color: Colors.white), child: Container(color: boxColor), ); } Widget _buildUnCheckBox({Color boxColor}) { return Container( padding: EdgeInsets.all(3.0), height: 20, width: 20, decoration: BoxDecoration( border: Border.all(color: boxColor, width: 2.5), borderRadius: BorderRadius.circular(4.0), color: Colors.white), ); } return Container( //padding: EdgeInsets.only(top: 10.0), alignment: Alignment.center, height: 150, width: 150, child: Column( mainAxisAlignment: MainAxisAlignment.center, // crossAxisAlignment: CrossAxisAlignment.center, children: [ //1 InkWell( onTap: () { setState(() { widget.screenValue = 1; }); }, child: TimelineTile( direction: Axis.vertical, nodeAlign: TimelineNodeAlign.start, oppositeContents: null, contents: Container( padding: EdgeInsets.only(left: 15.0), child: Text('Driving to pickup'), ), node: TimelineNode( indicator: ContainerIndicator( child: (widget.screenValue >= 1) ? _buildCheckBox(boxColor: Pendu.color('F97A7A')) : _buildUnCheckBox(boxColor: Pendu.color('F97A7A'))), endConnector: SizedBox( height: hightValue, child: DashedLineConnector( thickness: 1, dash: 2, gap: 2, color: Pendu.color('707070'), ), ), ), ), ), //2 InkWell( onTap: () { setState(() { widget.screenValue = 2; }); Navigator.push( context, MaterialPageRoute(builder: (context) => ShoppingPage()), ); }, child: TimelineTile( direction: Axis.vertical, nodeAlign: TimelineNodeAlign.start, oppositeContents: null, contents: Container( padding: EdgeInsets.only(left: 15.0), child: Text('Shopping started'), ), node: TimelineNode( indicator: ContainerIndicator( child: (widget.screenValue >= 2) ? _buildCheckBox(boxColor: Pendu.color('FFCE8A')) : _buildUnCheckBox(boxColor: Pendu.color('FFCE8A'))), startConnector: SizedBox( height: hightValue, child: DashedLineConnector( thickness: 1, dash: 2, gap: 2, color: Pendu.color('707070'), ), ), endConnector: SizedBox( height: hightValue, child: DashedLineConnector( thickness: 1, dash: 2, gap: 2, color: Pendu.color('707070'), ), ), ), ), ), //3 InkWell( onTap: () { setState(() { widget.screenValue = 3; }); }, child: TimelineTile( direction: Axis.vertical, nodeAlign: TimelineNodeAlign.start, oppositeContents: null, contents: Container( padding: EdgeInsets.only(left: 15.0), child: Text('Strat delivery'), ), node: TimelineNode( indicator: ContainerIndicator( child: (widget.screenValue >= 3) ? _buildCheckBox(boxColor: Pendu.color('29ABE2')) : _buildUnCheckBox(boxColor: Pendu.color('29ABE2'))), startConnector: SizedBox( height: hightValue, child: DashedLineConnector( thickness: 1, dash: 2, gap: 2, color: Pendu.color('707070'), ), ), ), ), ), ], ), ); } }
31.934911
77
0.468779
917b68b274fe3722ef72cd737eed2e60866ba99e
351
asm
Assembly
oeis/099/A099915.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/099/A099915.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/099/A099915.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A099915: Expansion of (1+4x)/((1-x)(1-10x)). ; Submitted by Jamie Morken(m1) ; 1,15,155,1555,15555,155555,1555555,15555555,155555555,1555555555,15555555555,155555555555,1555555555555,15555555555555,155555555555555,1555555555555555,15555555555555555,155555555555555555 seq $0,42 ; Unary representation of natural numbers. div $0,5 mul $0,7 add $0,1
39
190
0.792023
648a63a543303f87b18a6af5e6384fbdc64151b7
234
sql
SQL
source/database/migrations/mig_000051/upd_t_notificaciones.sql
DamyGenius/risk
2106f12185db80db024181be5a02f5e076e5ecfc
[ "MIT" ]
null
null
null
source/database/migrations/mig_000051/upd_t_notificaciones.sql
DamyGenius/risk
2106f12185db80db024181be5a02f5e076e5ecfc
[ "MIT" ]
null
null
null
source/database/migrations/mig_000051/upd_t_notificaciones.sql
DamyGenius/risk
2106f12185db80db024181be5a02f5e076e5ecfc
[ "MIT" ]
null
null
null
UPDATE t_notificaciones a SET a.id_usuario = to_number(regexp_substr(a.suscripcion, '\d+')) WHERE regexp_like(a.suscripcion, '(' || '&&user_' || ')\d+', 'i') AND a.suscripcion NOT LIKE '%&&!user_%' AND a.id_usuario IS NULL;
39
68
0.65812
6eafdb5adcb43f31eb7c4709b2afe4095ef5fc09
3,285
swift
Swift
Prework/SettingsViewController.swift
jonestrada7/tipCalculator
7b740a829b66e4fbdf7a21ebf1d27714baa57b4c
[ "Apache-2.0" ]
null
null
null
Prework/SettingsViewController.swift
jonestrada7/tipCalculator
7b740a829b66e4fbdf7a21ebf1d27714baa57b4c
[ "Apache-2.0" ]
null
null
null
Prework/SettingsViewController.swift
jonestrada7/tipCalculator
7b740a829b66e4fbdf7a21ebf1d27714baa57b4c
[ "Apache-2.0" ]
null
null
null
// // SettingsViewController.swift // Prework // // Created by Jonathan Estrada on 1/23/21. // import UIKit class SettingsViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var defaultTip: UITextField! @IBOutlet weak var bgColorPicker: UIPickerView! var bgColors: [String] = [String]() override func viewDidLoad() { super.viewDidLoad() // Connecting data self.bgColorPicker.reloadAllComponents() self.bgColorPicker.delegate = self self.bgColorPicker.dataSource = self bgColors = ["simple", "ocean", "sky", "coffee", "forest"] // Do any additional setup after loading the view. let defaults = UserDefaults.standard defaults.set(0.15, forKey: "defaultTipVal") defaults.set("simple", forKey: "colorScheme") defaults.synchronize() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ @IBAction func saveSettings(_ sender: Any) { let defTip = Double(defaultTip.text!) ?? 0 let defaults = UserDefaults.standard defaults.set(defTip, forKey: "defaultTipVal") defaults.synchronize() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return bgColors.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! { let color: String = String(bgColors[row]) return color } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){ let color: String = bgColors[pickerView.selectedRow(inComponent: 0)] // Set color scheme of SettingsViewController switch color { case "ocean": self.view.backgroundColor = #colorLiteral(red: 0.1411764771, green: 0.3960784376, blue: 0.5647059083, alpha: 1) case "sky": self.view.backgroundColor = #colorLiteral(red: 0.4745098054, green: 0.8392156959, blue: 0.9764705896, alpha: 1) case "coffee": self.view.backgroundColor = #colorLiteral(red: 1, green: 0.7504402995, blue: 0.4987524748, alpha: 1) case "forest": self.view.backgroundColor = #colorLiteral(red: 0.5843137503, green: 0.8235294223, blue: 0.4196078479, alpha: 1) default: self.view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0) } // Save color scheme for use in main ViewController let defaults = UserDefaults.standard defaults.set(color, forKey: "colorScheme") defaults.synchronize() self.bgColorPicker.reloadAllComponents() } }
34.578947
123
0.640487
34685fd120155bbfc663ee93be3ed518536db112
559
asm
Assembly
divison_remainder.asm
shaswata56/MIPS-32-Assembly
86c7b00840899d1cf301226df5a4d4a0ccfb2563
[ "Unlicense" ]
3
2019-02-28T22:08:12.000Z
2020-09-27T13:21:47.000Z
divison_remainder.asm
shaswata56/MIPS-32-Assembly
86c7b00840899d1cf301226df5a4d4a0ccfb2563
[ "Unlicense" ]
null
null
null
divison_remainder.asm
shaswata56/MIPS-32-Assembly
86c7b00840899d1cf301226df5a4d4a0ccfb2563
[ "Unlicense" ]
null
null
null
.data input1: .asciiz "Input first number: " input2: .asciiz "Input second number: " output: .asciiz "The quotient is: " remainder: .asciiz "\nThe remainder is: " point: .asciiz "." .text main: li $v0, 4 la $a0, input1 syscall li $v0, 5 syscall move $t1, $v0 li $v0, 4 la $a0, input2 syscall li $v0, 5 syscall move $t2, $v0 div $t1, $t2 mfhi $t3 mflo $t4 li $v0, 4 la $a0, output syscall li $v0, 1 move $a0, $t4 syscall li $v0, 4 la $a0, remainder syscall li $v0, 1 move $a0, $t3 syscall li $v0, 10 syscall
11.893617
41
0.604651
fbb86ab253fbf634435e8b2d6b6bd1c71f66482a
3,361
java
Java
src/main/java/cn/chuanwise/xiaoming/resource/ResourceManager.java
qfys521/XiaoMingBot
88d7b46c69e316d48b73429668fa93806afbd9f4
[ "Apache-2.0" ]
null
null
null
src/main/java/cn/chuanwise/xiaoming/resource/ResourceManager.java
qfys521/XiaoMingBot
88d7b46c69e316d48b73429668fa93806afbd9f4
[ "Apache-2.0" ]
null
null
null
src/main/java/cn/chuanwise/xiaoming/resource/ResourceManager.java
qfys521/XiaoMingBot
88d7b46c69e316d48b73429668fa93806afbd9f4
[ "Apache-2.0" ]
null
null
null
package cn.chuanwise.xiaoming.resource; import cn.chuanwise.xiaoming.bot.XiaoMingBot; import cn.chuanwise.xiaoming.contact.contact.XiaoMingContact; import cn.chuanwise.xiaoming.object.ModuleObject; import cn.chuanwise.xiaoming.contact.message.Message; import cn.chuanwise.common.preservable.Preservable; import net.mamoe.mirai.contact.Contact; import net.mamoe.mirai.message.code.MiraiCode; import net.mamoe.mirai.message.data.Image; import net.mamoe.mirai.message.data.MessageChain; import net.mamoe.mirai.message.data.SingleMessage; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.Objects; public interface ResourceManager extends ModuleObject, Preservable { default Message useResources(Message message, XiaoMingContact contact) { message.setMessageChain(useResources(message.getMessageChain(), contact.getMiraiContact())); return message; } MessageChain useResources(MessageChain messages, Contact miraiContact); default Message saveResources(Message message) throws IOException { saveResources(message.getMessageChain()); return message; } default MessageChain saveResources(MessageChain messages) throws IOException { for (SingleMessage singleMessage : messages) { if (singleMessage instanceof Image) { final Image image = (Image) singleMessage; if (Objects.isNull(getImage(image.getImageId()))) { saveImage(image); } } } return messages; } default String saveResources(String messages) throws IOException { saveResources(MiraiCode.deserializeMiraiCode(messages)); return messages; } default Image getImage(String id, XiaoMingContact contact) { return getImage(id, contact.getMiraiContact()); } Image getImage(String id, Contact miraiContact); File saveImage(Image image) throws IOException; File getImage(String id); File getImagesDirectory(); Map<String, Long> getImageLastVisitTimes(); default Long getImageLastVisitTime(String id) { return getImageLastVisitTimes().get(id); } void setResourceDirectory(File resourceDirectory); default int removeBefore(long time) { int sizeBeforeRemove = getImageLastVisitTimes().size(); getImageLastVisitTimes().entrySet().removeIf(entry -> { final String id = entry.getKey(); final long lastVisitTime = entry.getValue(); final boolean shouldRemove = time > lastVisitTime; return shouldRemove && getImage(id).delete(); }); return sizeBeforeRemove - getImageLastVisitTimes().size(); } @Override default void flushBotReference(XiaoMingBot xiaoMingBot) { final File imagesDirectory = getImagesDirectory(); imagesDirectory.mkdirs(); boolean added = false; for (File file : imagesDirectory.listFiles()) { if (file.isFile()) { if (Objects.isNull(getImageLastVisitTime(file.getName()))) { getImageLastVisitTimes().put(file.getName(), file.lastModified()); added = true; } } } if (added) { getXiaoMingBot().getFileSaver().readyToSave(this); } } }
33.949495
100
0.675989
e77a0b888bae8aa53f15408b1e78cb5744b08cc5
1,472
js
JavaScript
Drivers/CMSIS/docs/Core_A/html/search/groups_1.js
mlecriva/TrustZone_stm32l5xx
e924d22bb2b11ac363613e372850fb1896ca3a71
[ "MIT" ]
null
null
null
Drivers/CMSIS/docs/Core_A/html/search/groups_1.js
mlecriva/TrustZone_stm32l5xx
e924d22bb2b11ac363613e372850fb1896ca3a71
[ "MIT" ]
null
null
null
Drivers/CMSIS/docs/Core_A/html/search/groups_1.js
mlecriva/TrustZone_stm32l5xx
e924d22bb2b11ac363613e372850fb1896ca3a71
[ "MIT" ]
1
2021-09-25T16:44:11.000Z
2021-09-25T16:44:11.000Z
var searchData= [ ['configuration_20base_20address_20register_20_28cbar_29',['Configuration Base Address Register (CBAR)',['../group__CMSIS__CBAR.html',1,'']]], ['cbar_20bits',['CBAR Bits',['../group__CMSIS__CBAR__BITS.html',1,'']]], ['cache_20and_20branch_20predictor_20maintenance_20operations',['Cache and branch predictor maintenance operations',['../group__CMSIS__CBPM.html',1,'']]], ['counter_20frequency_20register_20_28cntfrq_29',['Counter Frequency register (CNTFRQ)',['../group__CMSIS__CNTFRQ.html',1,'']]], ['core_20peripherals',['Core Peripherals',['../group__CMSIS__Core__FunctionInterface.html',1,'']]], ['core_20register_20access',['Core Register Access',['../group__CMSIS__core__register.html',1,'']]], ['coprocessor_20access_20control_20register_20_28cpacr_29',['Coprocessor Access Control Register (CPACR)',['../group__CMSIS__CPACR.html',1,'']]], ['cpacr_20bits',['CPACR Bits',['../group__CMSIS__CPACR__BITS.html',1,'']]], ['cpacr_20cp_20field_20values',['CPACR CP field values',['../group__CMSIS__CPACR__CP.html',1,'']]], ['current_20program_20status_20register_20_28cpsr_29',['Current Program Status Register (CPSR)',['../group__CMSIS__CPSR.html',1,'']]], ['cpsr_20bits',['CPSR Bits',['../group__CMSIS__CPSR__BITS.html',1,'']]], ['cpsr_20m_20field_20values',['CPSR M field values',['../group__CMSIS__CPSR__M.html',1,'']]], ['compiler_20control',['Compiler Control',['../group__comp__cntrl__gr.html',1,'']]] ];
86.588235
157
0.726902
6b4ec38ca7f6a479a6da3ec9eddd593edff68b67
353
sql
SQL
sql/_02_user_authorization/_01_user/_003_member/cases/1012.sql
Zhaojia2019/cubrid-testcases
475a828e4d7cf74aaf2611fcf791a6028ddd107d
[ "BSD-3-Clause" ]
9
2016-03-24T09:51:52.000Z
2022-03-23T10:49:47.000Z
sql/_02_user_authorization/_01_user/_003_member/cases/1012.sql
Zhaojia2019/cubrid-testcases
475a828e4d7cf74aaf2611fcf791a6028ddd107d
[ "BSD-3-Clause" ]
173
2016-04-13T01:16:54.000Z
2022-03-16T07:50:58.000Z
sql/_02_user_authorization/_01_user/_003_member/cases/1012.sql
Zhaojia2019/cubrid-testcases
475a828e4d7cf74aaf2611fcf791a6028ddd107d
[ "BSD-3-Clause" ]
38
2016-03-24T17:10:31.000Z
2021-10-30T22:55:45.000Z
--[er]Add member to noexists group autocommit off; call login('dba','') on class db_user; call find_user('dba')on class db_user to admin; call login('dba','') on class db_user; call add_user ('test_user') on class db_user; call add_member('user1') ON admin; DROP user user1; call drop_user ('test_user') on class db_user; rollback; autocommit on;
19.611111
47
0.730878
fe75bd0af7310c35209f22aa54a485a54012b249
446
sql
SQL
sakila-app-domain/src/test/resources/db/migration/V0__001_sakila-country.sql
yujiorama/sakila-app
a3baf70fe5e2ee8a224a5b75b03266e414d87a30
[ "MIT" ]
null
null
null
sakila-app-domain/src/test/resources/db/migration/V0__001_sakila-country.sql
yujiorama/sakila-app
a3baf70fe5e2ee8a224a5b75b03266e414d87a30
[ "MIT" ]
null
null
null
sakila-app-domain/src/test/resources/db/migration/V0__001_sakila-country.sql
yujiorama/sakila-app
a3baf70fe5e2ee8a224a5b75b03266e414d87a30
[ "MIT" ]
null
null
null
-- -- Name: country; Type: TABLE; Schema: public; Owner: postgres; Tablespace: -- CREATE TABLE country ( country_id integer auto_increment NOT NULL, country character varying(50) NOT NULL, last_update timestamp without time zone DEFAULT now() NOT NULL ); -- -- Name: country_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres; Tablespace: -- ALTER TABLE country ADD CONSTRAINT country_pkey PRIMARY KEY (country_id);
24.777778
85
0.721973
410de90d82dd35e26f2221205263ada519223389
656
kt
Kotlin
src/main/kotlin/lain/Ast.kt
liminalitythree/bakadesu
6d5fbcc29da148fd72ecb58b164fc5c845267e5c
[ "CC0-1.0" ]
null
null
null
src/main/kotlin/lain/Ast.kt
liminalitythree/bakadesu
6d5fbcc29da148fd72ecb58b164fc5c845267e5c
[ "CC0-1.0" ]
null
null
null
src/main/kotlin/lain/Ast.kt
liminalitythree/bakadesu
6d5fbcc29da148fd72ecb58b164fc5c845267e5c
[ "CC0-1.0" ]
null
null
null
package lain // THIS IS NOT SOMETHING PERVERTED // IT STANDS FOR S-EXPRESSION // NOT SOMETHING WITH S*X IN IT // maybe sealed class Sexpr // stands for baka list (since List is already taken by meanie standard library) // maybe // start is the token of the starting left paren ( // maybe data class BList(val start: Token, val list: List<Sexpr>) : Sexpr() sealed class Symbol : Sexpr() data class Identifier(val token: Token, val name: String) : Symbol() // since the normal range is already using Range... maybe // maybe // start is the token of the starting left bracket [ // maybe data class AstRange(val start: Token, val range: Range) : Symbol()
27.333333
80
0.724085
c23681ee9977f5997cf6c10e8ad53b535c5f7437
2,362
go
Go
hw1_tree/main.go
Hixon10/golang-webservices-1-ru
59ab7e40e3fa2fbee09ecfd83cb74691181b04e3
[ "MIT" ]
null
null
null
hw1_tree/main.go
Hixon10/golang-webservices-1-ru
59ab7e40e3fa2fbee09ecfd83cb74691181b04e3
[ "MIT" ]
null
null
null
hw1_tree/main.go
Hixon10/golang-webservices-1-ru
59ab7e40e3fa2fbee09ecfd83cb74691181b04e3
[ "MIT" ]
null
null
null
package main import ( "os" "io" "log" "io/ioutil" "strconv" "fmt" "sort" "strings" ) type fileName struct { files []fileName name string } func main() { out := os.Stdout if !(len(os.Args) == 2 || len(os.Args) == 3) { panic("usage go run main.go . [-f]") } path := os.Args[1] printFiles := len(os.Args) == 3 && os.Args[2] == "-f" err := dirTree(out, path, printFiles) if err != nil { panic(err.Error()) } } func dirTree(output io.Writer, dirPath string, showFiles bool) error { fileNames := dirTraversal(dirPath, showFiles) needDelimiter := make(map[int]bool) printFiles(output, *fileNames, 0, false, needDelimiter) return nil } func dirTraversal(dirPath string, showFiles bool) *fileName { dirFiles, err := ioutil.ReadDir(dirPath) if err != nil { log.Fatal(err) } files := make([]fileName, 0) for _, f := range dirFiles { if f.IsDir() { newDirPath := dirPath + string(os.PathSeparator) + f.Name() newFiles := dirTraversal(newDirPath, showFiles) files = append(files, fileName{name: f.Name(), files:(*newFiles).files}) } else { if !showFiles { continue; } sizeStr := "empty" if f.Size() > 0 { sizeStr = strconv.Itoa(int(f.Size())) + "b" } fName := f.Name() + " (" + sizeStr + ")" files = append(files, fileName{name:fName}) } } sort.SliceStable(files, func(i, j int) bool { return strings.Compare(files[i].name, files[j].name) < 0 }) result := fileName{files:files} return &result } func printFiles(output io.Writer, files fileName, level int, last bool, needDelimiter map[int]bool) { newNeedDelimiter := make(map[int]bool) for key, value := range needDelimiter { newNeedDelimiter[key] = value } if len(files.name) > 0 { space := "" for i := 0; i < level; i++ { if i + 1 == level { if last { space = space + "└───" newNeedDelimiter[level] = false } else { space = space + "├───" } } else { needD := true f, ok :=newNeedDelimiter[i + 1] if ok { needD = f } if needD { space = space + "│" + "\t" } else { space = space + "\t" } } } fmt.Fprintln(output, space + files.name) } for fileIndex := 0; fileIndex < len(files.files); fileIndex++ { last := fileIndex+1 == len(files.files) printFiles(output, files.files[fileIndex], level + 1, last, newNeedDelimiter) } }
20.188034
101
0.602879
584f832eaa810b506891fc18601ac3d7e6b7b6b9
3,270
h
C
ui/message_center/views/message_center_button_bar.h
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-11-28T10:46:52.000Z
2019-11-28T10:46:52.000Z
ui/message_center/views/message_center_button_bar.h
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
ui/message_center/views/message_center_button_bar.h
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-03-27T11:15:39.000Z
2016-08-17T14:19:56.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef UI_MESSAGE_CENTER_VIEWS_MESSAGE_CENTER_BUTTON_BAR_H_ #define UI_MESSAGE_CENTER_VIEWS_MESSAGE_CENTER_BUTTON_BAR_H_ #include "ui/views/controls/button/button.h" #include "ui/views/controls/button/image_button.h" #include "ui/views/view.h" namespace views { class Label; } namespace message_center { class ButtonBarSettingsLabel; class MessageCenter; class MessageCenterTray; class MessageCenterView; class NotificationCenterButton; class NotifierSettingsProvider; // MessageCenterButtonBar is the class that shows the content outside the main // notification area - the label (or NotifierGroup switcher) and the buttons. class MessageCenterButtonBar : public views::View, public views::ButtonListener { public: MessageCenterButtonBar(MessageCenterView* message_center_view, MessageCenter* message_center, NotifierSettingsProvider* notifier_settings_provider, bool settings_initially_visible, const base::string16& title); ~MessageCenterButtonBar() override; // Enables or disables all of the buttons in the center. This is used to // prevent user clicks during the close-all animation. virtual void SetAllButtonsEnabled(bool enabled); // Sometimes we shouldn't see the close-all button. void SetCloseAllButtonEnabled(bool enabled); // Sometimes we shouldn't see the back arrow (not in settings). void SetBackArrowVisible(bool visible); private: // Updates the layout manager which can have differing configuration // depending on the visibilty of different parts of the button bar. void ViewVisibilityChanged(); // Overridden from views::View: void ChildVisibilityChanged(views::View* child) override; // Overridden from views::ButtonListener: void ButtonPressed(views::Button* sender, const ui::Event& event) override; MessageCenterView* message_center_view() const { return message_center_view_; } MessageCenter* message_center() const { return message_center_; } MessageCenterView* message_center_view_; // Weak reference. MessageCenter* message_center_; // Weak reference. // |close_bubble_button_| closes the message center bubble. This is required // for desktop Linux because the status icon doesn't toggle the bubble, and // close-on-deactivation is off. This is a tentative solution. Once pkotwicz // Fixes the problem of focus-follow-mouse, close-on-deactivation will be // back and this field will be removed. See crbug.com/319516. #if defined(OS_LINUX) && !defined(OS_CHROMEOS) views::ImageButton* close_bubble_button_; #endif // Sub-views of the button bar. NotificationCenterButton* title_arrow_; views::Label* notification_label_; views::View* button_container_; NotificationCenterButton* close_all_button_; NotificationCenterButton* settings_button_; NotificationCenterButton* quiet_mode_button_; DISALLOW_COPY_AND_ASSIGN(MessageCenterButtonBar); }; } // namespace message_center #endif // UI_MESSAGE_CENTER_VIEWS_MESSAGE_CENTER_BUTTON_BAR_H_
36.741573
78
0.759327
6c89651665ade0c6edaf26b7aaa72ba3bb5fcaa8
2,054
go
Go
vendor/github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/web/client/client.go
suhanime/installer
9c8baf2f69c50a9d745d86f4784bdd6b426040af
[ "Apache-2.0" ]
3
2021-03-03T17:50:29.000Z
2022-03-04T16:25:57.000Z
vendor/github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/web/client/client.go
suhanime/installer
9c8baf2f69c50a9d745d86f4784bdd6b426040af
[ "Apache-2.0" ]
9
2021-03-10T18:24:13.000Z
2021-05-27T21:58:26.000Z
vendor/github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/services/web/client/client.go
suhanime/installer
9c8baf2f69c50a9d745d86f4784bdd6b426040af
[ "Apache-2.0" ]
3
2021-01-04T22:29:08.000Z
2021-01-14T08:39:25.000Z
package client import ( "github.com/Azure/azure-sdk-for-go/services/web/mgmt/2019-08-01/web" "github.com/terraform-providers/terraform-provider-azurerm/azurerm/internal/common" ) type Client struct { AppServiceEnvironmentsClient *web.AppServiceEnvironmentsClient AppServicePlansClient *web.AppServicePlansClient AppServicesClient *web.AppsClient BaseClient *web.BaseClient CertificatesClient *web.CertificatesClient CertificatesOrderClient *web.AppServiceCertificateOrdersClient } func NewClient(o *common.ClientOptions) *Client { appServiceEnvironmentsClient := web.NewAppServiceEnvironmentsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&appServiceEnvironmentsClient.Client, o.ResourceManagerAuthorizer) appServicePlansClient := web.NewAppServicePlansClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&appServicePlansClient.Client, o.ResourceManagerAuthorizer) appServicesClient := web.NewAppsClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&appServicesClient.Client, o.ResourceManagerAuthorizer) baseClient := web.NewWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&baseClient.Client, o.ResourceManagerAuthorizer) certificatesClient := web.NewCertificatesClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&certificatesClient.Client, o.ResourceManagerAuthorizer) certificatesOrderClient := web.NewAppServiceCertificateOrdersClientWithBaseURI(o.ResourceManagerEndpoint, o.SubscriptionId) o.ConfigureClient(&certificatesOrderClient.Client, o.ResourceManagerAuthorizer) return &Client{ AppServiceEnvironmentsClient: &appServiceEnvironmentsClient, AppServicePlansClient: &appServicePlansClient, AppServicesClient: &appServicesClient, BaseClient: &baseClient, CertificatesClient: &certificatesClient, CertificatesOrderClient: &certificatesOrderClient, } }
45.644444
124
0.812074
d2df2502928938d4e070a939f4b6f721b919dd9b
4,304
php
PHP
application/views/admin/arac_listesi.php
umituysal/Codelgniter
450d2e611b7531ee9f394ef5e3e64d4b14560dbe
[ "MIT" ]
1
2019-03-15T20:55:57.000Z
2019-03-15T20:55:57.000Z
application/views/admin/arac_listesi.php
umituysal/Codelgniter
450d2e611b7531ee9f394ef5e3e64d4b14560dbe
[ "MIT" ]
null
null
null
application/views/admin/arac_listesi.php
umituysal/Codelgniter
450d2e611b7531ee9f394ef5e3e64d4b14560dbe
[ "MIT" ]
null
null
null
<div class="content"> <div class="container-fluid"> <div class="text-center"> <div class="row"> <?php if ($this->session->flashdata("sonuc")) { ?> <div class="alert alert-info"> <span><b> İşlem - </b><?=$this->session->flashdata("sonuc")?></span> </div> <?php } ?> </div> </div> <div class="row"> <div class="col-md-12"> <div class="card"> <div class="header"> <h4 class="title">&nbsp;<b> Araçlar </b><br><br> <a class="btn" href="<?=base_url()?>admin/araclar/insert">Yeni Araç Ekle</a></h4> <p class="category"></p> </div> <div class="content table-responsive table-full-width"> <table class="table table-striped"> <thead> <th>Marka</th> <th>Model</th> <th>Sene</th> <th>Depozit</th> <th>Kasko</th> <th>Vites</th> <th>Yakıt Tipi</th> <th>Kasa Tipi</th> <th>Motor Hacmi</th> <th>Motor Gücü</th> <th>Renk</th> <th>Yolcu Saysı</th> <th>Durumu</th> <th>Anahtar Kelime</th> <th>Fiyat1</th> <th>Fiyat2</th> <th>Fiyat3</th> <th>Resim</th> <th>Galeri</th> <th>Göster</th> <th>Sil</th> <th>Düzenle</th> </thead> <tbody> <?php foreach ($veri as $rs) { ?> <tr> <td><?=$rs->markaadi?></td> <td><?=$rs->model?></td> <td><?=$rs->sene?></td> <td><?=$rs->depozit?></td> <td><?=$rs->kasko?></td> <td><?=$rs->vites?></td> <td><?=$rs->yakit_tipi?></td> <td><?=$rs->kasa_tipi?></td> <td><?=$rs->motor_hacmi?></td> <td><?=$rs->motor_gucu?></td> <td><?=$rs->renk?></td> <td><?=$rs->yolcu_sayisi?></td> <td><?=$rs->durumu?></td> <td><?=$rs->keywords?></td> <td><?=$rs->fiyat?></td> <td><?=$rs->fiyatiki?></td> <td><?=$rs->fiyatuc?></td> <td> <a href="<?=base_url()?>admin/araclar/resim_ekle/<?=$rs->Id?>"> <?php if($rs->resim==NULL) { ?> Resim Ekle <?php } else { ?> <img height=50 src="<?=base_url()?>uploads/<?=$rs->resim?>"> <?php } ?> </a> </td> <td><a href="<?=base_url()?>admin/araclar/resim_galeri_ekle/<?=$rs->Id?>"> <img height=40 src="<?=base_url()?>assets/admin/assets/img/images.png"></a></td> <td class="center"><a class="btn" href="<?=base_url()?>admin/araclar/show/<?=$rs->Id?>"> Göster </a></td> <td><a class="btn btn-info" href="<?=base_url()?>admin/araclar/delete/<?=$rs->Id?>" onclick="return confirm('Silmek İstediğinize Emin misiniz?');">Sil</a></td> <td><a class="btn btn-info btn-fill" href="<?=base_url()?>admin/araclar/edit/<?=$rs->Id?>">Düzenle</a></td> </tr> <?php } ?> </tbody> </table> </div> </div> </div> </div> </div> </div>
37.103448
170
0.31947
04620563a0480a80c20b2f52c60ef9adb097f15e
2,851
java
Java
nginious-server/src/main/java/com/nginious/http/session/HttpCookieSessionManager.java
bojanp/Nginious
47924e4cc22aec1aaabf267a0011ccb2006e729a
[ "Apache-2.0" ]
null
null
null
nginious-server/src/main/java/com/nginious/http/session/HttpCookieSessionManager.java
bojanp/Nginious
47924e4cc22aec1aaabf267a0011ccb2006e729a
[ "Apache-2.0" ]
null
null
null
nginious-server/src/main/java/com/nginious/http/session/HttpCookieSessionManager.java
bojanp/Nginious
47924e4cc22aec1aaabf267a0011ccb2006e729a
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2012 NetDigital Sweden AB * * 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.nginious.http.session; import java.io.IOException; import com.nginious.http.HttpRequest; import com.nginious.http.HttpResponse; import com.nginious.http.HttpSession; import com.nginious.http.common.PathParameters; /** * A HTTP session manager which creates, serializes HTTP sessions into cookies and * deserializes HTTP sessions from cookies. * * @author Bojan Pisler, NetDigital Sweden AB * */ public class HttpCookieSessionManager implements HttpSessionManager { /** * Starts this HTTP cookie session manager. */ public void start() { return; } /** * Stops this HTTP cookie session manager. */ public void stop() { return; } /** * Deserializes HTTP session from cookies in specified HTTP request or creates a new HTTP session * if no session cookies exist. * * @param request the HTTP request to deserialize HTTP session from * @param create whether or not to create a new session if no cookies exists in HTTP request * @throws IOException if unable to deserialize HTTP session */ public HttpSession getSession(HttpRequest request, boolean create) throws IOException { HttpSessionImpl session = HttpCookieSessionDeserializer.deserialize(request); if(session == null && create) { session = new HttpSessionImpl(); } else if(session != null) { session.setLastAccessedTime(); } return session; } /** * Serializes the specified HTTP session into cookies and stores them in the specified HTTP response. The * cookie path is retrieved from the specified HTTP request. * * @param request the HTTP request * @param response the HTTP response * @param session the HTTP session to serialize * @throws IOException if unable to serialize HTTP session */ public void storeSession(HttpRequest request, HttpResponse response, HttpSession session) throws IOException { PathParameters params = new PathParameters(request); String path = params.get(0); if(path == null) { path = "/"; } else { path = "/" + path; } if(session.isInvalidated()) { HttpCookieSessionSerializer.invalidate(session, request, response, path); } else if(session.isNew()) { HttpCookieSessionSerializer.serialize(session, response, path); } } }
30.010526
111
0.73027
1eca683d7303fe4d6a3efa68c1422e88811a8df7
941
lua
Lua
lib/Enumerable.lua
LastTalon/Monolith
0168b05fd3ae4d5198169319091a4b3d121538e5
[ "MIT" ]
6
2020-11-30T03:05:05.000Z
2022-03-28T15:29:03.000Z
lib/Enumerable.lua
LastTalon/Monolith
0168b05fd3ae4d5198169319091a4b3d121538e5
[ "MIT" ]
21
2020-11-26T04:45:57.000Z
2020-12-26T22:25:53.000Z
lib/Enumerable.lua
IsoLogicGames/Monolith
0168b05fd3ae4d5198169319091a4b3d121538e5
[ "MIT" ]
1
2022-01-23T21:26:47.000Z
2022-01-23T21:26:47.000Z
--- Allows an object to iterate over its elements in a generic for loop. -- Provides an enumerator that can be used in a generic for loop similar to -- pairs or ipairs. -- -- @classmod Enumerable local Enumerable = {} Enumerable.__index = Enumerable --- Creates a new Enumerable interface instance. -- This should only be used when implementing a new Enumerable. -- -- @return the new Enumerable interface -- @static -- @access private function Enumerable.new() local self = setmetatable({}, Enumerable) return self end --- Creates an enumerator for the object. -- The enumerator can be used directly in a generic for loop similar to pairs -- or ipairs. -- -- @return the enumerator generator -- @return the invariant state -- @return the control variable state function Enumerable:Enumerator() error("Abstract method Enumerator must be overridden in first concrete subclass. Called directly from Enumerable.") end return Enumerable
27.676471
116
0.757705
a86c441392c3429d13bef7fc5bcf3cad0958e6c3
16,225
rs
Rust
jakescript/src/ast/mod.rs
jakemarsden/JakeScript
7ac9bd6f2e1c822d139bdaab2950736da387fa88
[ "MIT" ]
1
2022-03-29T20:06:15.000Z
2022-03-29T20:06:15.000Z
jakescript/src/ast/mod.rs
jakemarsden/JakeScript
7ac9bd6f2e1c822d139bdaab2950736da387fa88
[ "MIT" ]
null
null
null
jakescript/src/ast/mod.rs
jakemarsden/JakeScript
7ac9bd6f2e1c822d139bdaab2950736da387fa88
[ "MIT" ]
3
2021-11-04T15:15:54.000Z
2021-11-04T21:20:01.000Z
use crate::str::NonEmptyString; use serde::{Deserialize, Serialize}; use std::fmt; pub trait Node: Clone + fmt::Debug {} #[derive(Clone, Default, Debug, Serialize, Deserialize)] pub struct Program { body: Block, } impl Program { pub fn new(body: Block) -> Self { Self { body } } pub fn body(&self) -> &Block { &self.body } } impl Node for Program {} #[derive(Clone, Default, Debug, Serialize, Deserialize)] pub struct Block { hoisted_decls: Vec<DeclarationStatement>, stmts: Vec<Statement>, } impl Block { pub fn new(hoisted_decls: Vec<DeclarationStatement>, stmts: Vec<Statement>) -> Self { Self { hoisted_decls, stmts, } } pub fn hoisted_declarations(&self) -> &[DeclarationStatement] { &self.hoisted_decls } pub fn statements(&self) -> &[Statement] { &self.stmts } } impl Node for Block {} #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(tag = "statement_type")] pub enum Statement { Assert(AssertStatement), Break(BreakStatement), Continue(ContinueStatement), Declaration(DeclarationStatement), Exit(ExitStatement), Expression(Expression), If(IfStatement), Print(PrintStatement), Return(ReturnStatement), Throw(ThrowStatement), Try(TryStatement), ForLoop(ForLoop), WhileLoop(WhileLoop), } impl Node for Statement {} #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(tag = "declaration_type")] pub enum DeclarationStatement { Function(FunctionDeclaration), Variable(VariableDeclaration), } impl DeclarationStatement { pub fn is_hoisted(&self) -> bool { match self { Self::Function(..) => true, Self::Variable(decl) => decl.is_hoisted(), } } } impl Node for DeclarationStatement {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct AssertStatement { pub condition: Expression, } impl Node for AssertStatement {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ExitStatement; impl Node for ExitStatement {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct PrintStatement { pub argument: Expression, pub new_line: bool, } impl Node for PrintStatement {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct IfStatement { pub condition: Expression, pub success_block: Block, pub else_block: Option<Block>, } impl Node for IfStatement {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ForLoop { pub initialiser: Option<VariableDeclaration>, pub condition: Option<Expression>, pub incrementor: Option<Expression>, pub body: Block, } impl Node for ForLoop {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct WhileLoop { pub condition: Expression, pub body: Block, } impl Node for WhileLoop {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct BreakStatement { // TODO: Support labels. } impl Node for BreakStatement {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ContinueStatement { // TODO: Support labels. } impl Node for ContinueStatement {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ReturnStatement { pub expr: Option<Expression>, } impl Node for ReturnStatement {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ThrowStatement { pub exception: Expression, } impl Node for ThrowStatement {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct TryStatement { pub body: Block, pub catch_block: Option<CatchBlock>, pub finally_block: Option<FinallyBlock>, } impl Node for TryStatement {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct CatchBlock { pub exception_identifier: Option<Identifier>, pub body: Block, } impl Node for CatchBlock {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct FinallyBlock { pub inner: Block, } impl Node for FinallyBlock {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct FunctionDeclaration { pub fn_name: Identifier, pub param_names: Vec<Identifier>, pub body: Block, } impl Node for FunctionDeclaration {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct VariableDeclaration { pub kind: VariableDeclarationKind, pub entries: Vec<VariableDeclarationEntry>, } impl VariableDeclaration { pub fn is_escalated(&self) -> bool { match self.kind { VariableDeclarationKind::Let | VariableDeclarationKind::Const => false, VariableDeclarationKind::Var => true, } } pub fn is_hoisted(&self) -> bool { match self.kind { VariableDeclarationKind::Let | VariableDeclarationKind::Const => false, VariableDeclarationKind::Var => true, } } /// Split the declaration into /// /// 1. a "main" [`VariableDeclaration`], sans initialisers, to declare each entry /// 2. a new, synthesised [`Expression`] to initialise each entry, for each entry which started /// with an initialiser. pub fn into_declaration_and_initialiser(mut self) -> (Self, Vec<Expression>) { let mut initialisers = Vec::with_capacity(self.entries.len()); for entry in &mut self.entries { if let Some(initialiser) = entry.initialiser.take() { // Synthesise an assignment expression to initialise the variable initialisers.push(Expression::Assignment(AssignmentExpression { op: AssignmentOperator::Assign, lhs: Box::new(Expression::VariableAccess(VariableAccessExpression { var_name: entry.var_name.clone(), })), rhs: Box::new(initialiser), })); } } (self, initialisers) } } impl Node for VariableDeclaration {} #[derive(Clone, Debug, Serialize, Deserialize)] #[serde(tag = "expression_type")] pub enum Expression { Assignment(AssignmentExpression), Binary(BinaryExpression), Unary(UnaryExpression), Ternary(TernaryExpression), Grouping(GroupingExpression), FunctionCall(FunctionCallExpression), PropertyAccess(PropertyAccessExpression), ComputedPropertyAccess(ComputedPropertyAccessExpression), Literal(LiteralExpression), VariableAccess(VariableAccessExpression), } impl Node for Expression {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct AssignmentExpression { pub op: AssignmentOperator, pub lhs: Box<Expression>, pub rhs: Box<Expression>, } impl Node for AssignmentExpression {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct BinaryExpression { pub op: BinaryOperator, pub lhs: Box<Expression>, pub rhs: Box<Expression>, } impl Node for BinaryExpression {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct UnaryExpression { pub op: UnaryOperator, pub operand: Box<Expression>, } impl Node for UnaryExpression {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct TernaryExpression { pub condition: Box<Expression>, pub lhs: Box<Expression>, pub rhs: Box<Expression>, } impl Node for TernaryExpression {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct GroupingExpression { pub inner: Box<Expression>, } impl Node for GroupingExpression {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct LiteralExpression { pub value: Literal, } impl Node for LiteralExpression {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct FunctionCallExpression { pub function: Box<Expression>, pub arguments: Vec<Expression>, } impl Node for FunctionCallExpression {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct PropertyAccessExpression { pub base: Box<Expression>, pub property_name: Identifier, } impl Node for PropertyAccessExpression {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct ComputedPropertyAccessExpression { pub base: Box<Expression>, pub property: Box<Expression>, } impl Node for ComputedPropertyAccessExpression {} #[derive(Clone, Debug, Serialize, Deserialize)] pub struct VariableAccessExpression { pub var_name: Identifier, } impl Node for VariableAccessExpression {} #[derive(Clone, Eq, PartialEq, Hash, Debug, Serialize, Deserialize)] pub struct Identifier(NonEmptyString); impl From<NonEmptyString> for Identifier { fn from(s: NonEmptyString) -> Self { Self(s) } } impl From<i64> for Identifier { fn from(value: i64) -> Self { let s = value.to_string(); // Safety: The string can't be empty because it was created from a number. Self(unsafe { NonEmptyString::from_unchecked(s) }) } } impl fmt::Display for Identifier { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.0) } } #[derive(Clone, Default, Debug, Serialize, Deserialize)] #[serde(tag = "kind", content = "value")] pub enum Literal { Boolean(bool), Numeric(NumericLiteral), // TODO: Store string literals in the constant pool. String(String), Array(Vec<Expression>), Function { name: Option<Identifier>, param_names: Vec<Identifier>, body: Block, }, // TODO: Support properties in object literals. Object, Null, // TODO: Should be a property of the VM's global object at runtime, not a literal. #[default] Undefined, } #[derive(Copy, Clone, Debug, Serialize, Deserialize)] pub enum NumericLiteral { /// Numeric literal tokens are **always unsigned** (but can be made negative at runtime with the /// negation unary operator). Int(u64), // TODO: Should be a property of the VM's global object at runtime, not a literal. Infinity, // TODO: Should be a property of the VM's global object at runtime, not a literal. NaN, } pub trait Op: Copy + Eq + fmt::Debug { fn associativity(&self) -> Associativity; fn precedence(&self) -> Precedence; } #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum Operator { Assignment(AssignmentOperator), Binary(BinaryOperator), Unary(UnaryOperator), Ternary, Grouping, FunctionCall, PropertyAccess, ComputedPropertyAccess, } impl Op for Operator { fn associativity(&self) -> Associativity { match self { Self::Assignment(kind) => kind.associativity(), Self::Binary(kind) => kind.associativity(), Self::Unary(kind) => kind.associativity(), Self::Ternary => TernaryOperator.associativity(), Self::Grouping => GroupingOperator.associativity(), Self::FunctionCall => FunctionCallOperator.associativity(), Self::PropertyAccess => PropertyAccessOperator.associativity(), Self::ComputedPropertyAccess => ComputedPropertyAccessOperator.associativity(), } } fn precedence(&self) -> Precedence { match self { Self::Assignment(kind) => kind.precedence(), Self::Binary(kind) => kind.precedence(), Self::Unary(kind) => kind.precedence(), Self::Ternary => TernaryOperator.precedence(), Self::Grouping => GroupingOperator.precedence(), Self::FunctionCall => FunctionCallOperator.precedence(), Self::PropertyAccess => PropertyAccessOperator.precedence(), Self::ComputedPropertyAccess => ComputedPropertyAccessOperator.precedence(), } } } #[derive(Copy, Clone, Default, Eq, PartialEq, Debug, Serialize, Deserialize)] pub enum AssignmentOperator { #[default] Assign, AddAssign, DivAssign, ModAssign, MulAssign, PowAssign, SubAssign, ShiftLeftAssign, ShiftRightAssign, ShiftRightUnsignedAssign, BitwiseAndAssign, BitwiseOrAssign, BitwiseXOrAssign, } impl Op for AssignmentOperator { fn associativity(&self) -> Associativity { Associativity::RightToLeft } fn precedence(&self) -> Precedence { Precedence(3) } } #[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] pub enum BinaryOperator { Add, Div, Mod, Mul, Pow, Sub, Equal, NotEqual, Identical, NotIdentical, LessThan, LessThanOrEqual, MoreThan, MoreThanOrEqual, ShiftLeft, ShiftRight, ShiftRightUnsigned, BitwiseAnd, BitwiseOr, BitwiseXOr, LogicalAnd, LogicalOr, } impl Op for BinaryOperator { fn associativity(&self) -> Associativity { match self { Self::Pow => Associativity::RightToLeft, _ => Associativity::LeftToRight, } } fn precedence(&self) -> Precedence { match self { Self::Pow => Precedence(16), Self::Mul | Self::Div | Self::Mod => Precedence(15), Self::Add | Self::Sub => Precedence(14), Self::ShiftLeft | Self::ShiftRight | Self::ShiftRightUnsigned => Precedence(13), Self::LessThan | Self::LessThanOrEqual | Self::MoreThan | Self::MoreThanOrEqual => { Precedence(12) } Self::Equal | Self::NotEqual | Self::Identical | Self::NotIdentical => Precedence(11), Self::BitwiseAnd => Precedence(10), Self::BitwiseXOr => Precedence(9), Self::BitwiseOr => Precedence(8), Self::LogicalAnd => Precedence(7), Self::LogicalOr => Precedence(6), } } } #[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] pub enum UnaryOperator { DecrementPrefix, DecrementPostfix, IncrementPrefix, IncrementPostfix, BitwiseNot, LogicalNot, NumericNegate, NumericPlus, } impl Op for UnaryOperator { fn associativity(&self) -> Associativity { Associativity::RightToLeft } fn precedence(&self) -> Precedence { match self { Self::IncrementPostfix | Self::DecrementPostfix => Precedence(18), Self::LogicalNot | Self::BitwiseNot | Self::NumericPlus | Self::NumericNegate | Self::IncrementPrefix | Self::DecrementPrefix => Precedence(17), } } } #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub struct TernaryOperator; impl Op for TernaryOperator { fn associativity(&self) -> Associativity { Associativity::RightToLeft } fn precedence(&self) -> Precedence { Precedence(4) } } #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub struct GroupingOperator; impl Op for GroupingOperator { fn associativity(&self) -> Associativity { Associativity::LeftToRight } fn precedence(&self) -> Precedence { Precedence(21) } } #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub struct FunctionCallOperator; impl Op for FunctionCallOperator { fn associativity(&self) -> Associativity { Associativity::LeftToRight } fn precedence(&self) -> Precedence { Precedence(20) } } #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub struct PropertyAccessOperator; impl Op for PropertyAccessOperator { fn associativity(&self) -> Associativity { Associativity::LeftToRight } fn precedence(&self) -> Precedence { Precedence(20) } } #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub struct ComputedPropertyAccessOperator; impl Op for ComputedPropertyAccessOperator { fn associativity(&self) -> Associativity { Associativity::LeftToRight } fn precedence(&self) -> Precedence { Precedence(20) } } #[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)] pub enum VariableDeclarationKind { Const, Let, Var, } #[derive(Clone, Debug, Serialize, Deserialize)] pub struct VariableDeclarationEntry { pub var_name: Identifier, pub initialiser: Option<Expression>, } #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum Associativity { LeftToRight, RightToLeft, } #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug)] pub struct Precedence(u8); impl Precedence { pub const MIN: Self = Self(1); pub const MAX: Self = Self(21); }
25.312012
100
0.660955
4446be235f65e12738013067eb24ab193e4f3e96
2,213
sql
SQL
plugins/social_media_buttons/sql/social_media_buttons_install.sql
PapooSoftware/PapooCMS
0f1c30be2a6ac825cad6dad348a957452e545a8d
[ "MIT" ]
2
2021-04-22T14:03:19.000Z
2021-04-29T12:12:46.000Z
plugins/social_media_buttons/sql/social_media_buttons_install.sql
PapooSoftware/PapooCMS
0f1c30be2a6ac825cad6dad348a957452e545a8d
[ "MIT" ]
4
2021-05-20T12:46:21.000Z
2021-11-26T16:22:13.000Z
plugins/social_media_buttons/sql/social_media_buttons_install.sql
PapooSoftware/PapooCMS
0f1c30be2a6ac825cad6dad348a957452e545a8d
[ "MIT" ]
null
null
null
DROP TABLE IF EXISTS `XXX_plugin_social_media_buttons`; ##b_dump## CREATE TABLE `XXX_plugin_social_media_buttons` ( `id` tinyint(2) NOT NULL auto_increment , `display` varchar(255) NULL , `name` varchar(255) NULL , `aktiv` tinyint(1) NULL , PRIMARY KEY (`id`) ) ENGINE=MyISAM ; ##b_dump## INSERT INTO `XXX_plugin_social_media_buttons` (display, name, aktiv) VALUES ('Facebook', 'facebook', '1') ; ##b_dump## INSERT INTO `XXX_plugin_social_media_buttons` (display, name, aktiv) VALUES ('Twitter', 'twitter', '1') ; ##b_dump## INSERT INTO `XXX_plugin_social_media_buttons` (display, name, aktiv) VALUES ('LinkedIn', 'linkedin', '0') ; ##b_dump## INSERT INTO `XXX_plugin_social_media_buttons` (display, name, aktiv) VALUES ('Xing', 'xing', '0') ; ##b_dump## INSERT INTO `XXX_plugin_social_media_buttons` (display, name, aktiv) VALUES ('Whats App', 'whatsapp', '0') ; ##b_dump## INSERT INTO `XXX_plugin_social_media_buttons` (display, name, aktiv) VALUES ('Mail', 'mail', '1') ; ##b_dump## INSERT INTO `XXX_plugin_social_media_buttons` (display, name, aktiv) VALUES ('Info', 'info', '0') ; ##b_dump## INSERT INTO `XXX_plugin_social_media_buttons` (display, name, aktiv) VALUES ('AddThis', 'addthis', '0') ; ##b_dump## INSERT INTO `XXX_plugin_social_media_buttons` (display, name, aktiv) VALUES ('Tumblr', 'tumblr', '0') ; ##b_dump## INSERT INTO `XXX_plugin_social_media_buttons` (display, name, aktiv) VALUES ('Diaspora', 'diaspora', '0') ; ##b_dump## INSERT INTO `XXX_plugin_social_media_buttons` (display, name, aktiv) VALUES ('Reddit', 'reddit', '0') ; ##b_dump## INSERT INTO `XXX_plugin_social_media_buttons` (display, name, aktiv) VALUES ('StumbleUpon', 'stumbleupon', '0') ; ##b_dump## INSERT INTO `XXX_plugin_social_media_buttons` (display, name, aktiv) VALUES ('Threema', 'threema', '0') ; ##b_dump## DROP TABLE IF EXISTS `XXX_plugin_social_media_buttons_config`; ##b_dump## CREATE TABLE `XXX_plugin_social_media_buttons_config` ( `fontawesome` tinyint(1) NULL , `theme` varchar(255) NULL , `vertical` tinyint(1) NULL ) ENGINE=MyISAM ; ##b_dump## INSERT INTO `XXX_plugin_social_media_buttons_config` (fontawesome, theme, vertical) VALUES ('0', 'standard', '0') ; ##b_dump##
36.883333
83
0.715319
b4361e3cf7e531c50b262ba5acdd92a69c740579
377
a51
Assembly
a51test/(35)ADDC_A_d.a51
Aimini/51cpu
cdeb75510d1dcd867fbebe10e963c4dbecd5ff13
[ "MIT" ]
null
null
null
a51test/(35)ADDC_A_d.a51
Aimini/51cpu
cdeb75510d1dcd867fbebe10e963c4dbecd5ff13
[ "MIT" ]
null
null
null
a51test/(35)ADDC_A_d.a51
Aimini/51cpu
cdeb75510d1dcd867fbebe10e963c4dbecd5ff13
[ "MIT" ]
null
null
null
MOV 0x76,#0x3C MOV 0x2A,#0x24 MOV 0x5B,#0x68 MOV 0x41,#0x38 MOV 0x32,#0x64 MOV 0x34,#0x28 MOV 0x62,#0x7B MOV 0x54,#0x20 DB 0xA5 ADDC A,0x76 ;0x3C C = 0 AC = 0 ADDC A,0x2A ;0x60 C = 0 AC = 1 ADDC A,0x5B ;0xC8 C = 0 AC = 1 ADDC A,0x41 ;0x00 C = 1 Ac = 1 ADDC A,0x32 ;0x65 C = 0 AC = 0 ADDC A,0x34 ;0x8D C = 0 AC = 0 ADDC A,0x62 ;0x08 C = 1 AC = 1 ADDC A,0x54 ;0x29 C = 0 AC = 0
20.944444
30
0.6313
e5122b46f7aec3020e1655dfa142513f9fbed6cd
1,068
lua
Lua
bin/package/pure_sandbox.lua
datumflux/platform
09f6177d7146c3acf8e517c43154c8dfe4ae010c
[ "MIT" ]
4
2019-12-05T09:11:24.000Z
2021-08-05T20:52:07.000Z
bin/package/pure_sandbox.lua
datumflux/platform
09f6177d7146c3acf8e517c43154c8dfe4ae010c
[ "MIT" ]
null
null
null
bin/package/pure_sandbox.lua
datumflux/platform
09f6177d7146c3acf8e517c43154c8dfe4ae010c
[ "MIT" ]
null
null
null
local _G, coroutine = _G, coroutine local main_thread = coroutine.running() or {} -- returns nil in Lua 5.1 local thread_locals = setmetatable({ [main_thread] = _G }, { __mode = "k" }) local sandbox__metatable = {} function sandbox__metatable:__index(k) local v = __[k] if v then return v else local th = coroutine.running() or main_thread local t = thread_locals[th] if t then return t[k] else return _G[k] end end end function sandbox__metatable:__newindex(k, v) if not __(k, function (o) if o ~= nil then return v end end) then local th = coroutine.running() or main_thread local t = thread_locals[th] if not t then t = setmetatable({ _G = _G }, { __index = _G }) thread_locals[th] = t end t[k] = v end end -- convenient access to thread local variables via the `sandbox` table: local sandbox = setmetatable({}, sandbox__metatable) -- or make `sandbox` the default for globals lookup ... if setfenv then setfenv(1, sandbox) -- Lua 5.1 else _ENV = sandbox -- Lua 5.2+ end
23.217391
76
0.657303
6979a2b1986fc2ab60fa15bb66916cb4b76ee4e9
11,884
ps1
PowerShell
tests/Unit/Modules/AzureDevOpsDsc.Common/Resources/Functions/Public/Test-AzDevOpsProject.Tests.ps1
SphenicPaul/AzureDevOpsDsc
48e919e3f9be78154b0b75159239c7ee724b3429
[ "MIT" ]
1
2020-07-05T15:07:27.000Z
2020-07-05T15:07:27.000Z
tests/Unit/Modules/AzureDevOpsDsc.Common/Resources/Functions/Public/Test-AzDevOpsProject.Tests.ps1
SphenicPaul/AzureDevOpsDsc
48e919e3f9be78154b0b75159239c7ee724b3429
[ "MIT" ]
30
2020-07-05T08:33:51.000Z
2022-02-23T16:49:07.000Z
tests/Unit/Modules/AzureDevOpsDsc.Common/Resources/Functions/Public/Test-AzDevOpsProject.Tests.ps1
SphenicPaul/AzureDevOpsDsc
48e919e3f9be78154b0b75159239c7ee724b3429
[ "MIT" ]
6
2020-07-05T08:49:52.000Z
2022-01-07T03:13:04.000Z
# Initialize tests for module function . $PSScriptRoot\..\..\..\..\AzureDevOpsDsc.Common.Tests.Initialization.ps1 InModuleScope 'AzureDevOpsDsc.Common' { $script:dscModuleName = 'AzureDevOpsDsc' $script:moduleVersion = $(Get-Module -Name $script:dscModuleName -ListAvailable | Select-Object -First 1).Version $script:subModuleName = 'AzureDevOpsDsc.Common' $script:subModuleBase = $(Get-Module $script:subModuleName).ModuleBase $script:commandName = $(Get-Item $PSCommandPath).BaseName.Replace('.Tests','') $script:commandScriptPath = Join-Path "$PSScriptRoot\..\..\..\..\..\..\..\" -ChildPath "output\$($script:dscModuleName)\$($script:moduleVersion)\Modules\$($script:subModuleName)\Resources\Functions\Public\$($script:commandName).ps1" $script:tag = @($($script:commandName -replace '-')) . $script:commandScriptPath Describe "$script:subModuleName\Resources\Functions\Public\$script:commandName" -Tag $script:tag { # Mock functions called in function Mock Get-AzDevOpsProject {} # Generate valid, test cases $testCasesValidApiUris = Get-TestCase -ScopeName 'ApiUri' -TestCaseName 'Valid' $testCasesValidPats = Get-TestCase -ScopeName 'Pat' -TestCaseName 'Valid' $testCasesValidProjectIds = Get-TestCase -ScopeName 'ProjectId' -TestCaseName 'Valid' $testCasesValidApiUriPatProjectIds = Join-TestCaseArray -TestCaseArray @( $testCasesValidApiUris, $testCasesValidPats, $testCasesValidProjectIds) -Expand $testCasesValidApiUriPatProjectIds3 = $testCasesValidApiUriPatProjectIds | Select-Object -First 3 $testCasesValidProjectNames = Get-TestCase -ScopeName 'ProjectName' -TestCaseName 'Valid' $testCasesValidApiUriPatProjectNames = Join-TestCaseArray -TestCaseArray @( $testCasesValidApiUris, $testCasesValidPats, $testCasesValidProjectNames) -Expand $testCasesValidApiUriPatProjectNames3 = $testCasesValidApiUriPatProjectNames | Select-Object -First 3 $testCasesValidApiUriPatProjectIdProjectNames = Join-TestCaseArray -TestCaseArray @( $testCasesValidApiUris, $testCasesValidPats, $testCasesValidProjectIds, $testCasesValidProjectNames) -Expand $testCasesValidApiUriPatProjectIdProjectNames3 = $testCasesValidApiUriPatProjectIdProjectNames | Select-Object -First 3 $validApiVersion = Get-TestCaseValue -ScopeName 'ApiVersion' -TestCaseName 'Valid' -First 1 # Generate invalid, test cases $testCasesInvalidApiUris = Get-TestCase -ScopeName 'ApiUri' -TestCaseName 'Invalid' $testCasesInvalidPats = Get-TestCase -ScopeName 'Pat' -TestCaseName 'Invalid' $testCasesInvalidProjectIds = Get-TestCase -ScopeName 'ProjectId' -TestCaseName 'Invalid' $testCasesInvalidApiUriPatProjectIds = Join-TestCaseArray -TestCaseArray @( $testCasesInvalidApiUris, $testCasesInvalidPats, $testCasesInvalidProjectIds) -Expand $testCasesInvalidApiUriPatProjectIds3 = $testCasesInvalidApiUriPatProjectIds | Select-Object -First 3 $testCasesInvalidProjectNames = Get-TestCase -ScopeName 'ProjectName' -TestCaseName 'Invalid' $testCasesInvalidApiUriPatProjectNames = Join-TestCaseArray -TestCaseArray @( $testCasesInvalidApiUris, $testCasesInvalidPats, $testCasesInvalidProjectNames) -Expand $testCasesInvalidApiUriPatProjectNames3 = $testCasesInvalidApiUriPatProjectNames | Select-Object -First 3 $testCasesInvalidApiUriPatProjectIdProjectNames = Join-TestCaseArray -TestCaseArray @( $testCasesInvalidApiUris, $testCasesInvalidPats, $testCasesInvalidProjectIds, $testCasesInvalidProjectNames) -Expand $testCasesInvalidApiUriPatProjectIdProjectNames3 = $testCasesInvalidApiUriPatProjectIdProjectNames | Select-Object -First 3 $invalidApiVersion = Get-TestCaseValue -ScopeName 'ApiVersion' -TestCaseName 'Invalid' -First 1 Context 'When input parameters are valid' { Context 'When called with mandatory "ApiUri", "Pat" and "ProjectId" parameters' { It 'Should not throw - "<ApiUri>", "<Pat>", "<ProjectId>"' -TestCases $testCasesValidApiUriPatProjectIds { param ([string]$ApiUri, [string]$Pat, [string]$ProjectId) { Test-AzDevOpsProject -ApiUri $ApiUri -Pat $Pat -ProjectId $ProjectId } | Should -Not -Throw } It 'Should invoke "Get-AzDevOpsProject" only once - "<ApiUri>", "<Pat>", "<ProjectId>"' -TestCases $testCasesValidApiUriPatProjectIds3 { param ([string]$ApiUri, [string]$Pat, [string]$ProjectId) Mock Get-AzDevOpsProject {} -Verifiable Test-AzDevOpsProject -ApiUri $ApiUri -Pat $Pat -ProjectId $ProjectId | Out-Null Assert-MockCalled 'Get-AzDevOpsProject' -Times 1 -Exactly -Scope 'It' } Context 'When "Get-AzDevOpsProject" returns a present record (with an "id" property)' { It 'Should return $true - "<ApiUri>", "<Pat>", "<ProjectId>"' -TestCases $testCasesValidApiUriPatProjectIds { param ([string]$ApiUri, [string]$Pat, [string]$ProjectId) Mock Get-AzDevOpsProject { return $([PSObject]@{ id = "62d7a991-b78e-4386-b14e-e4eb2a805947" }) } Test-AzDevOpsProject -ApiUri $ApiUri -Pat $Pat -ProjectId $ProjectId | Should -BeTrue } } Context 'When "Get-AzDevOpsProject" does not return a record (with no "id" property)' { It 'Should return $false - "<ApiUri>", "<Pat>", "<ProjectId>"' -TestCases $testCasesValidApiUriPatProjectIds { param ([string]$ApiUri, [string]$Pat, [string]$ProjectId) Mock Get-AzDevOpsProject {} Test-AzDevOpsProject -ApiUri $ApiUri -Pat $Pat -ProjectId $ProjectId | Should -BeFalse } } } Context 'When called with mandatory "ApiUri", "Pat" and "ProjectName" parameters' { It 'Should not throw - "<ApiUri>", "<Pat>", "<ProjectName>"' -TestCases $testCasesValidApiUriPatProjectNames { param ([string]$ApiUri, [string]$Pat, [string]$ProjectName) { Test-AzDevOpsProject -ApiUri $ApiUri -Pat $Pat -ProjectName $ProjectName } | Should -Not -Throw } It 'Should invoke "Get-AzDevOpsProject" only once - "<ApiUri>", "<Pat>", "<ProjectName>"' -TestCases $testCasesValidApiUriPatProjectNames3 { param ([string]$ApiUri, [string]$Pat, [string]$ProjectName) Mock Get-AzDevOpsProject {} -Verifiable Test-AzDevOpsProject -ApiUri $ApiUri -Pat $Pat -ProjectName $ProjectName Assert-MockCalled 'Get-AzDevOpsProject' -Times 1 -Exactly -Scope 'It' } Context 'When "Get-AzDevOpsProject" returns a present record (with an "id" property)' { It 'Should return $true - "<ApiUri>", "<Pat>", "<ProjectName>"' -TestCases $testCasesValidApiUriPatProjectNames { param ([string]$ApiUri, [string]$Pat, [string]$ProjectName) Mock Get-AzDevOpsProject { return $([PSObject]@{ id = "62d7a991-b78e-4386-b14e-e4eb2a805947" }) } Test-AzDevOpsProject -ApiUri $ApiUri -Pat $Pat -ProjectName $ProjectName | Should -BeTrue } } Context 'When "Get-AzDevOpsProject" does not return a record (with no "id" property)' { It 'Should return $false - "<ApiUri>", "<Pat>", "<ProjectName>"' -TestCases $testCasesValidApiUriPatProjectNames { param ([string]$ApiUri, [string]$Pat, [string]$ProjectName) Mock Get-AzDevOpsProject {} Test-AzDevOpsProject -ApiUri $ApiUri -Pat $Pat -ProjectName $ProjectName | Should -BeFalse } } } Context 'When called with mandatory "ApiUri", "Pat", "ProjectId" and "ProjectName" parameters' { It 'Should not throw - "<ApiUri>", "<Pat>", "<ProjectId>", "<ProjectName>"' -TestCases $testCasesValidApiUriPatProjectIdProjectNames { param ([string]$ApiUri, [string]$Pat, [string]$ProjectId, [string]$ProjectName) { Test-AzDevOpsProject -ApiUri $ApiUri -Pat $Pat -ProjectId $ProjectId -ProjectName $ProjectName } | Should -Not -Throw } It 'Should invoke "Get-AzDevOpsProject" only once - "<ApiUri>", "<Pat>", "<ProjectId>", "<ProjectName>"' -TestCases $testCasesValidApiUriPatProjectIdProjectNames3 { param ([string]$ApiUri, [string]$Pat, [string]$ProjectId, [string]$ProjectName) Mock Get-AzDevOpsProject {} -Verifiable Test-AzDevOpsProject -ApiUri $ApiUri -Pat $Pat -ProjectId $ProjectId -ProjectName $ProjectName Assert-MockCalled 'Get-AzDevOpsProject' -Times 1 -Exactly -Scope 'It' } Context 'When "Get-AzDevOpsProject" returns a present record (with an "id" property)' { It 'Should return $true - "<ApiUri>", "<Pat>", "<ProjectId>", "<ProjectName>"' -TestCases $testCasesValidApiUriPatProjectIdProjectNames { param ([string]$ApiUri, [string]$Pat, [string]$ProjectId, [string]$ProjectName) Mock Get-AzDevOpsProject { return $([PSObject]@{ id = "62d7a991-b78e-4386-b14e-e4eb2a805947" }) } Test-AzDevOpsProject -ApiUri $ApiUri -Pat $Pat -ProjectId $ProjectId -ProjectName $ProjectName | Should -BeTrue } } Context 'When "Get-AzDevOpsProject" does not return a record (with no "id" property)' { It 'Should return $false - "<ApiUri>", "<Pat>", "<ProjectId>", "<ProjectName>"' -TestCases $testCasesValidApiUriPatProjectIdProjectNames { param ([string]$ApiUri, [string]$Pat, [string]$ProjectId, [string]$ProjectName) Mock Get-AzDevOpsProject {} Test-AzDevOpsProject -ApiUri $ApiUri -Pat $Pat -ProjectId $ProjectId -ProjectName $ProjectName | Should -BeFalse } } } } Context 'When input parameters are invalid' { Context 'When called with mandatory "ApiUri", "Pat", "ProjectId" and "ProjectName" parameters' { It 'Should throw - "<ApiUri>", "<Pat>", "<ProjectId>", "<ProjectName>"' -TestCases $testCasesInvalidApiUriPatProjectIdProjectNames { param ([string]$ApiUri, [string]$Pat, [string]$ProjectId, [string]$ProjectName) { Test-AzDevOpsProject -ApiUri $ApiUri -Pat $Pat -ProjectId $ProjectId -ProjectName $ProjectName } | Should -Throw } } } } }
48.90535
237
0.591972
f4c4362aa1cf8759c2f02069a10d0729af94faee
942
go
Go
internal/app/repo/repo.go
harunnryd/tempokerja
8aae0589d9764dd6c5eb28912e62b3e109f10d46
[ "MIT" ]
null
null
null
internal/app/repo/repo.go
harunnryd/tempokerja
8aae0589d9764dd6c5eb28912e62b3e109f10d46
[ "MIT" ]
null
null
null
internal/app/repo/repo.go
harunnryd/tempokerja
8aae0589d9764dd6c5eb28912e62b3e109f10d46
[ "MIT" ]
null
null
null
package repo import ( "log" "github.com/harunnryd/tempokerja/config" "github.com/harunnryd/tempokerja/internal/app/driver/db" "github.com/harunnryd/tempokerja/internal/app/repo/product" "github.com/harunnryd/tempokerja/internal/app/repo/transaction" "github.com/parnurzeal/gorequest" ) type Repo interface { Product() product.Product Transaction() transaction.Transaction } type repo struct { product product.Product transaction transaction.Transaction } func New(cfg config.Config) Repo { dbase := db.New(db.WithConfig(cfg)) _, err := dbase.Manager(db.PgsqlDialectParam) if err != nil { log.Fatalln("error1", err) } repo := new(repo) httpClient := gorequest.New() repo.product = product.New(httpClient) repo.transaction = transaction.New(httpClient) return repo } func (r *repo) Product() product.Product { return r.product } func (r *repo) Transaction() transaction.Transaction { return r.transaction }
20.478261
64
0.745223
8a660ded02c9c9c7d43e2b2c59f4559a9081f5cc
1,962
kt
Kotlin
archroid-runtime/src/main/java/app/junhyounglee/archroid/runtime/core/presenter/PresenterProvider.kt
cutehackers/Archroid
515d2b91dd7209c34a4c34761f474703d6200430
[ "Apache-2.0" ]
null
null
null
archroid-runtime/src/main/java/app/junhyounglee/archroid/runtime/core/presenter/PresenterProvider.kt
cutehackers/Archroid
515d2b91dd7209c34a4c34761f474703d6200430
[ "Apache-2.0" ]
null
null
null
archroid-runtime/src/main/java/app/junhyounglee/archroid/runtime/core/presenter/PresenterProvider.kt
cutehackers/Archroid
515d2b91dd7209c34a4c34761f474703d6200430
[ "Apache-2.0" ]
null
null
null
package app.junhyounglee.archroid.runtime.core.presenter import app.junhyounglee.archroid.runtime.core.view.MvpView /** * TODO create a method that binds view instance to Presenter */ class PresenterProvider( private val presenterStore: PresenterStore, private val factory: Factory ) { fun <V: MvpView, P : MvpPresenter<V>> get(key: String, presenterType: Class<P>, viewType: Class<V>, view: V): P { var instance: MvpPresenter<out MvpView>? = presenterStore.get(key) if (presenterType.isInstance(instance)) { @Suppress("UNCHECKED_CAST") return instance as P } instance = factory.create(presenterType, viewType, view) presenterStore.put(key, instance) return instance } fun <V : MvpView, P : MvpPresenter<V>> get(presenterType: Class<P>, viewType: Class<V>, view: V): P { val name = presenterType.canonicalName ?: throw IllegalArgumentException("Local and anonymous classes can not be Presenters") return get("$DEFAULT_KEY:$name", presenterType, viewType, view) } interface Factory { fun <V: MvpView, P : MvpPresenter<V>> create(presenterType: Class<P>, viewType: Class<V>, view: V): P } open class NewInstanceFactory : Factory { override fun <V: MvpView, P : MvpPresenter<V>> create(presenterType: Class<P>, viewType: Class<V>, view: V): P { return try { presenterType.getConstructor(viewType).newInstance(view) } catch (e: InstantiationException) { throw RuntimeException("Cannot create an instance of $presenterType", e) } catch (e: IllegalAccessException) { throw RuntimeException("Cannot create an instance of $presenterType", e) } } } companion object { private const val DEFAULT_KEY = "app.junhyounglee.archroid.runtime.core.presenter.PresenterProvider.DEFAULT_KEY" } }
38.470588
120
0.655454
53bd9337eea75ccde89c829322e4a6450b69e971
215
java
Java
base/src/main/java/store/idragon/tool/base/dto/DataQuery.java
xiaoshimei0305/IdragonTool
532cb03dba9e3e4a4d37e562ab13fc61a20b8992
[ "MIT" ]
null
null
null
base/src/main/java/store/idragon/tool/base/dto/DataQuery.java
xiaoshimei0305/IdragonTool
532cb03dba9e3e4a4d37e562ab13fc61a20b8992
[ "MIT" ]
null
null
null
base/src/main/java/store/idragon/tool/base/dto/DataQuery.java
xiaoshimei0305/IdragonTool
532cb03dba9e3e4a4d37e562ab13fc61a20b8992
[ "MIT" ]
null
null
null
package store.idragon.tool.base.dto; /** * @author xiaoshimei0305 * date 2020/12/12 10:35 下午 * description * @version 1.0 */ public class DataQuery<Q> { /** * 查询信息 */ private Q queryInfo; }
14.333333
36
0.604651
8f9a314130f3951542cc1893367cb75debe1a7c4
1,537
dart
Dart
lib/api/account.dart
koharubiyori/MoegirlViewer-dart
b98f95a8225729999e661c466d3ca42ae183f667
[ "MIT" ]
37
2020-12-27T10:54:52.000Z
2022-02-16T13:34:39.000Z
lib/api/account.dart
koharubiyori/MoegirlViewer-flutter
b98f95a8225729999e661c466d3ca42ae183f667
[ "MIT" ]
8
2020-12-27T16:06:56.000Z
2021-10-10T01:16:02.000Z
lib/api/account.dart
koharubiyori/MoegirlViewer-flutter
b98f95a8225729999e661c466d3ca42ae183f667
[ "MIT" ]
5
2021-05-09T09:02:14.000Z
2021-12-09T03:48:41.000Z
// @dart=2.9 import 'package:moegirl_plus/request/moe_request.dart'; Future<Map> _login(String token, String userName, String password) { return moeRequest( method: 'post', params: { 'action': 'clientlogin', 'loginmessageformat': 'html', 'loginreturnurl': 'https://zh.moegirl.org.cn/Mainpage', 'username': userName, 'password': password, 'rememberMe': true, 'logintoken': token } ); } class AccountApi { static Future<Map> getLoginToken() { return moeRequest( method: 'post', params: { 'action': 'query', 'meta': 'tokens', 'type': 'login' } ); } static Future<Map> login(String userName, String password) async { final tokenData = await getLoginToken(); final String token = tokenData['query']['tokens']['logintoken']; return _login(token, userName, password); } static Future logout() { return moeRequest( method: 'post', params: { 'action': 'logout' } ); } static Future<Map> getInfo() { return moeRequest(params: { 'action': 'query', 'meta': 'userinfo', 'uiprop': 'groups|blockinfo' }); } static Future poll(String pollId, int answer, String token) async { return moeRequest( baseUrl: 'https://zh.moegirl.org.cn/index.php', params: { 'action': 'ajax', 'rs': 'AJAXPoll::submitVote', 'rsargs': [pollId, answer, token] } ); } }
24.790323
70
0.560182
de0c1ba5cc536bd9a60485368df09e33e7a47332
3,261
rs
Rust
tokio/src/timer/interval.rs
leo-lb/tokio
d5c1119c881c9a8b511aa9000fd26b9bda014256
[ "MIT" ]
null
null
null
tokio/src/timer/interval.rs
leo-lb/tokio
d5c1119c881c9a8b511aa9000fd26b9bda014256
[ "MIT" ]
null
null
null
tokio/src/timer/interval.rs
leo-lb/tokio
d5c1119c881c9a8b511aa9000fd26b9bda014256
[ "MIT" ]
null
null
null
use crate::timer::{clock, Delay}; use futures_core::ready; use futures_util::future::poll_fn; use std::future::Future; use std::pin::Pin; use std::task::{self, Poll}; use std::time::{Duration, Instant}; /// A stream representing notifications at fixed interval #[derive(Debug)] pub struct Interval { /// Future that completes the next time the `Interval` yields a value. delay: Delay, /// The duration between values yielded by `Interval`. duration: Duration, } impl Interval { /// Create a new `Interval` that starts at `at` and yields every `duration` /// interval after that. /// /// Note that when it starts, it produces item too. /// /// The `duration` argument must be a non-zero duration. /// /// # Panics /// /// This function panics if `duration` is zero. pub fn new(at: Instant, duration: Duration) -> Interval { assert!( duration > Duration::new(0, 0), "`duration` must be non-zero." ); Interval::new_with_delay(Delay::new(at), duration) } /// Creates new `Interval` that yields with interval of `duration`. /// /// The function is shortcut for `Interval::new(tokio::timer::clock::now() + duration, duration)`. /// /// The `duration` argument must be a non-zero duration. /// /// # Panics /// /// This function panics if `duration` is zero. pub fn new_interval(duration: Duration) -> Interval { Interval::new(clock::now() + duration, duration) } pub(crate) fn new_with_delay(delay: Delay, duration: Duration) -> Interval { Interval { delay, duration } } #[doc(hidden)] // TODO: remove pub fn poll_next(&mut self, cx: &mut task::Context<'_>) -> Poll<Option<Instant>> { // Wait for the delay to be done ready!(Pin::new(&mut self.delay).poll(cx)); // Get the `now` by looking at the `delay` deadline let now = self.delay.deadline(); // The next interval value is `duration` after the one that just // yielded. let next = now + self.duration; self.delay.reset(next); // Return the current instant Poll::Ready(Some(now)) } /// Completes when the next instant in the interval has been reached. /// /// # Examples /// /// ``` /// use tokio::timer::Interval; /// /// use std::time::Duration; /// /// #[tokio::main] /// async fn main() { /// let mut interval = Interval::new_interval(Duration::from_millis(10)); /// /// interval.next().await; /// interval.next().await; /// interval.next().await; /// /// // approximately 30ms have elapsed. /// } /// ``` #[allow(clippy::should_implement_trait)] // TODO: rename (tokio-rs/tokio#1261) pub async fn next(&mut self) -> Option<Instant> { poll_fn(|cx| self.poll_next(cx)).await } } impl futures_core::FusedStream for Interval { fn is_terminated(&self) -> bool { false } } impl futures_core::Stream for Interval { type Item = Instant; fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context<'_>) -> Poll<Option<Self::Item>> { Interval::poll_next(self.get_mut(), cx) } }
28.858407
102
0.59031
b2a880b295016ed24c27494168ac49dc825e406c
867
kt
Kotlin
app/src/main/java/cz/palda97/repoviewer/model/network/GithubIon.kt
Palda97/RepoViewer
90d6efa6812587980437ba598924904fa75372dd
[ "MIT" ]
null
null
null
app/src/main/java/cz/palda97/repoviewer/model/network/GithubIon.kt
Palda97/RepoViewer
90d6efa6812587980437ba598924904fa75372dd
[ "MIT" ]
null
null
null
app/src/main/java/cz/palda97/repoviewer/model/network/GithubIon.kt
Palda97/RepoViewer
90d6efa6812587980437ba598924904fa75372dd
[ "MIT" ]
null
null
null
package cz.palda97.repoviewer.model.network import com.koushikdutta.ion.Ion import cz.palda97.repoviewer.RepoViewerApplication /** * Ion class for communicating with Github API. */ class GithubIon { suspend fun getRepos(username: String) = Ion.with(RepoViewerApplication.context) .load("$BASE_URL/users/$username/repos") .asJsonArray() .await() suspend fun getRecentCommits(repoFullName: String) = Ion.with(RepoViewerApplication.context) .load("$BASE_URL/repos/$repoFullName/commits?per_page=10") .asJsonArray() .await() suspend fun getBranches(repoFullName: String) = Ion.with(RepoViewerApplication.context) .load("$BASE_URL/repos/$repoFullName/branches") .asJsonArray() .await() companion object { private const val BASE_URL = "https://api.github.com" } }
27.967742
96
0.689735
54dd8bd8cb8d0fb77e7df0fd723ba60b2d721fce
302
asm
Assembly
oeis/141/A141044.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/141/A141044.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/141/A141044.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A141044: Two 2's followed by all 1's. ; Submitted by Christian Krause ; 2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1 div $0,2 cmp $0,0 add $0,1
37.75
201
0.556291
27e7dcfcb62ed671fab114812ab151db716b3153
120
ps1
PowerShell
exec.ps1
selva1990kumar/auth0_signIn_socialSignIn
576630aafb9f4b1a2c7f99b79bb67d25f6719201
[ "MIT" ]
144
2016-08-25T03:18:10.000Z
2022-01-22T23:30:27.000Z
exec.ps1
selva1990kumar/auth0_signIn_socialSignIn
576630aafb9f4b1a2c7f99b79bb67d25f6719201
[ "MIT" ]
55
2016-11-23T09:19:05.000Z
2022-02-02T23:15:18.000Z
exec.ps1
selva1990kumar/auth0_signIn_socialSignIn
576630aafb9f4b1a2c7f99b79bb67d25f6719201
[ "MIT" ]
455
2016-08-11T20:59:52.000Z
2022-03-25T17:15:18.000Z
docker build -t auth0-nodejs-webapp-01-login . docker run --env-file .env -p 3000:3000 -it auth0-nodejs-webapp-01-login
40
72
0.75
e87d0f24a18efba949562de43464ce90b352c19c
95
kt
Kotlin
app/src/main/java/com/ieeevit/enigma8/model/feedback/FeedbackData.kt
IEEE-VIT/enigma8-android
fbb071f350e22ea6346b8e6773c5c83cfd7b0971
[ "MIT" ]
7
2022-01-29T08:55:33.000Z
2022-01-30T05:15:08.000Z
app/src/main/java/com/ieeevit/enigma8/model/feedback/FeedbackData.kt
IEEE-VIT/enigma8-android
fbb071f350e22ea6346b8e6773c5c83cfd7b0971
[ "MIT" ]
null
null
null
app/src/main/java/com/ieeevit/enigma8/model/feedback/FeedbackData.kt
IEEE-VIT/enigma8-android
fbb071f350e22ea6346b8e6773c5c83cfd7b0971
[ "MIT" ]
1
2022-02-08T08:36:47.000Z
2022-02-08T08:36:47.000Z
package com.ieeevit.enigma8.model.feedback data class FeedbackData ( val message : String )
13.571429
42
0.778947
e77c390b751f1d06775ef586c8e5dfab767a2ae1
9,365
js
JavaScript
api/app.js
Rafoii/Bumblebee
c1a8e77a6ae41f475e8e6dff04ff1fe2d6c2ae3c
[ "Apache-2.0" ]
1
2020-01-19T16:18:34.000Z
2020-01-19T16:18:34.000Z
api/app.js
MlataIbrahim/Bumblebee
85506040b5f62802a66be49c63cd2f2af7b6ae8d
[ "Apache-2.0" ]
null
null
null
api/app.js
MlataIbrahim/Bumblebee
85506040b5f62802a66be49c63cd2f2af7b6ae8d
[ "Apache-2.0" ]
null
null
null
require('dotenv/config') const express = require('express') const bodyParser = require('body-parser') const session = require('express-session') const app = express() var server = require('http').createServer(app) const { version } = require('./package.json') var app_url var app_host var api_url var base var ws_kernel_base var whitelist = [] function updateHost (host = 'localhost') { var kernel_host = process.env.KERNEL_HOST || host var kernel_port = process.env.KERNEL_PORT || 8888 base = 'http://'+kernel_host+':'+kernel_port ws_kernel_base = 'ws://'+kernel_host+':'+kernel_port app_host = process.env.APP_HOST || host var app_port = process.env.APP_PORT || 3000 app_url = `${app_host}:${app_port}` var api_host = process.env.HOST || host var api_port = process.env.PORT || 5000 api_url = `${api_host}:${api_port}` } updateHost () if (!process.env.DISABLE_CORS) { const cors = require('cors') whitelist = [ 'http://'+app_url, 'https://'+app_url, 'http://'+app_host, 'https://'+app_host ] var corsOptions = { origin: function (origin, callback) { if (whitelist.indexOf(origin) !== -1 || !origin) { callback(null, true) } else { callback(new Error('Not allowed by CORS')) } }, optionsSuccessStatus: 200 } app.use(cors(corsOptions)); } app.use(bodyParser.json({ limit: '100mb', })) const app_secret = process.env.APP_SECRET || '6um61e6ee' app.use(session({ secret: app_secret, resave: true, saveUninitialized: false })) app.get('/', (req, res) => { if (req.userContext && req.userContext.userinfo) { res.send(`Bumblebee API v${version}- ${req.userContext.userinfo.name}!`) } else { res.send(`Bumblebee API v${version}`) } }) var sockets = [] var kernels = [] app.post('/dataset', (req, res) => { var socketName = req.body.username || req.body.session if (!socketName || !req.body.data) { res.send({status: 'error', message: '"session/username" and "data" fields required'}) } else if (!sockets[socketName]){ res.send({status: 'error', message: 'Socket with client not found'}) } else { var datasetData = req.body.data.toString() sockets[socketName].emit('dataset',datasetData) res.send({message: 'Dataset sent'}) } }) const Server = require('socket.io') const io = new Server(server) const new_socket = function (socket, session) { sockets[session] = socket socket.emit('success') socket.on('initialize', async (payload) => { var user_session = payload.session var result var tries = 10 while (tries--) { result = await createKernel(user_session) if (result.status=='error') { console.log(result) console.log('Kernel error, retrying') await deleteKernel(user_session) } else { console.log(result) break } } socket.emit('reply',{...result, timestamp: payload.timestamp}) }) socket.on('run', async (payload) => { var user_session = payload.session var result = await run_code(`${payload.code}`,user_session) socket.emit('reply',{...result, timestamp: payload.timestamp}) }) socket.on('cells', async (payload) => { var user_session = payload.session var result = await run_code(`${payload.code} df.send(output="json", infer=False, advanced_stats=False${ payload.name ? (', name="'+payload.name+'"') : '' })`, user_session) socket.emit('reply',{...result, timestamp: payload.timestamp}) }) return socket } io.on('connection', async (socket) => { const session = socket.handshake.query.session if (!session) { socket.disconnect() return } if (sockets[session] == undefined || !sockets[session].connected || sockets[session].disconnected) { socket = new_socket(socket,session) return } setTimeout(() => { if (sockets[session] == undefined || !sockets[session].connected || sockets[session].disconnected) { new_socket(socket,session) return } socket.emit('new-error','Session already exists. Change your session name.') socket.disconnect() }, 2000); }) const request = require('request-promise') const uuidv1 = require('uuid/v1'); const run_code = async function(code = '', user_session = '') { return new Promise( async function(resolve,reject) { if (!user_session) resolve({error: 'user_session is empty'}) try { const version_response = await request({ uri: `${base}/api`, method: 'GET', headers: {}, }) const version = JSON.parse(version_response).version if (kernels[user_session]==undefined) { console.log('Jupyter Kernel Gateway Version',version) let uuid = Buffer.from( uuidv1(), 'utf8' ).toString('hex') const response = await request({ uri: `${base}/api/kernels`, method: 'POST', headers: {}, }) kernels[user_session] = { kernel: JSON.parse(response), uuid } console.log('Kernel ID for',user_session,'is',kernels[user_session].kernel['id']) } var content = { code: code+'\n', silent: false } var hdr = { 'msg_id' : kernels[user_session].uuid, 'session': kernels[user_session].uuid, 'date': new Date().toISOString(), 'msg_type': 'execute_request', 'version' : version_response.version } var codeMsg = { 'header': hdr, 'parent_header': hdr, 'metadata': {}, 'content': content } const WebSocketClient = require('websocket').client var client = new WebSocketClient({closeTimeout: 20 * 60 * 1000}) client.on('connectFailed', async function(error) { console.warn('Connection to Jupyter Kernel Gateway failed') resolve({status: 'error', content: error, error: 'Connection to Jupyter Kernel Gateway failed'}) }); client.on('connect',function(connection){ connection.on('message', async function(message) { var response = JSON.parse(message.utf8Data) if (message.type === 'utf8'){ if (response.msg_type === 'execute_result') { connection.close() resolve({status: 'ok', content: response.content.data['text/plain']}) } else if (response.msg_type === 'error') { connection.close() // console.error("Error", response.content); resolve({status: 'error', content: response.content, error: 'Error'}) } } else { connection.close() // console.error("Message type error", response.content); resolve({status: 'error', content: 'Response from gateway is not utf8 type', error: 'Message type error'}) } }); connection.on('error', async function(error) { console.error("Connection Error", error); connection.close() resolve({status: 'error', content: error, error: 'Connection error'}) }); connection.on('close', function(reason) { // console.log('Connection closed before response') resolve({status: 'error', retry: true, error: 'Connection to Jupyter Kernel Gateway closed before response', content: reason}) }); connection.sendUTF(JSON.stringify(codeMsg)) }) client.on('disconnect',async function(reason) { // console.log('Client disconnected') resolve({status: 'disconnected', retry: true, error: 'Client disconnected', content: reason}) }) // console.log('Connecting client') client.connect(`${ws_kernel_base}/api/kernels/${kernels[user_session].kernel['id']}/channels`) } catch (error) { if (error.error) resolve({status: 'error',...error, content: error.message}) else resolve({status: 'error', error: 'Internal error', content: error}) } }) } const deleteKernel = async function(session) { try { if (kernels[session] != undefined) { var _id = kernels[session].kernel['id'] kernels[session] = undefined await request({ uri: `${base}/api/kernels/${_id}`, method: 'DELETE', headers: {}, }) console.log('Deleting Jupyter Kernel Gateway session for',session,_id) } } catch (err) {} } const createKernel = async function (user_session) { if (kernels[user_session]==undefined){ return await run_code(` from optimus import Optimus op = Optimus(master="local[*]", app_name="optimus", comm=True) 'kernel init optimus init ' + op.__version__`,user_session) } else { return await run_code(` _status = 'kernel ok ' try: op _status += 'optimus ok '+ op.__version__ + ' ' try: df _status += 'dataframe ok ' except NameError: _status += '' except NameError: from optimus import Optimus op = Optimus(master="local[*]", app_name="optimus", comm=True) _status = 'optimus init ' + op.__version__ + ' ' _status`,user_session) } } const startServer = async () => { const port = process.env.PORT || 5000 const host = process.env.HOST || '0.0.0.0' var _server = server.listen(port, host, async () => { console.log(`Bumblebee-api v${version} listening on ${host}:${port}`) try { const response = await request({ uri: `${base}/api/kernels`, method: 'GET', headers: {}, }) const kernels = JSON.parse(response) if (process.env.NODE_ENV == 'production') { kernels.forEach(async kernel => { console.log(`Deleting kernel ${kernel.id}`) await request({ uri: `${base}/api/kernels/${kernel.id}`, method: 'DELETE', headers: {}, }) }); } } catch (error) {} }) _server.timeout = 10 * 60 * 1000; } startServer()
24.388021
131
0.641111
98a4d099ebb557a46efdb9573b256a68e49bc56c
660
asm
Assembly
oeis/022/A022365.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/022/A022365.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/022/A022365.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A022365: Fibonacci sequence beginning 0, 31. ; Submitted by Jon Maiga ; 0,31,31,62,93,155,248,403,651,1054,1705,2759,4464,7223,11687,18910,30597,49507,80104,129611,209715,339326,549041,888367,1437408,2325775,3763183,6088958,9852141,15941099,25793240,41734339,67527579,109261918,176789497,286051415,462840912,748892327,1211733239,1960625566,3172358805,5132984371,8305343176,13438327547,21743670723,35181998270,56925668993,92107667263,149033336256,241141003519,390174339775,631315343294,1021489683069,1652805026363,2674294709432,4327099735795,7001394445227,11328494181022 mov $3,1 lpb $0 sub $0,1 mov $2,$3 add $3,$1 mov $1,$2 lpe mov $0,$1 mul $0,31
47.142857
499
0.815152
514996b81956e62b1c57bd823c7dac985aebe8f5
2,718
dart
Dart
lib/auth/firebase_auth.dart
codekaze/fireverse
d55c45bef79ff1b049c7e33f043b0a06d04f3660
[ "Apache-2.0" ]
null
null
null
lib/auth/firebase_auth.dart
codekaze/fireverse
d55c45bef79ff1b049c7e33f043b0a06d04f3660
[ "Apache-2.0" ]
null
null
null
lib/auth/firebase_auth.dart
codekaze/fireverse
d55c45bef79ff1b049c7e33f043b0a06d04f3660
[ "Apache-2.0" ]
null
null
null
import 'package:fireverse/auth/auth_gateway.dart'; import 'package:fireverse/auth/client.dart'; import 'package:fireverse/auth/token_provider.dart'; import 'package:fireverse/auth/token_store.dart'; import 'package:fireverse/auth/user_gateway.dart'; import 'package:http/http.dart' as http; class FireDartFirebaseAuth { /* Singleton interface */ static FireDartFirebaseAuth? _instance; static FireDartFirebaseAuth initialize( String apiKey, FireDartTokenStore tokenStore) { if (_instance != null) { throw Exception('FirebaseAuth instance was already initialized'); } _instance = FireDartFirebaseAuth(apiKey, tokenStore); return _instance!; } static FireDartFirebaseAuth get instance { if (_instance == null) { throw Exception( "FirebaseAuth hasn't been initialized. Please call FirebaseAuth.initialize() before using it."); } return _instance!; } /* Instance interface */ final String apiKey; http.Client httpClient; late FireDartTokenProvider tokenProvider; late FireDartAuthGateway _authGateway; late FireDartUserGateway _userGateway; FireDartFirebaseAuth(this.apiKey, FireDartTokenStore tokenStore, {http.Client? httpClient}) : assert(apiKey.isNotEmpty), httpClient = httpClient ?? http.Client() { var keyClient = FireDartKeyClient(this.httpClient, apiKey); tokenProvider = FireDartTokenProvider(keyClient, tokenStore); _authGateway = FireDartAuthGateway(keyClient, tokenProvider); _userGateway = FireDartUserGateway(keyClient, tokenProvider); } bool get isSignedIn => tokenProvider.isSignedIn; Stream<bool> get signInState => tokenProvider.signInState; String get userId { if (!isSignedIn) throw Exception('User signed out'); return tokenProvider.userId!; } Future<FireDartUser> signUp(String email, String password) => _authGateway.signUp(email, password); Future<FireDartUser> signIn(String email, String password) => _authGateway.signIn(email, password); Future<FireDartUser> signInAnonymously() => _authGateway.signInAnonymously(); void signOut() => tokenProvider.signOut(); Future<void> resetPassword(String email) => _authGateway.resetPassword(email); Future<void> requestEmailVerification() => _userGateway.requestEmailVerification(); Future<void> changePassword(String password) => _userGateway.changePassword(password); Future<FireDartUser> getUser() => _userGateway.getUser(); Future<void> updateProfile({String? displayName, String? photoUrl}) => _userGateway.updateProfile(displayName, photoUrl); Future<void> deleteAccount() async { await _userGateway.deleteAccount(); signOut(); } }
31.604651
106
0.740618
9f3d90efe83db67ca18c23d7f37d593f30ddde8e
4,125
sql
SQL
data base/Dump20180305-telmex VIP/telmex_vip_estado_ot.sql
pabloestebanZTE/Telmex-VIP
9a19a9da854b89f88ea7b7c2eb0972716f545554
[ "MIT" ]
null
null
null
data base/Dump20180305-telmex VIP/telmex_vip_estado_ot.sql
pabloestebanZTE/Telmex-VIP
9a19a9da854b89f88ea7b7c2eb0972716f545554
[ "MIT" ]
null
null
null
data base/Dump20180305-telmex VIP/telmex_vip_estado_ot.sql
pabloestebanZTE/Telmex-VIP
9a19a9da854b89f88ea7b7c2eb0972716f545554
[ "MIT" ]
null
null
null
-- MySQL dump 10.13 Distrib 5.7.17, for Win64 (x86_64) -- -- Host: 127.0.0.1 Database: telmex_vip -- ------------------------------------------------------ -- Server version 5.5.5-10.1.28-MariaDB /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `estado_ot` -- DROP TABLE IF EXISTS `estado_ot`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `estado_ot` ( `k_id_estado_ot` int(11) NOT NULL AUTO_INCREMENT, `k_id_tipo` int(11) DEFAULT NULL, `n_name_estado_ot` varchar(100) NOT NULL, PRIMARY KEY (`k_id_estado_ot`), KEY `fk_estado_tipo_ot` (`k_id_tipo`), CONSTRAINT `fk_estado_tipo_ot` FOREIGN KEY (`k_id_tipo`) REFERENCES `tipo_ot_hija` (`k_id_tipo`) ) ENGINE=InnoDB AUTO_INCREMENT=74 DEFAULT CHARSET=latin1; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `estado_ot` -- LOCK TABLES `estado_ot` WRITE; /*!40000 ALTER TABLE `estado_ot` DISABLE KEYS */; INSERT INTO `estado_ot` VALUES (1,1,'Generada'),(2,1,'Cancelada'),(3,1,'Cerrada'),(4,2,'Generada'),(5,2,'Gestión VOC'),(6,2,'OBRA CIVIL Gestión SIAO'),(7,2,'OBRA CIVIL Cotización'),(8,2,'OBRA CIVIL Envío Cot'),(9,2,'OBRA CIVIL Aprobación Cliente'),(10,2,'OBRA CIVIL Devolución'),(11,2,'OBRA CIVIL Factibit'),(12,2,'Cancelada'),(13,2,'Cerrada'),(14,3,'CONF.Ing de Detalle/plan Técnico'),(15,3,'PSR'),(16,3,'CONF.Configuración de Servicios'),(17,3,'Cancelada'),(18,3,'Cerrada'),(19,4,'INST.PLANTA Gestión SIAO'),(20,4,'INST.PLANTA Tendido Interno OC'),(21,4,'INST.PLANTA Envío Instalación'),(22,4,'Cancelada'),(23,4,'Cerrada'),(24,5,'Generada'),(25,5,'Pendiente Cliente'),(26,5,'Problema Ejecu. OC'),(27,5,'Problema VOC'),(28,5,'Terminada'),(29,5,'Cancelada'),(30,5,'Cerrada'),(31,6,'Generada'),(32,6,'En ejecución'),(33,6,'Terminada'),(34,6,'Cancelada'),(35,6,'Cerrada'),(36,7,'Gestión SIAO'),(37,7,'INST.PLANTA Replanteo'),(38,7,'Apto.Arriendo Infraestr'),(39,7,'INST.PLANTA Ruta'),(40,7,'Terminada'),(41,7,'Cancelada'),(42,7,'Cerrada'),(43,8,'Instalación Terceros GP'),(44,8,'Instalación Terceros Tend Externo'),(45,8,'Instalación Terceros Envió Instalación'),(46,8,'Terminada'),(47,8,'Cancelada'),(48,8,'Cerrada'),(49,9,'EQUIPOS Solicitud'),(50,9,'EQUIPOS Gestión SIAO'),(51,9,'Reserva Equ.Estándar'),(52,9,'Reserva Equ.No Estándar'),(53,9,'Gest.Comp.Estándar'),(54,9,'Gest.Comp.No-Estándar'),(55,9,'Asignación-Legalización.Eq'),(56,9,'EQUIPOS.Verificar Equipos'),(57,9,'EQUIPOS.Salida Equipos'),(58,9,'Cancelada'),(59,9,'Cerrada'),(60,10,'Visita.Cliente Gestión'),(61,10,'Visita.Cliente Planeación y Asignación'),(62,10,'Gestion Permisos'),(63,10,'Visita.Cliente Ejecución Contratista'),(64,10,'Entrega.Cliente'),(65,10,'Cancelada'),(66,10,'Cerrada'),(67,11,'Visita.Cliente Gestión'),(68,11,'Visita.Cliente Planeación y Asignación'),(69,11,'Gestión Permisos'),(70,11,'Visita.Cliente Ejecución Contratista'),(71,11,'Entrega Cliente'),(72,11,'Cancelada'),(73,11,'Cerrada'); /*!40000 ALTER TABLE `estado_ot` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2018-03-05 10:24:15
75
1,975
0.693818
682c974b126a3e0b2c9aa9bb08d4af3fd6193e7a
2,908
inl
C++
src/vcm/vcm/PathVertexMap.inl
PearCoding/PearRay
8654a7dcd55cc67859c7c057c7af64901bf97c35
[ "MIT" ]
19
2016-11-07T00:01:19.000Z
2021-12-29T05:35:14.000Z
src/vcm/vcm/PathVertexMap.inl
PearCoding/PearRay
8654a7dcd55cc67859c7c057c7af64901bf97c35
[ "MIT" ]
33
2016-07-06T21:58:05.000Z
2020-08-01T18:18:24.000Z
src/vcm/vcm/PathVertexMap.inl
PearCoding/PearRay
8654a7dcd55cc67859c7c057c7af64901bf97c35
[ "MIT" ]
null
null
null
// IWYU pragma: private, include "vcm/PathVertexMap.h" namespace PR { namespace VCM { PathVertexMap::PathVertexMap(const BoundingBox& bbox, float gridDelta, const std::vector<PathVertex>& vertices) : HashGrid(bbox, gridDelta, vcm_position_getter<size_t>{ vertices }) , mVertices(vertices) { } PathVertexMap::~PathVertexMap() { } template <typename AccumFunction> SpectralBlob PathVertexMap::estimateSphere(const QuerySphere& sphere, const AccumFunction& accumFunc, size_t& found) const { static const auto estSphereSqueeze = [](const PathVertex& pht, const QuerySphere& sph, float& dist2) { const Vector3f V = pht.IP.P - sph.Center; dist2 = V.squaredNorm(); const float d = V.dot(sph.Normal); const float r = sph.Distance2 * (1 - std::abs(d)) + sph.Distance2 * std::abs(d) * (1 - sph.SqueezeWeight); return dist2 <= r; }; static const auto estSphereNoSqueeze = [](const PathVertex& pht, const QuerySphere& sph, float& dist2) { const Vector3f V = pht.IP.P - sph.Center; dist2 = V.squaredNorm(); return dist2 <= sph.Distance2; }; if (sphere.SqueezeWeight > PR_EPSILON) return estimate<AccumFunction>(sphere, estSphereSqueeze, accumFunc, found); else return estimate<AccumFunction>(sphere, estSphereNoSqueeze, accumFunc, found); } template <typename AccumFunction> SpectralBlob PathVertexMap::estimateDome(const QuerySphere& sphere, const AccumFunction& accumFunc, size_t& found) const { static const auto estDomeSqueeze = [](const PathVertex& pht, const QuerySphere& sph, float& dist2) { const Vector3f V = pht.IP.P - sph.Center; dist2 = V.squaredNorm(); const float d = V.dot(sph.Normal); const float k = -pht.IP.Ray.Direction.dot(sph.Normal); const float r = sph.Distance2 * (1 - std::abs(d)) + sph.Distance2 * std::abs(d) * (1 - sph.SqueezeWeight); return k > -PR_EPSILON && dist2 <= r; }; static const auto estDomeNoSqueeze = [](const PathVertex& pht, const QuerySphere& sph, float& dist2) { const Vector3f V = pht.IP.P - sph.Center; dist2 = V.squaredNorm(); const float k = -pht.IP.Ray.Direction.dot(sph.Normal); return k > -PR_EPSILON && dist2 <= sph.Distance2; }; if (sphere.SqueezeWeight > PR_EPSILON) return estimate<AccumFunction>(sphere, estDomeSqueeze, accumFunc, found); else return estimate<AccumFunction>(sphere, estDomeNoSqueeze, accumFunc, found); } template <typename AccumFunction> SpectralBlob PathVertexMap::estimate(const QuerySphere& sphere, const CheckFunction& checkFunc, const AccumFunction& accumFunc, size_t& found) const { found = 0; SpectralBlob spec = SpectralBlob::Zero(); search<true>(sphere.Center, sphere.Distance2, [&](size_t id) { const PathVertex& pht = mVertices[id]; // Bad Hack? float dist2 = 0; if (checkFunc(pht, sphere, dist2)) { // Found a photon! found++; accumFunc(spec, pht, dist2); } }); return spec; } } // namespace VCM } // namespace PR
36.35
122
0.711486
c25b0eaff47b6b6c0d6e54a67a319e29113d0f80
887
swift
Swift
Allowance/Util/Color+Hex.swift
RohanNagar/allowance
8f072bdc22de9edb01dbc9969ee8666fa35dba53
[ "MIT" ]
null
null
null
Allowance/Util/Color+Hex.swift
RohanNagar/allowance
8f072bdc22de9edb01dbc9969ee8666fa35dba53
[ "MIT" ]
null
null
null
Allowance/Util/Color+Hex.swift
RohanNagar/allowance
8f072bdc22de9edb01dbc9969ee8666fa35dba53
[ "MIT" ]
1
2021-03-30T22:06:17.000Z
2021-03-30T22:06:17.000Z
// // Color+Hex.swift // Allowance // // Created by Rohan Nagar on 2/19/21. // import Foundation import SwiftUI extension Color { init(hexString: String, opacity: Double = 1.0) { var hString = hexString if hexString.hasPrefix("#") { let start = hexString.index(hexString.startIndex, offsetBy: 1) hString = String(hexString[start...]) } let scanner = Scanner(string: hString) var hexNumber: UInt64 = 0 if scanner.scanHexInt64(&hexNumber) { self.init(hex: hexNumber, opacity: opacity) } else { self.init(hex: 0x000000, opacity: opacity) } } init(hex: UInt64, opacity:Double = 1.0) { let red = Double((hex & 0xff0000) >> 16) / 255.0 let green = Double((hex & 0xff00) >> 8) / 255.0 let blue = Double((hex & 0xff) >> 0) / 255.0 self.init(.sRGB, red: red, green: green, blue: blue, opacity: opacity) } }
23.972973
74
0.621195
b9925957aa3011e13334a6d3f4692fb48345f4b6
3,015
c
C
examples/tls_client/main.c
Ichishino/coldforce
dcdc9c4dfd4e396920aed2f275e233fecca2d697
[ "MIT" ]
null
null
null
examples/tls_client/main.c
Ichishino/coldforce
dcdc9c4dfd4e396920aed2f275e233fecca2d697
[ "MIT" ]
null
null
null
examples/tls_client/main.c
Ichishino/coldforce
dcdc9c4dfd4e396920aed2f275e233fecca2d697
[ "MIT" ]
null
null
null
#include <coldforce/coldforce_tls.h> #include <stdio.h> #include <string.h> // my app object typedef struct { co_app_t base_app; // my app data co_tcp_client_t* client; co_timer_t* retry_timer; } my_app; void my_connect(my_app* self); void on_my_tls_receive(my_app* self, co_tcp_client_t* client) { (void)self; for (;;) { char buffer[1024]; ssize_t size = co_tls_receive(client, buffer, sizeof(buffer)); if (size <= 0) { break; } printf("receive %zd bytes\n", (size_t)size); } } void on_my_tls_close(my_app* self, co_tcp_client_t* client) { (void)client; printf("close\n"); co_tls_client_destroy(self->client); self->client = NULL; // quit app co_net_app_stop(); } void on_my_tls_connect(my_app* self, co_tcp_client_t* client, int error_code) { if (error_code == 0) { printf("connect success\n"); // send const char* data = "hello"; co_tls_send(client, data, strlen(data)); } else { printf("connect failed\n"); co_tls_client_destroy(self->client); self->client = NULL; // start retry timer co_timer_start(self->retry_timer); } } void on_my_retry_timer(my_app* self, co_timer_t* timer) { (void)timer; // connect retry my_connect(self); } void my_connect(my_app* self) { const char* ip_address = "127.0.0.1"; uint16_t port = 9443; // local address co_net_addr_t local_net_addr = CO_NET_ADDR_INIT; co_net_addr_set_family(&local_net_addr, CO_ADDRESS_FAMILY_IPV4); self->client = co_tls_client_create(&local_net_addr, NULL); co_tls_set_receive_handler(self->client, (co_tcp_receive_fn)on_my_tls_receive); co_tls_set_close_handler(self->client, (co_tcp_close_fn)on_my_tls_close); // remote address co_net_addr_t remote_net_addr = CO_NET_ADDR_INIT; co_net_addr_set_address(&remote_net_addr, ip_address); co_net_addr_set_port(&remote_net_addr, port); // connect co_tls_connect( self->client, &remote_net_addr, (co_tcp_connect_fn)on_my_tls_connect); char remote_str[64]; co_net_addr_get_as_string(&remote_net_addr, remote_str); printf("connect to %s\n", remote_str); } bool on_my_app_create(my_app* self, const co_arg_st* arg) { (void)arg; // connect retry timer self->retry_timer = co_timer_create( 5000, (co_timer_fn)on_my_retry_timer, false, 0); // connect my_connect(self); return true; } void on_my_app_destroy(my_app* self) { co_timer_destroy(self->retry_timer); co_tls_client_destroy(self->client); } int main(int argc, char* argv[]) { co_tls_setup(); my_app app; co_net_app_init( (co_app_t*)&app, (co_app_create_fn)on_my_app_create, (co_app_destroy_fn)on_my_app_destroy); // app start int exit_code = co_net_app_start((co_app_t*)&app, argc, argv); co_tls_cleanup(); return exit_code; }
20.510204
83
0.660365
dd04b576ae057da96b54af9d7d1910e55d5d7692
7,440
asm
Assembly
working/m12-enemynames.asm
Imavoyc/Mother2Gba-chs
1e285d3e58d2371045bc0680fb09fa3912af5a78
[ "MIT" ]
null
null
null
working/m12-enemynames.asm
Imavoyc/Mother2Gba-chs
1e285d3e58d2371045bc0680fb09fa3912af5a78
[ "MIT" ]
null
null
null
working/m12-enemynames.asm
Imavoyc/Mother2Gba-chs
1e285d3e58d2371045bc0680fb09fa3912af5a78
[ "MIT" ]
1
2022-02-18T17:39:42.000Z
2022-02-18T17:39:42.000Z
.org 0x8C032CC :: .incbin "m12-enemynames.bin" .org 0x8B1A2F4 :: dw 0x000E97FC .org 0x8B1A2F8 :: dw 0x000E9802 .org 0x8B1A2FC :: dw 0x000E9812 .org 0x8B1A300 :: dw 0x000E9825 .org 0x8B1A304 :: dw 0x000E9833 .org 0x8B1A308 :: dw 0x000E9840 .org 0x8B1A30C :: dw 0x000E984E .org 0x8B1A310 :: dw 0x000E985A .org 0x8B1A314 :: dw 0x000E9872 .org 0x8B1A318 :: dw 0x000E988B .org 0x8B1A31C :: dw 0x000E989A .org 0x8B1A320 :: dw 0x000E98AF .org 0x8B1A324 :: dw 0x000E98C2 .org 0x8B1A328 :: dw 0x000E98D3 .org 0x8B1A32C :: dw 0x000E98E7 .org 0x8B1A330 :: dw 0x000E98FE .org 0x8B1A334 :: dw 0x000E9913 .org 0x8B1A338 :: dw 0x000E992A .org 0x8B1A33C :: dw 0x000E993A .org 0x8B1A340 :: dw 0x000E994D .org 0x8B1A344 :: dw 0x000E9960 .org 0x8B1A348 :: dw 0x000E9970 .org 0x8B1A34C :: dw 0x000E997F .org 0x8B1A350 :: dw 0x000E9997 .org 0x8B1A354 :: dw 0x000E99A9 .org 0x8B1A358 :: dw 0x000E99BF .org 0x8B1A35C :: dw 0x000E99D5 .org 0x8B1A360 :: dw 0x000E99E5 .org 0x8B1A364 :: dw 0x000E99F1 .org 0x8B1A368 :: dw 0x000E99FE .org 0x8B1A36C :: dw 0x000E9A11 .org 0x8B1A370 :: dw 0x000E9A22 .org 0x8B1A374 :: dw 0x000E9A30 .org 0x8B1A378 :: dw 0x000E9A3D .org 0x8B1A37C :: dw 0x000E9A50 .org 0x8B1A380 :: dw 0x000E9A58 .org 0x8B1A384 :: dw 0x000E9A63 .org 0x8B1A388 :: dw 0x000E9A6F .org 0x8B1A38C :: dw 0x000E9A7C .org 0x8B1A390 :: dw 0x000E9A8A .org 0x8B1A394 :: dw 0x000E9A94 .org 0x8B1A398 :: dw 0x000E9AA8 .org 0x8B1A39C :: dw 0x000E9AB4 .org 0x8B1A3A0 :: dw 0x000E9AC5 .org 0x8B1A3A4 :: dw 0x000E9ADA .org 0x8B1A3A8 :: dw 0x000E9AE7 .org 0x8B1A3AC :: dw 0x000E9AFA .org 0x8B1A3B0 :: dw 0x000E9B14 .org 0x8B1A3B4 :: dw 0x000E9B1F .org 0x8B1A3B8 :: dw 0x000E9B2C .org 0x8B1A3BC :: dw 0x000E9B34 .org 0x8B1A3C0 :: dw 0x000E9B43 .org 0x8B1A3C4 :: dw 0x000E9B52 .org 0x8B1A3C8 :: dw 0x000E9B61 .org 0x8B1A3CC :: dw 0x000E9B76 .org 0x8B1A3D0 :: dw 0x000E9B7B .org 0x8B1A3D4 :: dw 0x000E9B87 .org 0x8B1A3D8 :: dw 0x000E9B9B .org 0x8B1A3DC :: dw 0x000E9BA6 .org 0x8B1A3E0 :: dw 0x000E9BB3 .org 0x8B1A3E4 :: dw 0x000E9BC2 .org 0x8B1A3E8 :: dw 0x000E9BD7 .org 0x8B1A3EC :: dw 0x000E9BE4 .org 0x8B1A3F0 :: dw 0x000E9BF4 .org 0x8B1A3F4 :: dw 0x000E9C0C .org 0x8B1A3F8 :: dw 0x000E9C18 .org 0x8B1A3FC :: dw 0x000E9C22 .org 0x8B1A400 :: dw 0x000E9C32 .org 0x8B1A404 :: dw 0x000E9C3B .org 0x8B1A408 :: dw 0x000E9C4A .org 0x8B1A40C :: dw 0x000E9C5C .org 0x8B1A410 :: dw 0x000E9C6C .org 0x8B1A414 :: dw 0x000E9C83 .org 0x8B1A418 :: dw 0x000E9C9A .org 0x8B1A41C :: dw 0x000E9CAC .org 0x8B1A420 :: dw 0x000E9CBC .org 0x8B1A424 :: dw 0x000E9CCB .org 0x8B1A428 :: dw 0x000E9CD9 .org 0x8B1A42C :: dw 0x000E9CEB .org 0x8B1A430 :: dw 0x000E9CF7 .org 0x8B1A434 :: dw 0x000E9D04 .org 0x8B1A438 :: dw 0x000E9D16 .org 0x8B1A43C :: dw 0x000E9D27 .org 0x8B1A440 :: dw 0x000E9D3A .org 0x8B1A444 :: dw 0x000E9D47 .org 0x8B1A448 :: dw 0x000E9D59 .org 0x8B1A44C :: dw 0x000E9D6B .org 0x8B1A450 :: dw 0x000E9D7F .org 0x8B1A454 :: dw 0x000E9D91 .org 0x8B1A458 :: dw 0x000E9D9B .org 0x8B1A45C :: dw 0x000E9DA9 .org 0x8B1A460 :: dw 0x000E9DBD .org 0x8B1A464 :: dw 0x000E9DC5 .org 0x8B1A468 :: dw 0x000E9DD2 .org 0x8B1A46C :: dw 0x000E9DE0 .org 0x8B1A470 :: dw 0x000E9DF2 .org 0x8B1A474 :: dw 0x000E9DFF .org 0x8B1A478 :: dw 0x000E9E0E .org 0x8B1A47C :: dw 0x000E9E24 .org 0x8B1A480 :: dw 0x000E9E2B .org 0x8B1A484 :: dw 0x000E9E32 .org 0x8B1A488 :: dw 0x000E9E3B .org 0x8B1A48C :: dw 0x000E9E43 .org 0x8B1A490 :: dw 0x000E9E50 .org 0x8B1A494 :: dw 0x000E9E60 .org 0x8B1A498 :: dw 0x000E9E6F .org 0x8B1A49C :: dw 0x000E9E84 .org 0x8B1A4A0 :: dw 0x000E9E91 .org 0x8B1A4A4 :: dw 0x000E9E9E .org 0x8B1A4A8 :: dw 0x000E9EAC .org 0x8B1A4AC :: dw 0x000E9EBA .org 0x8B1A4B0 :: dw 0x000E9EC4 .org 0x8B1A4B4 :: dw 0x000E9ED1 .org 0x8B1A4B8 :: dw 0x000E9EE0 .org 0x8B1A4BC :: dw 0x000E9EED .org 0x8B1A4C0 :: dw 0x000E9EFB .org 0x8B1A4C4 :: dw 0x000E9F0B .org 0x8B1A4C8 :: dw 0x000E9F1C .org 0x8B1A4CC :: dw 0x000E9F2A .org 0x8B1A4D0 :: dw 0x000E9F37 .org 0x8B1A4D4 :: dw 0x000E9F43 .org 0x8B1A4D8 :: dw 0x000E9F59 .org 0x8B1A4DC :: dw 0x000E9F66 .org 0x8B1A4E0 :: dw 0x000E9F7A .org 0x8B1A4E4 :: dw 0x000E9F84 .org 0x8B1A4E8 :: dw 0x000E9F92 .org 0x8B1A4EC :: dw 0x000E9FA1 .org 0x8B1A4F0 :: dw 0x000E9FB7 .org 0x8B1A4F4 :: dw 0x000E9FC0 .org 0x8B1A4F8 :: dw 0x000E9FD3 .org 0x8B1A4FC :: dw 0x000E9FE3 .org 0x8B1A500 :: dw 0x000E9FF8 .org 0x8B1A504 :: dw 0x000E9FFF .org 0x8B1A508 :: dw 0x000EA00E .org 0x8B1A50C :: dw 0x000EA01D .org 0x8B1A510 :: dw 0x000EA028 .org 0x8B1A514 :: dw 0x000EA033 .org 0x8B1A518 :: dw 0x000EA03D .org 0x8B1A51C :: dw 0x000EA04D .org 0x8B1A520 :: dw 0x000EA05B .org 0x8B1A524 :: dw 0x000EA071 .org 0x8B1A528 :: dw 0x000EA07F .org 0x8B1A52C :: dw 0x000EA094 .org 0x8B1A530 :: dw 0x000EA0A4 .org 0x8B1A534 :: dw 0x000EA0BA .org 0x8B1A538 :: dw 0x000EA0CE .org 0x8B1A53C :: dw 0x000EA0DA .org 0x8B1A540 :: dw 0x000EA0E8 .org 0x8B1A544 :: dw 0x000EA0FE .org 0x8B1A548 :: dw 0x000EA10F .org 0x8B1A54C :: dw 0x000EA118 .org 0x8B1A550 :: dw 0x000EA122 .org 0x8B1A554 :: dw 0x000EA132 .org 0x8B1A558 :: dw 0x000EA13D .org 0x8B1A55C :: dw 0x000EA148 .org 0x8B1A560 :: dw 0x000EA159 .org 0x8B1A564 :: dw 0x000EA16B .org 0x8B1A568 :: dw 0x000EA17B .org 0x8B1A56C :: dw 0x000EA188 .org 0x8B1A570 :: dw 0x000EA198 .org 0x8B1A574 :: dw 0x000EA1A7 .org 0x8B1A578 :: dw 0x000EA1AF .org 0x8B1A57C :: dw 0x000EA1B6 .org 0x8B1A580 :: dw 0x000EA1BD .org 0x8B1A584 :: dw 0x000EA1C3 .org 0x8B1A588 :: dw 0x000EA1D2 .org 0x8B1A58C :: dw 0x000EA1DF .org 0x8B1A590 :: dw 0x000EA1EB .org 0x8B1A594 :: dw 0x000EA1F7 .org 0x8B1A598 :: dw 0x000EA209 .org 0x8B1A59C :: dw 0x000EA217 .org 0x8B1A5A0 :: dw 0x000EA227 .org 0x8B1A5A4 :: dw 0x000EA23A .org 0x8B1A5A8 :: dw 0x000EA249 .org 0x8B1A5AC :: dw 0x000EA259 .org 0x8B1A5B0 :: dw 0x000EA265 .org 0x8B1A5B4 :: dw 0x000EA271 .org 0x8B1A5B8 :: dw 0x000EA27E .org 0x8B1A5BC :: dw 0x000EA28C .org 0x8B1A5C0 :: dw 0x000EA296 .org 0x8B1A5C4 :: dw 0x000EA2AA .org 0x8B1A5C8 :: dw 0x000EA2B6 .org 0x8B1A5CC :: dw 0x000EA2C7 .org 0x8B1A5D0 :: dw 0x000EA2CF .org 0x8B1A5D4 :: dw 0x000EA2DE .org 0x8B1A5D8 :: dw 0x000EA2E7 .org 0x8B1A5DC :: dw 0x000EA2F6 .org 0x8B1A5E0 :: dw 0x000EA308 .org 0x8B1A5E4 :: dw 0x000EA318 .org 0x8B1A5E8 :: dw 0x000EA327 .org 0x8B1A5EC :: dw 0x000EA335 .org 0x8B1A5F0 :: dw 0x000EA342 .org 0x8B1A5F4 :: dw 0x000EA356 .org 0x8B1A5F8 :: dw 0x000EA364 .org 0x8B1A5FC :: dw 0x000EA376 .org 0x8B1A600 :: dw 0x000EA383 .org 0x8B1A604 :: dw 0x000EA390 .org 0x8B1A608 :: dw 0x000EA398 .org 0x8B1A60C :: dw 0x000EA3A5 .org 0x8B1A610 :: dw 0x000EA3B5 .org 0x8B1A614 :: dw 0x000EA3BF .org 0x8B1A618 :: dw 0x000EA3D0 .org 0x8B1A61C :: dw 0x000EA3E3 .org 0x8B1A620 :: dw 0x000EA3F8 .org 0x8B1A624 :: dw 0x000EA408 .org 0x8B1A628 :: dw 0x000EA41D .org 0x8B1A62C :: dw 0x000EA42B .org 0x8B1A630 :: dw 0x000EA436 .org 0x8B1A634 :: dw 0x000EA43D .org 0x8B1A638 :: dw 0x000EA44F .org 0x8B1A63C :: dw 0x000EA45D .org 0x8B1A640 :: dw 0x000EA476 .org 0x8B1A644 :: dw 0x000EA483 .org 0x8B1A648 :: dw 0x000EA48D .org 0x8B1A64C :: dw 0x000EA49E .org 0x8B1A650 :: dw 0x000EA4AE .org 0x8B1A654 :: dw 0x000EA4B9 .org 0x8B1A658 :: dw 0x000EA4CE .org 0x8B1A65C :: dw 0x000EA4E3 .org 0x8B1A660 :: dw 0x000EA4EB .org 0x8B1A664 :: dw 0x000EA4F3 .org 0x8B1A668 :: dw 0x000EA4FB .org 0x8B1A66C :: dw 0x000EA503 .org 0x8B1A670 :: dw 0x000EA510 .org 0x8B1A674 :: dw 0x000EA526 .org 0x8B1A678 :: dw 0x000EA530 .org 0x8B1A67C :: dw 0x000EA541 .org 0x8B1A680 :: dw 0x000EA54C .org 0x8B1A684 :: dw 0x000EA562 .org 0x8B1A688 :: dw 0x000EA572 .org 0x8B1A68C :: dw 0x000EA57A
31.794872
46
0.749731
03044f42aab65158fb8b51932e7c88941c9c997c
3,311
dart
Dart
lib/src/channel/channel.dart
amondnet/pusher.dart
d88f62f64f976d490286341c3e4a0becd3a38bb4
[ "MIT" ]
null
null
null
lib/src/channel/channel.dart
amondnet/pusher.dart
d88f62f64f976d490286341c3e4a0becd3a38bb4
[ "MIT" ]
null
null
null
lib/src/channel/channel.dart
amondnet/pusher.dart
d88f62f64f976d490286341c3e4a0becd3a38bb4
[ "MIT" ]
null
null
null
import 'subscription_event_listener.dart'; abstract class Channel { /// Gets the name of the Pusher channel that this object represents. /// /// @return The name of the channel. String get name; /// Binds a {@link SubscriptionEventListener} to an event. The /// {@link SubscriptionEventListener} will be notified whenever the specified /// event is received on this channel. /// /// @param eventName /// The name of the event to listen to. /// @param listener /// A listener to receive notifications when the event is /// received. /// @throws IllegalArgumentException /// If either of the following are true: /// <ul> /// <li>The name of the event is null.</li> /// <li>The {@link SubscriptionEventListener} is null.</li> /// </ul> /// @throws IllegalStateException /// If the channel has been unsubscribed by calling /// {@link com.pusher.client.Pusher#unsubscribe(String)}. This /// puts the {@linkplain Channel} in a terminal state from which /// it can no longer be used. To resubscribe, call /// {@link com.pusher.client.Pusher#subscribe(String)} or /// {@link com.pusher.client.Pusher#subscribe(String, ChannelEventListener, String...)} /// again to receive a fresh {@linkplain Channel} instance. Future<void> bind(String eventName, SubscriptionEventListener listener); /// <p> /// Unbinds a previously bound {@link SubscriptionEventListener} from an /// event. The {@link SubscriptionEventListener} will no longer be notified /// whenever the specified event is received on this channel. /// </p> /// /// <p> /// Calling this method does not unsubscribe from the channel even if there /// are no more {@link SubscriptionEventListener}s bound to it. If you want /// to unsubscribe from the channel completely, call /// {@link com.pusher.client.Pusher#unsubscribe(String)}. It is not necessary /// to unbind your {@link SubscriptionEventListener}s first. /// </p> /// /// @param eventName /// The name of the event to stop listening to. /// @param listener /// The listener to unbind from the event. /// @throws IllegalArgumentException /// If either of the following are true: /// <ul> /// <li>The name of the event is null.</li> /// <li>The {@link SubscriptionEventListener} is null.</li> /// </ul> /// @throws IllegalStateException /// If the channel has been unsubscribed by calling /// {@link com.pusher.client.Pusher#unsubscribe(String)}. This /// puts the {@linkplain Channel} in a terminal state from which /// it can no longer be used. To resubscribe, call /// {@link com.pusher.client.Pusher#subscribe(String)} or /// {@link com.pusher.client.Pusher#subscribe(String, ChannelEventListener, String...)} /// again to receive a fresh {@linkplain Channel} instance. Future<void> unbind(String eventName, SubscriptionEventListener listener); /// /// @return Whether or not the channel is subscribed. bool get isSubscribed; }
45.986111
101
0.623377
fb7397baa658d6c847a93a03b800ca726c6f3f78
2,259
c
C
standalone/pruntime/rizin/librz/bin/p/bin_ningba.c
ndkazu/guessNumber-vs-Bot
6e756977ce849137c62edb0716df6926583da9b2
[ "Apache-2.0" ]
null
null
null
standalone/pruntime/rizin/librz/bin/p/bin_ningba.c
ndkazu/guessNumber-vs-Bot
6e756977ce849137c62edb0716df6926583da9b2
[ "Apache-2.0" ]
null
null
null
standalone/pruntime/rizin/librz/bin/p/bin_ningba.c
ndkazu/guessNumber-vs-Bot
6e756977ce849137c62edb0716df6926583da9b2
[ "Apache-2.0" ]
null
null
null
// SPDX-FileCopyrightText: 2014-2019 condret <condr3t@protonmail.com> // SPDX-License-Identifier: LGPL-3.0-only #include <rz_types.h> #include <rz_util.h> #include <rz_lib.h> #include <rz_bin.h> #include <string.h> #include "../format/nin/gba.h" static bool check_buffer(RzBuffer *b) { ut8 lict[156]; rz_return_val_if_fail(b, false); rz_buf_read_at(b, 4, (ut8 *)lict, sizeof(lict)); return !memcmp(lict, lic_gba, 156); } static bool load_buffer(RzBinFile *bf, RzBinObject *obj, RzBuffer *buf, Sdb *sdb) { return check_buffer(buf); } static RzList *entries(RzBinFile *bf) { RzList *ret = rz_list_newf(free); RzBinAddr *ptr = NULL; if (bf && bf->buf) { if (!ret) { return NULL; } if (!(ptr = RZ_NEW0(RzBinAddr))) { return ret; } ptr->paddr = ptr->vaddr = 0x8000000; rz_list_append(ret, ptr); } return ret; } static RzBinInfo *info(RzBinFile *bf) { ut8 rom_info[16]; RzBinInfo *ret = RZ_NEW0(RzBinInfo); if (!ret) { return NULL; } if (!bf || !bf->buf) { free(ret); return NULL; } ret->lang = NULL; rz_buf_read_at(bf->buf, 0xa0, rom_info, 16); ret->file = rz_str_ndup((const char *)rom_info, 12); ret->type = rz_str_ndup((char *)&rom_info[12], 4); ret->machine = strdup("GameBoy Advance"); ret->os = strdup("any"); ret->arch = strdup("arm"); ret->has_va = 1; ret->bits = 32; ret->big_endian = 0; ret->dbg_info = 0; return ret; } static RzList *sections(RzBinFile *bf) { RzList *ret = NULL; RzBinSection *s = RZ_NEW0(RzBinSection); if (!s) { return NULL; } ut64 sz = rz_buf_size(bf->buf); if (!(ret = rz_list_newf((RzListFree)rz_bin_section_free))) { free(s); return NULL; } s->name = strdup("ROM"); s->paddr = 0; s->vaddr = 0x8000000; s->size = sz; s->vsize = 0x2000000; s->perm = RZ_PERM_RX; rz_list_append(ret, s); return ret; } RzBinPlugin rz_bin_plugin_ningba = { .name = "ningba", .desc = "Game Boy Advance format rz_bin plugin", .license = "LGPL3", .load_buffer = &load_buffer, .check_buffer = &check_buffer, .entries = &entries, .info = &info, .maps = &rz_bin_maps_of_file_sections, .sections = &sections, }; #ifndef RZ_PLUGIN_INCORE RZ_API RzLibStruct rizin_plugin = { .type = RZ_LIB_TYPE_BIN, .data = &rz_bin_plugin_ningba, .version = RZ_VERSION }; #endif
21.11215
83
0.665339
e7d7e19179e82a2de84be3f9768a5313a4b142b8
285
sql
SQL
kata-files/lesson2/postgresql/expected/MYLARGESCHEMA/table/table302.sql
goldmansachs/obevo-kata
5596ff44ad560d89d183ac0941b727db1a2a7346
[ "Apache-2.0" ]
22
2017-09-28T21:35:04.000Z
2022-02-12T06:24:28.000Z
kata-files/lesson2/postgresql/expected/MYLARGESCHEMA/table/table302.sql
goldmansachs/obevo-kata
5596ff44ad560d89d183ac0941b727db1a2a7346
[ "Apache-2.0" ]
6
2017-07-01T13:52:34.000Z
2018-09-13T15:43:47.000Z
kata-files/lesson2/postgresql/expected/MYLARGESCHEMA/table/table302.sql
goldmansachs/obevo-kata
5596ff44ad560d89d183ac0941b727db1a2a7346
[ "Apache-2.0" ]
11
2017-04-30T18:39:09.000Z
2021-08-22T16:21:11.000Z
//// CHANGE name=change0 CREATE TABLE table302 ( id integer NOT NULL, field1 character varying(30), usertype4field usertype4, usertype2field usertype2 ); GO //// CHANGE name=change1 ALTER TABLE ONLY table302 ADD CONSTRAINT table302_pkey PRIMARY KEY (id); GO
14.25
50
0.712281
91fd090e71396fc359168070f1a036c6b5bc1a37
453
kt
Kotlin
features/image_viewer/src/main/java/es/littledavity/features/image/viewer/ImageViewerRoute.kt
Benderinos/chorboagenda
4f7f9d251c4da8e130a9f2b64879867bfecb44e8
[ "Apache-2.0", "Unlicense" ]
1
2021-06-25T22:30:32.000Z
2021-06-25T22:30:32.000Z
features/image_viewer/src/main/java/es/littledavity/features/image/viewer/ImageViewerRoute.kt
Benderinos/chorboagenda
4f7f9d251c4da8e130a9f2b64879867bfecb44e8
[ "Apache-2.0", "Unlicense" ]
null
null
null
features/image_viewer/src/main/java/es/littledavity/features/image/viewer/ImageViewerRoute.kt
Benderinos/chorboagenda
4f7f9d251c4da8e130a9f2b64879867bfecb44e8
[ "Apache-2.0", "Unlicense" ]
null
null
null
/* * Copyright 2021 dalodev */ package es.littledavity.features.image.viewer import es.littledavity.commons.ui.base.events.Command import es.littledavity.commons.ui.base.events.Route internal sealed class ImageViewerCommand : Command { data class ShareText(val text: String) : ImageViewerCommand() object ResetSystemWindows : ImageViewerCommand() } internal sealed class ImageViewerRoute : Route { object Back : ImageViewerRoute() }
22.65
65
0.774834
3310fadeca0f260ba9d2c8cc23013446b8c2b5d0
1,216
py
Python
tutorials/poplar/tut3_vertices/test/test_tut3.py
xihuaiwen/chinese_bert
631afbc76c40b0ac033be2186e717885246f446c
[ "MIT" ]
null
null
null
tutorials/poplar/tut3_vertices/test/test_tut3.py
xihuaiwen/chinese_bert
631afbc76c40b0ac033be2186e717885246f446c
[ "MIT" ]
null
null
null
tutorials/poplar/tut3_vertices/test/test_tut3.py
xihuaiwen/chinese_bert
631afbc76c40b0ac033be2186e717885246f446c
[ "MIT" ]
null
null
null
# Copyright 2020 Graphcore Ltd. from pathlib import Path import pytest # NOTE: The import below is dependent on 'pytest.ini' in the root of # the repository from examples_tests.test_util import SubProcessChecker working_path = Path(__file__).parent class TestBuildAndRun(SubProcessChecker): def setUp(self): ''' Compile the start here and complete versions of the tutorial code ''' self.run_command("make clean", working_path, []) self.run_command("make all", working_path, []) def tearDown(self): self.run_command("make clean", working_path, []) @pytest.mark.category1 def test_run_start_here(self): ''' Check that the start here version of the tutorial code runs ''' self.run_command("./tut3_start_here", working_path, ["Program complete"]) @pytest.mark.category1 def test_run_complete(self): ''' Check that the complete version of the tutorial code runs ''' self.run_command("../complete/tut3_complete", working_path.parent.joinpath("complete"), ["Program complete", "v2: {7,6,4.5,2.5}"])
32
81
0.626645
04a726f409b88058c841227a12693d539d0539d1
1,179
html
HTML
nodes/realtime/realtime.html
n0bisuke/-node-red-contrib-google-analytics
ab163a3eb9dbfa42f202f893e61e6e5c82b11705
[ "Apache-2.0" ]
1
2021-12-06T23:38:48.000Z
2021-12-06T23:38:48.000Z
nodes/realtime/realtime.html
n0bisuke/-node-red-contrib-google-analytics
ab163a3eb9dbfa42f202f893e61e6e5c82b11705
[ "Apache-2.0" ]
null
null
null
nodes/realtime/realtime.html
n0bisuke/-node-red-contrib-google-analytics
ab163a3eb9dbfa42f202f893e61e6e5c82b11705
[ "Apache-2.0" ]
null
null
null
<script> RED.nodes.registerType('Realtime',{ category: 'Google Analytics', color: '#E47500', defaults: { propertyId: {value:"", required:true}, }, // credentials: { // Credentials:{value:"", type: "password", required:true}, // AccessToken:{value:"", type: "password", required:true} // }, inputs: 1, outputs: 1, icon: "serial.svg", align: "right", label: function() { return this.name||"Realtime"; } }); </script> <script type="text/x-red" data-template-name="Realtime"> <div class="form-row"> <label for="node-input-name"><i class="icon-tag"></i> Name</label> <input type="text" id="node-input-name" placeholder="Name"> </div> <div class="form-row"> <label for="node-input-propertyId"> <i class="icon-tag"></i> Google Analytics propertyId (GA4) </label> <input type="text" id="node-input-propertyId" placeholder="PropertyId"> </div> </script> <script type="text/x-red" data-help-name="Realtime"> <p>Google Analyticsのリアルタイム民</p> </script>
29.475
79
0.544529
b821a93c6dc1f9c42099b60a36e53d7783c42d38
344
dart
Dart
dartmazing/lib/Models/repository_owner_response.dart
HelioMesquita/Dartmazing
a04e37524228a9e89402b2356d0a6b30a394a56d
[ "MIT" ]
2
2021-04-29T21:58:16.000Z
2021-05-10T19:28:39.000Z
dartmazing/lib/Models/repository_owner_response.dart
HelioMesquita/Dartmazing
a04e37524228a9e89402b2356d0a6b30a394a56d
[ "MIT" ]
null
null
null
dartmazing/lib/Models/repository_owner_response.dart
HelioMesquita/Dartmazing
a04e37524228a9e89402b2356d0a6b30a394a56d
[ "MIT" ]
null
null
null
class RepositoryOwnerResponse { String login; String avatarUrl; RepositoryOwnerResponse({ required this.login, required this.avatarUrl, }); factory RepositoryOwnerResponse.fromJson(Map<String, dynamic> json) { return RepositoryOwnerResponse( login: json['login'], avatarUrl: json['avatar_url'], ); } }
20.235294
71
0.694767
ddcdb758812b1f1f38e789d86cc52024584eeef6
8,211
php
PHP
src/Builders/Remove/Entity.php
j0hnys/trident
7983c6961d455e02d8dd0df12ae39da7f28d9ba8
[ "MIT" ]
3
2018-12-05T09:45:11.000Z
2021-04-18T04:56:28.000Z
src/Builders/Remove/Entity.php
j0hnys/trident
7983c6961d455e02d8dd0df12ae39da7f28d9ba8
[ "MIT" ]
2
2019-03-06T19:47:58.000Z
2021-02-02T16:26:21.000Z
src/Builders/Remove/Entity.php
j0hnys/trident
7983c6961d455e02d8dd0df12ae39da7f28d9ba8
[ "MIT" ]
2
2019-03-05T08:36:01.000Z
2019-06-13T02:34:50.000Z
<?php namespace j0hnys\Trident\Builders\Remove; use PhpParser\Error; use PhpParser\NodeDumper; use PhpParser\ParserFactory; use PhpParser\{Node, NodeFinder}; use j0hnys\Trident\Base\Storage\Disk; use j0hnys\Trident\Base\Storage\Trident; use j0hnys\Trident\Base\Constants\Trident\FolderStructure; class Entity { private $storage_disk; private $storage_trident; private $mustache; public function __construct(Disk $storage_disk = null, Trident $storage_trident = null) { $this->storage_disk = new Disk(); if (!empty($storage_disk)) { $this->storage_disk = $storage_disk; } $this->storage_trident = new Trident(); if (!empty($storage_trident)) { $this->storage_trident = $storage_trident; } $this->mustache = new \Mustache_Engine; $this->folder_structure = new FolderStructure(); } /** * @param string $name * @return void */ public function run(string $name = ''): void { $this->folder_structure->checkPath('app/Http/Controllers/Trident/*'); $this->folder_structure->checkPath('app/Models/*'); $this->folder_structure->checkPath('app/Policies/Trident/*'); $this->folder_structure->checkPath('app/Trident/Business/Exceptions/*'); $this->folder_structure->checkPath('app/Trident/Business/Logic/*'); $this->folder_structure->checkPath('app/Trident/Interfaces/Business/Logic/*'); $this->folder_structure->checkPath('app/Trident/Interfaces/Workflows/Logic/*'); $this->folder_structure->checkPath('app/Trident/Interfaces/Workflows/Repositories/*'); $this->folder_structure->checkPath('app/Trident/Workflows/Exceptions/*'); $this->folder_structure->checkPath('app/Trident/Workflows/Logic/*'); $this->folder_structure->checkPath('app/Trident/Workflows/Repositories/*'); $this->folder_structure->checkPath('app/Trident/Workflows/Schemas/Logic/*'); $this->folder_structure->checkPath('app/Trident/Workflows/Validations/*'); $this->folder_structure->checkPath('database/factories/Models/*'); $controller_path = $this->storage_disk->getBasePath().'/app/Http/Controllers/Trident/'.($name).'Controller.php'; $model_path = $this->storage_disk->getBasePath().'/app/Models/'.($name).'.php'; $policies_path = $this->storage_disk->getBasePath().'/app/Policies/Trident/'.($name).'Policy.php'; $business_exception_path = $this->storage_disk->getBasePath().'/app/Trident/Business/Exceptions/'.($name).'Exception.php'; $business_logic_path = $this->storage_disk->getBasePath().'/app/Trident/Business/Logic/'.($name).'.php'; $interfaces_business_logic_path = $this->storage_disk->getBasePath().'/app/Trident/Interfaces/Business/Logic/'.($name).'Interface.php'; $interfaces_workflow_logic_path = $this->storage_disk->getBasePath().'/app/Trident/Interfaces/Workflows/Logic/'.($name).'Interface.php'; $interfaces_repositories_path = $this->storage_disk->getBasePath().'/app/Trident/Interfaces/Workflows/Repositories/'.($name).'RepositoryInterface.php'; $workflow_exception_path = $this->storage_disk->getBasePath().'/app/Trident/Workflows/Exceptions/'.($name).'Exception.php'; $workflow_logic_path = $this->storage_disk->getBasePath().'/app/Trident/Workflows/Logic/'.($name).'.php'; $workflow_repository_path = $this->storage_disk->getBasePath().'/app/Trident/Workflows/Repositories/'.($name).'Repository.php'; $this->storage_disk->deleteDirectoryAndFiles($this->storage_disk->getBasePath().'/app/Trident/Workflows/Schemas/Logic/'); $workflow_validations_path = glob($this->storage_disk->getBasePath().'/app/Trident/Workflows/Validations/'.($name).'*.php'); $database_factory_logic_path = $this->storage_disk->getBasePath().'/database/factories/Models/'.($name).'.php'; ($this->storage_disk->isFile($controller_path)) ? $this->storage_disk->deleteFile($controller_path) : null; ($this->storage_disk->isFile($model_path)) ? $this->storage_disk->deleteFile($model_path) : null; ($this->storage_disk->isFile($policies_path)) ? $this->storage_disk->deleteFile($policies_path) : null; ($this->storage_disk->isFile($business_exception_path)) ? $this->storage_disk->deleteFile($business_exception_path) : null; ($this->storage_disk->isFile($business_logic_path)) ? $this->storage_disk->deleteFile($business_logic_path) : null; ($this->storage_disk->isFile($interfaces_business_logic_path)) ? $this->storage_disk->deleteFile($interfaces_business_logic_path) : null; ($this->storage_disk->isFile($interfaces_workflow_logic_path)) ? $this->storage_disk->deleteFile($interfaces_workflow_logic_path) : null; ($this->storage_disk->isFile($interfaces_repositories_path)) ? $this->storage_disk->deleteFile($interfaces_repositories_path) : null; ($this->storage_disk->isFile($workflow_exception_path)) ? $this->storage_disk->deleteFile($workflow_exception_path) : null; ($this->storage_disk->isFile($workflow_logic_path)) ? $this->storage_disk->deleteFile($workflow_logic_path) : null; ($this->storage_disk->isFile($workflow_repository_path)) ? $this->storage_disk->deleteFile($workflow_repository_path) : null; array_map(function($element){ ($this->storage_disk->isFile($element)) ? $this->storage_disk->deleteFile($element) : null; },$workflow_validations_path); ($this->storage_disk->isFile($database_factory_logic_path)) ? $this->storage_disk->deleteFile($database_factory_logic_path) : null; // //update resource routes $Td_entities_workflows = $this->storage_trident->getCurrentControllers(); $workflows = array_map(function ($element) { return [ 'Td_entity' => ucfirst($element), 'td_entity' => lcfirst($element), ]; }, $Td_entities_workflows); $this->folder_structure->checkPath('routes/trident.php'); $trident_resource_routes_path = $this->storage_disk->getBasePath() . '/routes/trident.php'; $stub = $this->storage_disk->readFile(__DIR__ . '/../../Stubs/routes/trident.stub'); $stub = $this->mustache->render($stub, [ 'register_resource_routes' => $workflows, ]); $this->storage_disk->writeFile($trident_resource_routes_path, $stub); // //update trident auth provider $this->folder_structure->checkPath('app/Providers/TridentAuthServiceProvider.php'); $trident_auth_provider_path = $this->storage_disk->getBasePath() . '/app/Providers/TridentAuthServiceProvider.php'; $stub = $this->storage_disk->readFile(__DIR__ . '/../../Stubs/app/Providers/TridentAuthServiceProvider.stub'); $stub = $this->mustache->render($stub, [ 'register_workflow_policies' => $workflows, ]); $this->storage_disk->writeFile($trident_auth_provider_path, $stub); // //update TridentServiceProvider $Td_entities_workflows = $this->storage_trident->getCurrentWorkflows(); $Td_entities_businesses = $this->storage_trident->getCurrentBusinesses(); $workflows = array_map(function($element){ return [ 'Td_entity' => ucfirst($element), ]; },$Td_entities_workflows); $businesses = array_map(function($element){ return [ 'Td_entity' => ucfirst($element), ]; },$Td_entities_businesses); $this->folder_structure->checkPath('app/Providers/TridentServiceProvider.php'); $trident_event_service_provider_path = $this->storage_disk->getBasePath().'/app/Providers/TridentServiceProvider.php'; $stub = $this->storage_disk->readFile(__DIR__.'/../../Stubs/app/Providers/TridentServiceProvider.stub'); $stub = $this->mustache->render($stub, [ 'register_workflows' => $workflows, 'register_business' => $businesses, ]); $this->storage_disk->writeFile($trident_event_service_provider_path, $stub); } }
53.666667
159
0.67373
2659ec8a88677d194b6c45425beab1e557378bbf
2,715
java
Java
src/main/Main.java
HananoshikaYomaru/BeliefEngine
af9a4fcf5fc4705929fdfc0352bbe6ce6e7a4dc8
[ "MIT" ]
null
null
null
src/main/Main.java
HananoshikaYomaru/BeliefEngine
af9a4fcf5fc4705929fdfc0352bbe6ce6e7a4dc8
[ "MIT" ]
null
null
null
src/main/Main.java
HananoshikaYomaru/BeliefEngine
af9a4fcf5fc4705929fdfc0352bbe6ce6e7a4dc8
[ "MIT" ]
null
null
null
package main; import java.util.Scanner; import belief.Belief; import belief.BeliefBase; import expression.CNF; import expression.ExpressionFactory; public class Main { public static void main(String[] args ) { showMenu() ; } private static void showMenu() { // TODO Auto-generated method stub BeliefBase beliefBase = new BeliefBase () ; Scanner scan = new Scanner(System .in ) ; boolean loop = true ; while( loop ) { printMenu() ; try { String choice = scan. nextLine() ; switch (choice ) { case "1" : System.out.println("Feed me belief : ") ; String beliefString = scan.nextLine() ; System.out.println("order (between 1 to 10 ) : ") ; String order = scan.nextLine() ; beliefBase.add(new Belief(beliefString, order.isEmpty() ? 10 : Integer.parseInt(order))) ; break ; case "2" : System.out.println("Feed me belief : ") ; beliefString = scan.nextLine() ; if(beliefBase.entail(ExpressionFactory.createExpression(beliefString))) { System.out.println("logical entailment is true ") ; }else System.out.println("no logical entailment") ; break ; case "3" : System.out.println("Enter belief for contraction: ") ; beliefString = scan.nextLine() ; beliefBase.contract(ExpressionFactory.createExpression(beliefString)) ; break ; case "4" : beliefBase.print(); break ; case "5" : if(beliefBase.getBeliefs().size() == 0 ) { System.out.println("no belief...") ; break ; } ExpressionFactory.createMultiary(CNF.operator, beliefBase.getBeliefExpressionList()).getTruthTable().print() ; break ; case "6" : System.out.println("good bye ") ; return ; case "Test" : printTestExpression() ; break ; default: System.out.println("no such option, try again") ; } }catch(Exception e ) { e.printStackTrace(); } } scan.close() ; } private static void printMenu() { System.out.println("-----Menu----------------------"); System.out.println("1. Feed new belief"); System.out.println("2. check for logical entailment"); System.out.println("3. contraction of belief base"); System.out.println("4. print belief base") ; System.out.println("5. print Truth Table") ; System.out.println("6. Exit"); System.out.println("-------------------------------"); } private static void printTestExpression() { StringBuilder sb = new StringBuilder() ; for(int i = 0 ; i < 20 ; i++ ) { sb.append("A" + i + " && ") ; } sb.append("BB" ) ; System.out.println(sb.toString()) ; } }
28.882979
116
0.594107
049dcc1733c6c042664b7a11858c04ee82bb1891
1,092
java
Java
runtime/src/main/java/io/quarkiverse/githubapp/event/IssueComment.java
jtama/quarkus-github-app
f7d360631f82e18ef000085156335555b13a0a8e
[ "Apache-2.0" ]
312
2021-01-20T05:40:52.000Z
2022-03-31T05:03:19.000Z
runtime/src/main/java/io/quarkiverse/githubapp/event/IssueComment.java
jtama/quarkus-github-app
f7d360631f82e18ef000085156335555b13a0a8e
[ "Apache-2.0" ]
45
2021-02-05T16:07:55.000Z
2022-03-21T20:52:50.000Z
runtime/src/main/java/io/quarkiverse/githubapp/event/IssueComment.java
jtama/quarkus-github-app
f7d360631f82e18ef000085156335555b13a0a8e
[ "Apache-2.0" ]
12
2021-03-26T10:59:16.000Z
2021-12-06T18:10:10.000Z
package io.quarkiverse.githubapp.event; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.ElementType.TYPE; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.inject.Qualifier; import org.kohsuke.github.GHEventPayload; @Event(name = "issue_comment", payload = GHEventPayload.IssueComment.class) @Target({ PARAMETER, TYPE }) @Retention(RUNTIME) @Qualifier public @interface IssueComment { String value() default Actions.ALL; @IssueComment(Created.NAME) @Target(PARAMETER) @Retention(RUNTIME) @Qualifier public @interface Created { String NAME = Actions.CREATED; } @IssueComment(Deleted.NAME) @Target(PARAMETER) @Retention(RUNTIME) @Qualifier public @interface Deleted { String NAME = Actions.DELETED; } @IssueComment(Edited.NAME) @Target(PARAMETER) @Retention(RUNTIME) @Qualifier public @interface Edited { String NAME = Actions.EDITED; } }
22.285714
75
0.722527
c5ccd87af5140796fb1c04e962ce2f30723d97bd
844
cpp
C++
problemes/probleme2xx/probleme271.cpp
ZongoForSpeed/ProjectEuler
2e2d45f984d48a1da8275886c976f909a0de94ce
[ "MIT" ]
6
2015-10-13T17:07:21.000Z
2018-05-08T11:50:22.000Z
problemes/probleme2xx/probleme271.cpp
ZongoForSpeed/ProjectEuler
2e2d45f984d48a1da8275886c976f909a0de94ce
[ "MIT" ]
null
null
null
problemes/probleme2xx/probleme271.cpp
ZongoForSpeed/ProjectEuler
2e2d45f984d48a1da8275886c976f909a0de94ce
[ "MIT" ]
null
null
null
#include "problemes.h" #include "mpz_nombre.h" namespace { mpz_nombre S(size_t n) { mpz_nombre somme = 0; size_t increment = 2 * 3 * 5 * 11 * 17 * 23 * 29 * 41; for (mpz_nombre x = increment + 1; x < n; x += increment) { mpz_nombre x3 = x * x * x; if (x3 % n == 1) somme += x; } return somme; } } ENREGISTRER_PROBLEME(271, "Modular Cubes, part 1") { // For a positive number n, define S(n) as the sum of the integers x, for which 1<x<n and x3≡1 mod n. // // When n=91, there are 8 possible values for x, namely : 9, 16, 22, 29, 53, 74, 79, 81. Thus, // S(91)=9+16+22+29+53+74+79+81=363. // // Find S(13082761331670030). size_t n = 13082761331670030ULL; mpz_nombre resultat = S(n); return std::to_string(resultat); }
28.133333
105
0.550948