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
dd9c9cb670a868688063acefc5dc38275886044d
1,077
go
Go
comment.go
itchyny/go-kintone
b83b0ffcb17a11c72591215be3759a4d0b3475c4
[ "BSD-2-Clause" ]
8
2016-05-01T06:53:25.000Z
2019-07-09T23:51:34.000Z
comment.go
itchyny/go-kintone
b83b0ffcb17a11c72591215be3759a4d0b3475c4
[ "BSD-2-Clause" ]
11
2016-05-12T00:30:46.000Z
2020-02-14T06:18:58.000Z
comment.go
itchyny/go-kintone
b83b0ffcb17a11c72591215be3759a4d0b3475c4
[ "BSD-2-Clause" ]
18
2015-07-31T09:00:43.000Z
2020-06-15T16:34:44.000Z
package kintone import ( "encoding/json" "errors" ) // const ( ConstCommentMentionTypeGroup = "GROUP" ConstCommentMentionTypeDepartment = "ORGANIZATION" ConstCommentMentionTypeUser = "USER" ) // ObjMentions structure type ObjMention struct { Code string `json:"code"` Type string `json:"type"` } // ObjCreator structure type ObjCreator struct { Name string `json:"name"` Code string `json:"code"` } // Comment structure type Comment struct { Id string `json:"id"` Text string `json:"text"` CreatedAt string `json:"createdAt"` Creator *ObjCreator `json:"creator"` Mentions []*ObjMention `json:"mentions"` } // DecodeRecordComments decodes JSON response for comment api func DecodeRecordComments(b []byte) ([]Comment, error) { var comments struct { MyComments []Comment `json:"comments"` Older bool `json:"older"` Newer bool `json:"newer"` } err := json.Unmarshal(b, &comments) if err != nil { return nil, errors.New("Invalid JSON format") } return comments.MyComments, nil }
21.979592
61
0.672238
502c0aad13ef2fe5f62da67fe6ccdec547ae174b
3,192
go
Go
go/src/fblib/edge.go
dominichamon/force-bundles
3bc542ef7d471a3541f58e9458473d5b0e3839fd
[ "Apache-2.0" ]
null
null
null
go/src/fblib/edge.go
dominichamon/force-bundles
3bc542ef7d471a3541f58e9458473d5b0e3839fd
[ "Apache-2.0" ]
null
null
null
go/src/fblib/edge.go
dominichamon/force-bundles
3bc542ef7d471a3541f58e9458473d5b0e3839fd
[ "Apache-2.0" ]
1
2020-11-15T20:12:29.000Z
2020-11-15T20:12:29.000Z
package fblib import ( "fmt" "math" ) const ( K = 0.01 ) type Edge struct { forces []Vector velocities []Vector vertices []Point } func NewEdge(p0, p1 Point) *Edge { return &Edge{forces: []Vector{}, velocities: []Vector{}, vertices: []Point{p0, p1},} } func (e *Edge) compatibility(q Edge) float64 { delta_p := e.vertices[len(e.vertices)-1].Sub(e.vertices[0]) delta_q := q.vertices[len(q.vertices)-1].Sub(q.vertices[0]) len_p := delta_p.Length() len_q := delta_q.Length() // angle Ca := math.Abs(delta_p.Dot(delta_q) / (len_p * len_q)) // scale len_avg := (len_p + len_q) / 2.0 Cs := 2.0 / (len_avg*math.Min(len_p, len_q) + math.Max(len_p, len_q)/len_avg) // position mid_p := e.vertices[len(e.vertices)/2] mid_q := q.vertices[len(q.vertices)/2] Cp := len_avg / (len_avg + mid_p.Sub(mid_q).Length()) // visibility // TODO Cv := 1.0 return Ca * Cs * Cp * Cv } func (e *Edge) Subdivide(segments int) { delta := e.vertices[len(e.vertices)-1].Sub(e.vertices[0]) subdelta := delta.Scale(1.0 / float64(segments)) newVertices := make([]Point, segments+1) newVertices[segments] = e.vertices[len(e.vertices)-1] for i := 0; i < segments; i++ { newVertices[i] = e.vertices[0].Add(subdelta.Scale(float64(i))) } e.vertices = newVertices e.forces = make([]Vector, len(e.vertices)) e.velocities = make([]Vector, len(e.vertices)) if len(e.vertices) != len(e.forces) || len(e.vertices) != len(e.velocities) { fmt.Println("WTF0") } } func (e *Edge) ClearForces() { for i, _ := range e.forces { e.forces[i] = Vector{0, 0} } } func (e *Edge) AddSpringForces() { if len(e.vertices) != len(e.forces) || len(e.vertices) != len(e.velocities) { fmt.Println("WTF1") } for i := 1; i < len(e.vertices)-1; i++ { // spring forces delta0 := e.vertices[i-1].Sub(e.vertices[i]) delta1 := e.vertices[i].Sub(e.vertices[i+1]) // TODO: shouldn't this be the difference from the original length? delta0_len := delta0.Length() delta1_len := delta1.Length() delta0_dir := delta0.Scale(1.0 / delta0_len) delta1_dir := delta1.Scale(1.0 / delta1_len) Fs0 := delta0_dir.Scale(K * delta0_len) Fs1 := delta1_dir.Scale(K * delta1_len) e.forces[i] = e.forces[i].Add(Fs0).Add(Fs1) } } func (e *Edge) AddElectrostaticForces(q Edge) { if len(e.vertices) != len(e.forces) || len(e.vertices) != len(e.velocities) { fmt.Println("WTF2") } compat := e.compatibility(q) for i := 1; i < len(e.vertices)-1; i++ { // electrostatic forces delta_e := e.vertices[i].Sub(q.vertices[i]) delta_e_len := delta_e.Length() delta_e_dir := delta_e.Scale(1.0 / delta_e_len) Fe := delta_e_dir.Scale(1.0 / delta_e_len) e.forces[i] = e.forces[i].Add(Fe.Scale(compat)) } } func (e *Edge) UpdatePositions(dt float64) bool { if len(e.vertices) != len(e.forces) || len(e.vertices) != len(e.velocities) { fmt.Println("WTF3") } moved := false for i, _ := range e.vertices { // assume mass == 1 // Euler integration (blech) e.velocities[i] = e.velocities[i].Add(e.forces[i].Scale(dt)) delta_p := e.velocities[i].Scale(dt) e.vertices[i] = e.vertices[i].Add(delta_p) if delta_p.Length() > EPSILON { moved = true } } return moved }
24.744186
85
0.640664
46d20b2d9b3022661062e990c3d4b3eddafd1b02
527
swift
Swift
UIXMLSamples/UIXMLSamples/RowSpanCell.swift
bsorrentino/UIXML
14bfa54e661c77e55c2ce1a776e945a7c7ec5772
[ "MIT" ]
null
null
null
UIXMLSamples/UIXMLSamples/RowSpanCell.swift
bsorrentino/UIXML
14bfa54e661c77e55c2ce1a776e945a7c7ec5772
[ "MIT" ]
null
null
null
UIXMLSamples/UIXMLSamples/RowSpanCell.swift
bsorrentino/UIXML
14bfa54e661c77e55c2ce1a776e945a7c7ec5772
[ "MIT" ]
null
null
null
// // RowSpanCell.swift // UIXMLSamples // // Created by softphone on 23/11/2017. // Copyright © 2017 soulsoftware. All rights reserved. // import Foundation import UIKit @objc class RowSpanViewController : UIXMLFormViewControllerEx { override func viewDidLoad() { super.viewDidLoad() load(fromFile: "RowSpanForm.plist") tableView.backgroundColor = UIColor.clear } } class RowSpanDataEntryCell : BaseDataEntryCell { @IBOutlet var form:RowSpanViewController?; }
17.566667
63
0.685009
f02b8245c77b51b14671d8a00624f3eea527fbb8
137
js
JavaScript
src/services/api.js
sifthedog/dashboard-reactjs
85bc883877e4acb6259c4ab99c0aadac9cc46b71
[ "MIT" ]
35
2020-05-15T14:37:48.000Z
2021-12-14T06:40:14.000Z
src/services/api.js
sifthedog/dashboard-reactjs
85bc883877e4acb6259c4ab99c0aadac9cc46b71
[ "MIT" ]
4
2021-03-10T22:07:39.000Z
2022-02-27T06:35:55.000Z
src/services/api.js
sifthedog/dashboard-reactjs
85bc883877e4acb6259c4ab99c0aadac9cc46b71
[ "MIT" ]
8
2020-05-15T14:27:55.000Z
2021-12-14T06:40:16.000Z
// import axios from 'axios'; // const api = axios.create({ // baseURL: 'YourAPIHost' // }); const api = null; export default api;
15.222222
29
0.620438
fcd7c91aa132719ce99799ca856e30c6465e5fd0
603
css
CSS
public/css/template.css
GouirahFarid/parc_informatique
007e485612a002530c780e235d66f3b6bc9bbb6a
[ "MIT" ]
null
null
null
public/css/template.css
GouirahFarid/parc_informatique
007e485612a002530c780e235d66f3b6bc9bbb6a
[ "MIT" ]
null
null
null
public/css/template.css
GouirahFarid/parc_informatique
007e485612a002530c780e235d66f3b6bc9bbb6a
[ "MIT" ]
2
2021-05-05T11:34:29.000Z
2021-07-08T17:18:10.000Z
body{ background-color: #617cad; font-family:"Arial Rounded MT Bold"; } .navbar{ background-color: #2e2c62; } .drop:hover{ background-color: #e17410; color:#FFF; } a:hover{ text-decoration: none; } .glyphicon{ margin-right: 3px; } table{ background-color: #FFFFFF; } .glyphicon-remove{ color: #ff0900; } .glyphicon-ok{ color: #3ebc1d; } .text-center,.table-responsive{ margin-top: 15px; margin-bottom: 15px; } th{ background-color: #1b1e21; color:#FFF; } .a{ color: #FFF; } .a:hover{ color: #FFF; }
14.707317
41
0.575456
e78602804eb2be485029323e6b4206ee79b8c5b3
1,606
js
JavaScript
packages/docs/src/pages/card/samples/Card14.js
jeven2016/react-windy-ui
93623d11fec4b282ecaeb3e09c60bf81ecf56c3f
[ "MIT" ]
1
2022-01-22T14:31:30.000Z
2022-01-22T14:31:30.000Z
packages/docs/src/pages/card/samples/Card14.js
jeven2016/react-windy-ui
93623d11fec4b282ecaeb3e09c60bf81ecf56c3f
[ "MIT" ]
2
2021-06-12T05:52:22.000Z
2022-02-26T07:03:01.000Z
packages/docs/src/pages/card/samples/Card14.js
jeven2016/react-windy-ui
93623d11fec4b282ecaeb3e09c60bf81ecf56c3f
[ "MIT" ]
null
null
null
import React, {useState} from 'react'; import {Button, Card, Space, Toggle} from 'react-windy-ui'; import pic from './girl1.jpg'; import {FontAwesomeIcon} from "@fortawesome/react-fontawesome"; import {faPlus} from "@fortawesome/free-solid-svg-icons"; export default function Card14() { const [darkMask, setDarkMask] = useState(true); return <> <div className="doc doc-row"> <Toggle active={darkMask} onChange={val => setDarkMask(val)} label='Dark Mask'/> </div> <div style={{width: '15rem'}}> <Card block> <Card.Curtain darkMask={darkMask} closeContent={ <div className="flex-adjust align-center " style={{height: '100%', padding: '0 1rem'}}> <Space direction="vertical"> <Button color="white" hasOutlineBackground={false} outline invertedOutline hasMinWidth leftIcon={<FontAwesomeIcon icon={faPlus}/>}> Add </Button> <div className="text color-white">This is the description of this picture. </div> </Space> </div> }> <Card.CardImage> <Card.Image src={pic} onClick="return false"> </Card.Image> <Card.OverlayTitle> <h3>A Picture</h3> <h6>The description for this picture</h6> </Card.OverlayTitle> </Card.CardImage> </Card.Curtain> <Card.Row> A Movie Star </Card.Row> </Card> </div> </>; }
32.77551
79
0.534247
4a33f5543c3aada54e72254aa795486fbea199b2
560
js
JavaScript
test/language/types/reference/8.7.2-4-s.js
katemihalikova/test262
aaf4402b4ca9923012e61830fba588bf7ceb6027
[ "BSD-3-Clause" ]
2,602
2015-01-02T10:45:13.000Z
2022-03-30T23:04:17.000Z
test/language/types/reference/8.7.2-4-s.js
katemihalikova/test262
aaf4402b4ca9923012e61830fba588bf7ceb6027
[ "BSD-3-Clause" ]
2,157
2015-01-06T05:01:55.000Z
2022-03-31T17:18:08.000Z
test/language/types/reference/8.7.2-4-s.js
katemihalikova/test262
aaf4402b4ca9923012e61830fba588bf7ceb6027
[ "BSD-3-Clause" ]
527
2015-01-08T16:04:26.000Z
2022-03-24T03:34:47.000Z
// Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es5id: 8.7.2-4-s description: > Strict Mode - TypeError is thrown if LeftHandSide is a reference to an accessor property with no setter flags: [onlyStrict] ---*/ var _8_7_2_4 = {}; var _8_7_2_4_bValue = 1; Object.defineProperty(_8_7_2_4, "b", { get: function () { return _8_7_2_4_bValue; } }); assert.throws(TypeError, function() { _8_7_2_4.b = 11; });
28
70
0.632143
98bcd51fac26fb3b59c94c13cb4ee2a6c0d21718
297
html
HTML
src/app/containers/default-layout/default-footer/default-footer.component.html
Rawandlazez/angularProject
2db145716ec1f5e531ff67b77d1e7c042e8818b9
[ "MIT" ]
null
null
null
src/app/containers/default-layout/default-footer/default-footer.component.html
Rawandlazez/angularProject
2db145716ec1f5e531ff67b77d1e7c042e8818b9
[ "MIT" ]
null
null
null
src/app/containers/default-layout/default-footer/default-footer.component.html
Rawandlazez/angularProject
2db145716ec1f5e531ff67b77d1e7c042e8818b9
[ "MIT" ]
null
null
null
<!--<c-footer>--> <div> <a href="https://coreui.io/pro/angular/" target="_blank"></a> <span> &copy; </span> </div> <div class="ms-auto"> Created by <a href="https://coreui.io/pro/angular" target="_blank"> <span> Rawand lazez</span> </a> </div> <!--</c-footer>-->
22.846154
65
0.535354
69ea31a382e1d75a0a6cded0419c75ece8791dfd
9,755
sql
SQL
u635941118_rent.sql
VincentiusGerardo/RentalBackEnd
2f8b44bba6e6f70e6e1049138e5a9296fc9aae30
[ "MIT" ]
null
null
null
u635941118_rent.sql
VincentiusGerardo/RentalBackEnd
2f8b44bba6e6f70e6e1049138e5a9296fc9aae30
[ "MIT" ]
null
null
null
u635941118_rent.sql
VincentiusGerardo/RentalBackEnd
2f8b44bba6e6f70e6e1049138e5a9296fc9aae30
[ "MIT" ]
1
2019-12-14T15:53:27.000Z
2019-12-14T15:53:27.000Z
-- phpMyAdmin SQL Dump -- version 4.8.5 -- https://www.phpmyadmin.net/ -- -- Host: 10.4.1.142:3306 -- Generation Time: Aug 30, 2019 at 05:31 PM -- Server version: 10.2.24-MariaDB -- PHP Version: 7.2.18 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; 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: `u635941118_rent` -- -- -------------------------------------------------------- -- -- Table structure for table `ms_admin` -- CREATE TABLE `ms_admin` ( `ID_Admin` int(11) NOT NULL, `Nama` varchar(50) DEFAULT NULL, `JK` varchar(10) DEFAULT NULL, `NIK` int(16) DEFAULT NULL, `Alamat` text DEFAULT NULL, `TanggalLahir` date DEFAULT NULL, `Email` text DEFAULT NULL, `Username` varchar(50) DEFAULT NULL, `Password` text DEFAULT NULL, `NomorHP` varchar(12) DEFAULT NULL, `FlagActive` char(1) DEFAULT 'Y' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `ms_admin` -- INSERT INTO `ms_admin` (`ID_Admin`, `Nama`, `JK`, `NIK`, `Alamat`, `TanggalLahir`, `Email`, `Username`, `Password`, `NomorHP`, `FlagActive`) VALUES (1, 'Administrator', NULL, NULL, NULL, NULL, NULL, NULL, '$2y$10$sF.seUKQ8Eu6Wcd/Q7Q/Pu8f9pGtcJc5ahtGb9rq7UQCDKp6XdkVG', NULL, 'Y'); -- -------------------------------------------------------- -- -- Table structure for table `ms_jenismobil` -- CREATE TABLE `ms_jenismobil` ( `ID_JenisMobil` int(11) NOT NULL, `JenisMobil` varchar(50) DEFAULT NULL, `ID_Pengentri` int(11) DEFAULT NULL, `TanggalEntri` datetime DEFAULT NULL, `FlagActive` char(1) DEFAULT 'Y' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `ms_jenismobil` -- INSERT INTO `ms_jenismobil` (`ID_JenisMobil`, `JenisMobil`, `ID_Pengentri`, `TanggalEntri`, `FlagActive`) VALUES (1, 'Mini Bus', 1, '2019-08-20 16:45:22', 'Y'), (2, 'Sedan', 1, '2019-08-20 16:45:29', 'Y'), (3, 'REIWA', 1, '2019-08-29 11:41:36', 'N'), (4, 'ELF', 1, '2019-08-31 00:13:49', 'Y'), (5, 'MPV', 1, '2019-08-31 00:16:48', 'Y'); -- -------------------------------------------------------- -- -- Table structure for table `ms_mobil` -- CREATE TABLE `ms_mobil` ( `ID_Mobil` int(11) NOT NULL, `NamaMobil` varchar(100) DEFAULT NULL, `PlatNomor` varchar(10) DEFAULT NULL, `Harga` int(11) DEFAULT NULL, `Kapasitas` int(11) DEFAULT NULL, `Bagasi` int(11) DEFAULT NULL, `TahunKeluaran` int(4) DEFAULT NULL, `TarifDriver` int(11) DEFAULT NULL, `ID_JenisMobil` int(11) DEFAULT NULL, `Warna` varchar(50) DEFAULT NULL, `PhotoURL` text DEFAULT NULL, `Transmisi` varchar(10) DEFAULT NULL, `BahanBakar` varchar(50) DEFAULT NULL, `StatusPinjam` char(1) DEFAULT 'N', `ID_Pengentri` int(11) DEFAULT NULL, `TanggalEntri` datetime DEFAULT NULL, `LastUpdate` datetime DEFAULT NULL, `FlagActive` char(1) DEFAULT 'Y' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `ms_mobil` -- INSERT INTO `ms_mobil` (`ID_Mobil`, `NamaMobil`, `PlatNomor`, `Harga`, `Kapasitas`, `Bagasi`, `TahunKeluaran`, `TarifDriver`, `ID_JenisMobil`, `Warna`, `PhotoURL`, `Transmisi`, `BahanBakar`, `StatusPinjam`, `ID_Pengentri`, `TanggalEntri`, `LastUpdate`, `FlagActive`) VALUES (1, 'Nissan GT-R Nismo Special Edition', 'B 7777 UMZ', 10000000, 2, 1, 2019, 1000000, 2, 'White', '1_Nissan_GT-R_Nismo_Special_Edition1_30_08_2019_11:21:06_31_08_2019_00:28:20.jpg', 'Automatic', 'Bensin', 'N', 1, '2019-08-20 16:47:29', '2019-08-31 00:28:20', 'Y'), (2, 'MAMA', 'B 360 LU', 400000000, 16, 2, 2015, 2000000, 2, 'HITAM', '2_asfasdfaw123123.jpg', 'Manual', 'Solar', 'N', 1, '2019-08-29 09:58:54', NULL, 'N'), (3, 'asdasda', 'b asdasd', 2147483647, 2, 1, 2051, 20000000, 2, 'sdasda', '3_asdasda.png', 'Manual', 'Solar', 'N', 1, '2019-08-29 10:03:36', NULL, 'N'), (4, 'asfasdfaw123123', 'asdas', 254673453, 2, 1, 2015, 2000000, 1, 'putih', '4_asfasdfaw123123.png', 'Manual', 'Solar', 'N', 1, '2019-08-29 10:05:11', NULL, 'N'), (5, 'ANGELUS EFORD', 'B 360 LU', 254673453, 2, 1, 2015, 2000000, 2, 'putih', '5_asfasdfaw123123.png', 'Automatic', 'Bensin', 'N', 1, '2019-08-29 10:06:02', NULL, 'N'), (6, 'asfasdfaw123123', 'asdas', 254673453, 2, 1, 2015, 20000000, 1, 'putih', '6_asfasdfaw123123.jpg', 'Automatic', 'Solar', 'N', 1, '2019-08-29 11:38:03', NULL, 'N'), (7, 'ISUZU ELF NLR 55 B', 'B 9090 UYE', 400000000, 2, 1, 2015, 2000000, 4, 'ABU-ABU', '7_ELF.jpg', 'Manual', 'Solar', 'N', 1, '2019-08-31 00:15:17', NULL, 'Y'), (8, 'Toyota All New Avanza', 'B 312 AK', 250000, 6, 2, 2017, 100000, 5, 'Silver', '8_Toyota_All_New_Avanza.jpg', 'Manual', 'Bensin', 'N', 1, '2019-08-31 00:18:14', NULL, 'Y'); -- -------------------------------------------------------- -- -- Table structure for table `ms_pelanggan` -- CREATE TABLE `ms_pelanggan` ( `ID_Pelanggan` int(11) NOT NULL, `NamaPelanggan` varchar(50) DEFAULT NULL, `JK` varchar(10) DEFAULT NULL, `NIK` char(16) DEFAULT NULL, `Alamat` text DEFAULT NULL, `TanggalLahir` date DEFAULT NULL, `Email` varchar(255) DEFAULT NULL, `NomorHP` varchar(12) DEFAULT NULL, `FlagActive` char(1) DEFAULT 'Y' ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `ms_pelanggan` -- INSERT INTO `ms_pelanggan` (`ID_Pelanggan`, `NamaPelanggan`, `JK`, `NIK`, `Alamat`, `TanggalLahir`, `Email`, `NomorHP`, `FlagActive`) VALUES (1, 'Vincentius Gerardo', 'Laki-laki', '3171042611960003', 'Jl. Kali Baru Timur GG. IV A/12 RT 009/05', '1996-11-26', 'vincentiusgerardo11@gmail.com', '081293654545', 'Y'), (2, 'Fandi Farhan Anas', 'Laki-laki', '3171042707970001', 'asdasd', '1997-07-27', 'anas.fandi@gmail.com', '081293654545', 'Y'), (3, 'Elia Brian', 'Laki-laki', '12312313213123', 'sadadas', '2019-08-28', 'eliab@gmail.com', '123123123131', 'Y'), (4, 'Vania Anastasya', 'Perempuan', '3171041601980001', 'bekasi', '1998-01-16', 'vaniaanas@gmail.com', '08788589625', 'Y'), (5, 'Yugs', 'Laki-laki', '1414144444', 'Jl. Aja dulu sampe nyaman ', '1997-08-29', 'prayugao@gmail.com', '62625252522', 'Y'); -- -------------------------------------------------------- -- -- Table structure for table `tr_rental` -- CREATE TABLE `tr_rental` ( `ID_Rental` int(11) NOT NULL, `ID_Pelanggan` int(11) DEFAULT NULL, `ID_Mobil` int(11) DEFAULT NULL, `TanggalBooking` date DEFAULT NULL, `WaktuAmbil` datetime DEFAULT NULL, `WaktuKembali` datetime DEFAULT NULL, `Biaya` int(11) DEFAULT NULL, `BuktiPembayaran` text DEFAULT NULL, `StatusPembayaran` char(1) DEFAULT 'N', `ValidasiOleh` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `tr_rental` -- INSERT INTO `tr_rental` (`ID_Rental`, `ID_Pelanggan`, `ID_Mobil`, `TanggalBooking`, `WaktuAmbil`, `WaktuKembali`, `Biaya`, `BuktiPembayaran`, `StatusPembayaran`, `ValidasiOleh`) VALUES (1, 4, 1, '2019-05-07', '2019-05-07 10:00:00', '2019-05-10 12:00:00', 100000000, NULL, 'N', NULL); -- -- Indexes for dumped tables -- -- -- Indexes for table `ms_admin` -- ALTER TABLE `ms_admin` ADD PRIMARY KEY (`ID_Admin`); -- -- Indexes for table `ms_jenismobil` -- ALTER TABLE `ms_jenismobil` ADD PRIMARY KEY (`ID_JenisMobil`), ADD KEY `ms_jenismobil_ibfk_1` (`ID_Pengentri`); -- -- Indexes for table `ms_mobil` -- ALTER TABLE `ms_mobil` ADD PRIMARY KEY (`ID_Mobil`), ADD KEY `ms_mobil_ibfk_1` (`ID_JenisMobil`), ADD KEY `ms_mobil_ibfk_2` (`ID_Pengentri`); -- -- Indexes for table `ms_pelanggan` -- ALTER TABLE `ms_pelanggan` ADD PRIMARY KEY (`ID_Pelanggan`), ADD UNIQUE KEY `Email` (`Email`); -- -- Indexes for table `tr_rental` -- ALTER TABLE `tr_rental` ADD PRIMARY KEY (`ID_Rental`), ADD KEY `tr_rental_ibfk_1` (`ID_Pelanggan`), ADD KEY `tr_rental_ibfk_2` (`ID_Mobil`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `ms_admin` -- ALTER TABLE `ms_admin` MODIFY `ID_Admin` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `ms_jenismobil` -- ALTER TABLE `ms_jenismobil` MODIFY `ID_JenisMobil` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `ms_mobil` -- ALTER TABLE `ms_mobil` MODIFY `ID_Mobil` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT for table `ms_pelanggan` -- ALTER TABLE `ms_pelanggan` MODIFY `ID_Pelanggan` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `tr_rental` -- ALTER TABLE `tr_rental` MODIFY `ID_Rental` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- Constraints for dumped tables -- -- -- Constraints for table `ms_jenismobil` -- ALTER TABLE `ms_jenismobil` ADD CONSTRAINT `ms_jenismobil_ibfk_1` FOREIGN KEY (`ID_Pengentri`) REFERENCES `ms_admin` (`ID_Admin`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `ms_mobil` -- ALTER TABLE `ms_mobil` ADD CONSTRAINT `ms_mobil_ibfk_1` FOREIGN KEY (`ID_JenisMobil`) REFERENCES `ms_jenismobil` (`ID_JenisMobil`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `ms_mobil_ibfk_2` FOREIGN KEY (`ID_Pengentri`) REFERENCES `ms_admin` (`ID_Admin`) ON DELETE CASCADE ON UPDATE CASCADE; -- -- Constraints for table `tr_rental` -- ALTER TABLE `tr_rental` ADD CONSTRAINT `tr_rental_ibfk_1` FOREIGN KEY (`ID_Pelanggan`) REFERENCES `ms_pelanggan` (`ID_Pelanggan`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `tr_rental_ibfk_2` FOREIGN KEY (`ID_Mobil`) REFERENCES `ms_mobil` (`ID_Mobil`) ON DELETE CASCADE ON UPDATE CASCADE; 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 */;
35.472727
273
0.67104
b9bb414dad9610d1fb5a3291c8eff43f1538e8e9
2,241
kt
Kotlin
pleo-antaeus-core/src/test/kotlin/io/pleo/antaeus/context/billing/service/BillingSagaServiceTest.kt
dmorenoh/new-anteaus
5b693a0967a0074675da829710de9ead041a286c
[ "CC0-1.0" ]
null
null
null
pleo-antaeus-core/src/test/kotlin/io/pleo/antaeus/context/billing/service/BillingSagaServiceTest.kt
dmorenoh/new-anteaus
5b693a0967a0074675da829710de9ead041a286c
[ "CC0-1.0" ]
null
null
null
pleo-antaeus-core/src/test/kotlin/io/pleo/antaeus/context/billing/service/BillingSagaServiceTest.kt
dmorenoh/new-anteaus
5b693a0967a0074675da829710de9ead041a286c
[ "CC0-1.0" ]
null
null
null
package io.pleo.antaeus.context.billing.service import io.mockk.every import io.mockk.mockk import io.mockk.slot import io.mockk.verify import io.pleo.antaeus.context.billing.command.CompleteBillingBatchProcessCommand import io.pleo.antaeus.context.billing.event.BillingBatchProcessStartedEvent import io.pleo.antaeus.context.invoice.service.InvoiceService import io.pleo.antaeus.context.payment.RequestInvoicePaymentCommand import io.pleo.antaeus.core.messagebus.CommandBus import io.pleo.antaeus.models.Currency import io.pleo.antaeus.models.Invoice import io.pleo.antaeus.models.InvoiceStatus import io.pleo.antaeus.models.Money import org.junit.jupiter.api.Test import java.math.BigDecimal class BillingSagaServiceTest { companion object { const val PROCESS_ID = 12314 val TEN_EURO = Money(BigDecimal.TEN, Currency.EUR) } private val invoiceService = mockk<InvoiceService>() private val commandBus = mockk<CommandBus>(relaxed = true) private val billingSagaService = BillingSagaService(invoiceService, commandBus) @Test fun `should complete billing bath process when no pending invoices found`() { //given every { invoiceService.fetchAllPending() } returns emptyList() //when billingSagaService.handle(BillingBatchProcessStartedEvent(PROCESS_ID)) //then verify { commandBus.send(CompleteBillingBatchProcessCommand(PROCESS_ID)) } verify(exactly = 0) { commandBus.send(ofType(RequestInvoicePaymentCommand::class)) } } @Test fun `should request invoice payment for evert pending invoice`() { //given val invoice1 = Invoice(1, 2, TEN_EURO, InvoiceStatus.PENDING) val invoice2 = Invoice(2, 3, TEN_EURO, InvoiceStatus.PENDING) every { invoiceService.fetchAllPending() } returns listOf(invoice1, invoice2) //when billingSagaService.handle(BillingBatchProcessStartedEvent(PROCESS_ID)) //then val slot = slot<RequestInvoicePaymentCommand>() verify(exactly = 0) { commandBus.send(ofType(CompleteBillingBatchProcessCommand::class)) } verify(exactly = 2) { commandBus.send(ofType(RequestInvoicePaymentCommand::class)) } } }
37.35
98
0.740295
6bacd2b12cd4a63a35ed097e0da3b7977ba4037b
2,119
h
C
LoggingSupport.framework/OSLogTermDumper.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
4
2021-10-06T12:15:26.000Z
2022-02-21T02:26:00.000Z
LoggingSupport.framework/OSLogTermDumper.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
null
null
null
LoggingSupport.framework/OSLogTermDumper.h
reels-research/iOS-Private-Frameworks
9a4f4534939310a51fdbf5a439dd22487efb0f01
[ "MIT" ]
1
2021-10-08T07:40:53.000Z
2021-10-08T07:40:53.000Z
/* Generated by RuntimeBrowser Image: /System/Library/PrivateFrameworks/LoggingSupport.framework/LoggingSupport */ @interface OSLogTermDumper : NSObject { unsigned char _colorMode; unsigned short _cur_attrs; bool _fancy; int _fd; unsigned short _last_attrs; struct os_trace_blob_s { union { char *ob_b; void *ob_v; char *ob_s; char *ob_c; } ; unsigned int ob_len; unsigned int ob_size; unsigned int ob_maxsize; unsigned short ob_flags; bool ob_binary; } _ob; unsigned char _ob_slop; bool _vis; } @property (nonatomic) unsigned char bgColor; @property (getter=isBold, nonatomic) bool bold; @property (nonatomic, readonly) unsigned char colorMode; @property (nonatomic) unsigned char fgColor; @property (nonatomic, readonly) bool isFancy; @property (getter=isOblique, nonatomic) bool oblique; @property (nonatomic) unsigned short style; @property (getter=isUnderlined, nonatomic) bool underline; - (void)_flushAttrs; - (void)_resetAttrsForNewline; - (void)beginEditing; - (unsigned char)bgColor; - (void)close; - (unsigned char)colorMode; - (void)dealloc; - (void)endEditing; - (unsigned char)fgColor; - (void)flush:(bool)arg1; - (unsigned int)format:(const char *)arg1; - (void)hexdump:(const void*)arg1 length:(unsigned long long)arg2; - (id)init; - (id)initWithFd:(int)arg1 colorMode:(unsigned char)arg2; - (bool)isBold; - (bool)isFancy; - (bool)isOblique; - (bool)isUnderlined; - (void)pad:(int)arg1 count:(unsigned long long)arg2; - (void)putUUID:(unsigned char)arg1; - (void)putc:(int)arg1; - (void)puts:(const char *)arg1; - (void)resetStyle; - (void)setBgColor:(unsigned char)arg1; - (void)setBold:(bool)arg1; - (void)setFgColor:(unsigned char)arg1; - (void)setOblique:(bool)arg1; - (void)setStyle:(unsigned short)arg1; - (void)setUnderline:(bool)arg1; - (void)startPager; - (unsigned short)style; - (unsigned int)vformat:(const char *)arg1 args:(char *)arg2; - (void)write:(const void*)arg1 size:(unsigned long long)arg2; - (void)writeln; @end
29.027397
83
0.689476
041be5062dc1b3c6681eedc987b3066621e616be
1,651
js
JavaScript
config/butler.defaults.js
palantirnet/butler
c156fe1b28df6c129cd77d4b4e0ea806c9e1d222
[ "MIT" ]
13
2016-10-26T09:34:48.000Z
2019-01-10T18:10:18.000Z
config/butler.defaults.js
palantirnet/butler
c156fe1b28df6c129cd77d4b4e0ea806c9e1d222
[ "MIT" ]
75
2015-09-16T20:11:46.000Z
2022-03-22T13:22:33.000Z
config/butler.defaults.js
palantirnet/butler
c156fe1b28df6c129cd77d4b4e0ea806c9e1d222
[ "MIT" ]
2
2015-11-05T20:11:31.000Z
2016-03-02T15:11:09.000Z
// Define Butler default configuration var defaults = {}; // What we run by default. defaults.develop_tasks = ['sass', 'sculpin', 'watch']; // .scss files defaults.scss = ['../../styleguide/source/code/sass/*.scss', '../../styleguide/source/code/sass/**/*.scss']; // location of the compiled CSS defaults.css = '../../styleguide/source/code/css/'; // location of the sculpin project root defaults.sculpin_dir = '../../styleguide/'; // location of the template files defaults.template_files = ['../../styleguide/source/*.html', '../../styleguide/source/**/*.html']; // location of the compiled output defaults.output_dev = '../../styleguide/output_dev'; // location of the compiled html files defaults.html_files = ['../../styleguide/output_dev/*.html', '../../styleguide/output_dev/**/*.html']; // production files to be deployed defaults.output_prod = '../../styleguide/output_prod/**/*'; // location of spress files defaults.spress_output = '../../styleguide/build/**/*'; // location of sculpin.phar defaults.sculpin_run = '../../vendor/bin/sculpin'; defaults.spress_home = '../../'; defaults.spress_bin = '../../vendor/bin/spress'; // Autoprefixer defaults // Support 2 most recent browser versions and anything with more than 5% support defaults.autoprefixer = { browsers: ['last 2 versions', '> 5%'] }; // Stylelint defaults // point to the configuration file defaults.stylelint = { configFile: 'config/linters/stylelint.config.json' }; // Deploy defaults // point to the correct repo & include deploy message defaults.deploy = { remoteUrl: defaults.repo, message: 'Updated with Butler - [timestamp]' }; module.exports = defaults;
33.693878
108
0.69473
bccb951d1c37a80587443a3084ebf508f258e96a
3,705
js
JavaScript
assets/modules/login/js/login.js
zealinfovision/fastpmcf
c814edb8d806cf88efc3b928a2b2c9b96133861f
[ "MIT" ]
null
null
null
assets/modules/login/js/login.js
zealinfovision/fastpmcf
c814edb8d806cf88efc3b928a2b2c9b96133861f
[ "MIT" ]
null
null
null
assets/modules/login/js/login.js
zealinfovision/fastpmcf
c814edb8d806cf88efc3b928a2b2c9b96133861f
[ "MIT" ]
null
null
null
$(document).ready(function() { $("#login_user_vendor_form").validate({ rules: { password: { required: true, maxlength: 20 }, email: { required: true, email: true, maxlength: 50 }, }, errorElement: "em", errorPlacement: function ( error, element ) { error.addClass( "help-block" ); error.insertAfter( element ); }, highlight: function ( element, errorClass, validClass ) { $( element ).parents( ".form-group" ).addClass( "has-danger" ).removeClass( "has-success" ); }, unhighlight: function (element, errorClass, validClass) { $( element ).parents( ".form-group" ).addClass( "has-success" ).removeClass( "has-danger" ); }, focusInvalid: false, invalidHandler: function(form, validator) { if (!validator.numberOfInvalids()) return; }, success: function() { return false; }, submitHandler: function(form) { var currentUrlReturn = window.location.href; var currentUrlPath = window.location.pathname, expr = /venue-details/; var checkout_vendor = /vendor-detail/; var formData = $(form).serialize()+'&csrf_test_name='+$.cookie('csrf_cookie_name'); $.ajax({ type: 'post', url: base_url+"login-user", data: formData, dataType: 'json', beforeSend: function() { $(".submit-login-vendor-user").html('Sign In <i class="fa fa-spinner fa-spin"></i>').attr('disabled', 'disabled'); $(".error-message").html(''); }, success: function(res) { if (res.status == 1) { $('#login_logout').modal('hide'); if (expr.test(currentUrlPath)) { $('#bookVenueForm').find('input[name="csrf_test_name"]').val($.cookie('csrf_cookie_name')); var frm = $("#bookVenueForm").serialize(); if (frm.indexOf('=&') > -1 || frm.substr(frm.length - 1) == '=') { $("#bookVenueForm").submit(); } else { $(".event-content-tab-item").attr('data-id',1); $("#bookVenueForm").attr('action', base_url+'checkout'); $("#bookVenueForm").submit(); } }else if (checkout_vendor.test(currentUrlPath)) { $("#bookVenueForm").attr('action', base_url+'connect'); $("#bookVenueForm").submit(); } else { window.location.href = base_url; } } else if(res.status==6){ window.location.href = base_url+"add-venue"; }else if(res.status==7){ window.location.href = base_url+"add-vendor"; } else { $('.alert-error-message').html('<div class="alert alert-danger alert-dismissible"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>' + res.msg + '</div>'); $(".submit-login-vendor-user").html('Sign In ').removeAttr('disabled'); } } }); } }); });
45.182927
207
0.438327
b14e202ca9ab08cb5c8a9f745c9eb5c1e20233b8
324
css
CSS
web/css/custom.css
TheSuperSagor/shufflehex_admin
3b4afecb6fac65f3304a997787aea318cb0664b4
[ "BSD-3-Clause" ]
null
null
null
web/css/custom.css
TheSuperSagor/shufflehex_admin
3b4afecb6fac65f3304a997787aea318cb0664b4
[ "BSD-3-Clause" ]
null
null
null
web/css/custom.css
TheSuperSagor/shufflehex_admin
3b4afecb6fac65f3304a997787aea318cb0664b4
[ "BSD-3-Clause" ]
null
null
null
.main-logo{ width: 180px !important; height: 30px !important; margin-top: 8px; border-right:0 !important; } body { font-family: 'Poppins', sans-serif !important; } .breadcumbs ul { background-color: #4c5f6b; } .breadcumbs li{ color: white !important; } .breadcumbs a { color: #fe4930; }
14.086957
50
0.62963
9c01205d252ee1a4634218eb8952a31f3a7fab86
3,906
js
JavaScript
test/utils.spec.js
lake-effect/react-decoration
a7322bd66eaaffb6376e76cf3e864486904c8fed
[ "MIT" ]
679
2016-09-28T18:15:21.000Z
2022-02-06T21:21:11.000Z
test/utils.spec.js
lake-effect/react-decoration
a7322bd66eaaffb6376e76cf3e864486904c8fed
[ "MIT" ]
13
2016-10-22T02:45:35.000Z
2020-03-27T12:44:43.000Z
test/utils.spec.js
lake-effect/react-decoration
a7322bd66eaaffb6376e76cf3e864486904c8fed
[ "MIT" ]
34
2016-09-27T21:06:32.000Z
2021-07-17T02:44:54.000Z
import expect from 'expect'; import React from 'react'; import ReactTestUtils from 'react-dom/test-utils'; import { validateClass, validateFunction, validateClassAndFunction, } from '../src/utils/validators'; import getEventPreprocessor from '../src/utils/getEventPreprocessor'; import wrapLifecycleMethod from '../src/utils/wrapLifecycleMethod'; describe('utils', () => { it('should get a decorator for given events', () => { expect(getEventPreprocessor).toThrow('Invalid method list'); const prevent = getEventPreprocessor('prevent', 'preventDefault'); expect(prevent(() => false)).toExist(); const unknownEventPrepocessor = getEventPreprocessor('unknown', 'foo'); expect(unknownEventPrepocessor(() => false)).toExist(); const invalidEventFunc = getEventPreprocessor('invalidEventFunc', 'foo', undefined, null); // eslint-disable-next-line class Input extends React.Component { @invalidEventFunc onChange() { // do nothing } render() { return ( <input onChange={this.onChange} /> ); } } const rendered = ReactTestUtils.renderIntoDocument(<Input />); const input = ReactTestUtils.findRenderedDOMComponentWithTag(rendered, 'input'); expect(() => ReactTestUtils.Simulate.change(input)).toNotThrow(); }); it('should validate class', () => { expect(() => validateClass(class Foo { })).toNotThrow(); expect(() => validateClass(43)).toThrow(); expect(() => validateClass(undefined)).toThrow(); expect( () => validateClass(43, 'foo') ).toThrow('@foo decorator can only be applied to class not: number'); }); it('should validate function', () => { expect(() => validateFunction(() => 43)).toNotThrow(); expect(() => validateFunction(43)).toThrow(); expect(() => validateFunction(undefined)).toThrow(); expect( () => validateFunction(43, 'foo') ).toThrow('@foo decorator can only be applied to methods not: number'); }); it('should validate class and function', () => { expect(() => validateClassAndFunction(() => 43)).toNotThrow(); expect(() => validateClassAndFunction(class Foo { })).toNotThrow(); expect(() => validateClassAndFunction(43)).toThrow(); expect(() => validateClassAndFunction(undefined)).toThrow(); expect( () => validateClassAndFunction(43, 'foo') ).toThrow('@foo decorator can only be applied to class and methods not: number'); }); it('should wrap a lifecycle method', (done) => { @wrapLifecycleMethod('componentDidUpdate', function componentDidUpdateWrapper(prevProps, prevState) { expect(prevProps).toEqual({}); expect(prevState).toEqual({}); expect(this.foo).toEqual('bar'); return 'foo'; } ) // eslint-disable-next-line class DivWithoutUserMethod extends React.Component { constructor(...params) { super(...params); expect(this.componentDidUpdate({}, {})).toEqual('foo'); } foo = 'bar' render() { return ( <div /> ); } } @wrapLifecycleMethod('componentDidUpdate', (prevProps, prevState, res) => { expect(prevProps).toEqual({}); expect(prevState).toEqual({}); expect(res).toEqual(true); return 'foo'; }) // eslint-disable-next-line class DivWithUserMethod extends React.Component { constructor(...params) { super(...params); expect(this.componentDidUpdate({}, {})).toEqual('foo'); done(); } componentDidUpdate() { expect(this.foo).toEqual('bar'); return true; } foo = 'bar'; render() { return ( <div /> ); } } ReactTestUtils.renderIntoDocument(<DivWithoutUserMethod />); ReactTestUtils.renderIntoDocument(<DivWithUserMethod />); }); });
30.515625
94
0.616743
3d052dd80b40866b1a5f2797e995992515d13b8d
2,149
go
Go
pkg/cli/v0/loadbalancer/backends.go
MagnusS/infrakit
350060829e83c2ff3f10f2ce9af3167590e9b59e
[ "Apache-2.0" ]
1
2021-07-01T05:28:49.000Z
2021-07-01T05:28:49.000Z
pkg/cli/v0/loadbalancer/backends.go
MagnusS/infrakit
350060829e83c2ff3f10f2ce9af3167590e9b59e
[ "Apache-2.0" ]
null
null
null
pkg/cli/v0/loadbalancer/backends.go
MagnusS/infrakit
350060829e83c2ff3f10f2ce9af3167590e9b59e
[ "Apache-2.0" ]
null
null
null
package loadbalancer import ( "fmt" "io" "os" "github.com/docker/infrakit/pkg/cli" "github.com/docker/infrakit/pkg/spi/instance" "github.com/spf13/cobra" ) // Backends returns the describe command func Backends(name string, services *cli.Services) *cobra.Command { backends := &cobra.Command{ Use: "backends", Short: "Loadbalancer backends", } ls := &cobra.Command{ Use: "ls", Short: "List loadbalancer backends", } register := &cobra.Command{ Use: "add <instance.ID> ...", Short: "Register backends []instance.ID", RunE: func(cmd *cobra.Command, args []string) error { if len(args) != 1 { cmd.Usage() os.Exit(1) } l4, err := services.Scope.L4(name) if err != nil { return nil } cli.MustNotNil(l4, "L4 not found", "name", name) ids := []instance.ID{} for _, a := range args { ids = append(ids, instance.ID(a)) } res, err := l4.RegisterBackends(ids) fmt.Println(res) return err }, } deregister := &cobra.Command{ Use: "rm <instance.ID> ...", Short: "Deregister backends []instance.ID", RunE: func(cmd *cobra.Command, args []string) error { if len(args) != 1 { cmd.Usage() os.Exit(1) } l4, err := services.Scope.L4(name) if err != nil { return nil } cli.MustNotNil(l4, "L4 not found", "name", name) ids := []instance.ID{} for _, a := range args { ids = append(ids, instance.ID(a)) } res, err := l4.DeregisterBackends(ids) fmt.Println(res) return err }, } backends.AddCommand(ls, register, deregister) ls.Flags().AddFlagSet(services.OutputFlags) ls.RunE = func(cmd *cobra.Command, args []string) error { if len(args) != 0 { cmd.Usage() os.Exit(1) } l4, err := services.Scope.L4(name) if err != nil { return nil } cli.MustNotNil(l4, "L4 not found", "name", name) list, err := l4.Backends() if err != nil { return err } return services.Output(os.Stdout, list, func(w io.Writer, v interface{}) error { fmt.Printf("%-20v\n", "INSTANCE ID") for _, r := range list { fmt.Printf("%-20v\n", r) } return nil }) } return backends }
20.084112
67
0.604467
daafe6c9914e40a08742468ef3abfffe4a473ca3
10,067
sql
SQL
sistema_de_votacion.sql
StivenEnriquez/Votacion
ca516b1e5c5d190776d7b83df4e1c71f3df68c81
[ "MIT" ]
null
null
null
sistema_de_votacion.sql
StivenEnriquez/Votacion
ca516b1e5c5d190776d7b83df4e1c71f3df68c81
[ "MIT" ]
null
null
null
sistema_de_votacion.sql
StivenEnriquez/Votacion
ca516b1e5c5d190776d7b83df4e1c71f3df68c81
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 5.0.4 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 16-02-2021 a las 09:30:57 -- Versión del servidor: 10.4.17-MariaDB -- Versión de PHP: 8.0.0 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 */; -- -- Base de datos: `sistema_de_votacion` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `alumno` -- CREATE TABLE `alumno` ( `id` bigint(20) UNSIGNED NOT NULL, `cedula_alumno` bigint(20) UNSIGNED NOT NULL, `nombre` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `curso` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `cod_candidato` bigint(20) UNSIGNED DEFAULT NULL, `votos` bigint(20) UNSIGNED DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Volcado de datos para la tabla `alumno` -- INSERT INTO `alumno` (`id`, `cedula_alumno`, `nombre`, `curso`, `cod_candidato`, `votos`, `created_at`, `updated_at`) VALUES (1, 20200101, 'jair araujo', '11', NULL, NULL, NULL, NULL), (2, 20200102, 'jose benavidez', '11', 1, NULL, NULL, NULL), (3, 1082123564, 'esneda banguera', '11', NULL, NULL, '2021-02-12 18:17:57', '2021-02-12 18:17:57'), (4, 1082123564, 'esneda banguera', '11', NULL, NULL, '2021-02-12 18:18:06', '2021-02-12 18:18:06'), (5, 6576565, 'jhjkhjhlkjhljhj', '3', NULL, NULL, '2021-02-14 01:13:11', '2021-02-14 01:13:11'), (6, 1087188677, 'hector salazar', '10', NULL, NULL, '2021-02-15 08:10:14', '2021-02-15 08:10:14'), (7, 215151049, 'Stiven Enriquez', '11', NULL, NULL, '2021-02-15 17:26:51', '2021-02-15 17:26:51'), (8, 215151049, 'Stiven Enriquez', '11', NULL, NULL, '2021-02-15 17:27:03', '2021-02-15 17:27:03'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `candidato` -- CREATE TABLE `candidato` ( `id` bigint(20) UNSIGNED NOT NULL, `cedula_candidato` bigint(20) UNSIGNED NOT NULL, `nombre` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `cod_candidato` bigint(20) UNSIGNED NOT NULL, `foto` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Volcado de datos para la tabla `candidato` -- INSERT INTO `candidato` (`id`, `cedula_candidato`, `nombre`, `cod_candidato`, `foto`, `created_at`, `updated_at`) VALUES (21, 1087188689, 'cleudia elena torres', 1, '1.jpg', NULL, NULL), (22, 1080123456, 'andres felipes viveros', 2, '2.jpg', NULL, NULL), (23, 1234567890, 'luis bangueragjhghjgjhg', 3, 'IMD98C~1.JPG', '2021-02-12 10:16:27', '2021-02-12 10:16:27'), (24, 123456789, 'leo banguera', 5, '3.jpg', '2021-02-12 18:20:07', '2021-02-12 18:20:07'), (25, 8987655, 'rufino', 4, '1.jpg', '2021-02-14 01:15:01', '2021-02-14 01:15:01'), (26, 12345, 'Pilar Macuase', 1, 'images.jfif', '2021-02-15 08:38:53', '2021-02-15 08:38:53'), (27, 1087201202, 'Cristian Angulo', 6, 'images.jfif', '2021-02-15 17:31:48', '2021-02-15 17:31:48'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `cursos` -- CREATE TABLE `cursos` ( `id` bigint(20) UNSIGNED NOT NULL, `curso` varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Volcado de datos para la tabla `cursos` -- INSERT INTO `cursos` (`id`, `curso`, `created_at`, `updated_at`) VALUES (1, '1', NULL, NULL), (2, '2', NULL, NULL), (3, '3', NULL, NULL), (4, '4', NULL, NULL), (5, '5', NULL, NULL), (6, '6', NULL, NULL), (7, '7', NULL, NULL), (8, '8', NULL, NULL), (9, '9', NULL, NULL), (10, '10', NULL, NULL), (11, '11', NULL, NULL); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `failed_jobs` -- CREATE TABLE `failed_jobs` ( `id` bigint(20) UNSIGNED NOT NULL, `uuid` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `connection` text COLLATE utf8mb4_unicode_ci NOT NULL, `queue` text COLLATE utf8mb4_unicode_ci NOT NULL, `payload` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `exception` longtext COLLATE utf8mb4_unicode_ci NOT NULL, `failed_at` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `migrations` -- CREATE TABLE `migrations` ( `id` int(10) UNSIGNED NOT NULL, `migration` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `batch` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Volcado de datos para la tabla `migrations` -- INSERT INTO `migrations` (`id`, `migration`, `batch`) VALUES (1, '2014_10_12_000000_create_users_table', 1), (2, '2014_10_12_100000_create_password_resets_table', 1), (3, '2019_08_19_000000_create_failed_jobs_table', 1), (4, '2021_02_10_212526_create_cursos_table', 1), (5, '2021_02_10_215959_create_votos_table', 1), (6, '2021_02_10_220819_create_alumno_table', 1), (7, '2021_02_10_221332_create_candidato_table', 1); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `password_resets` -- CREATE TABLE `password_resets` ( `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `token` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `created_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `users` -- CREATE TABLE `users` ( `id` bigint(20) UNSIGNED NOT NULL, `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `fullacces` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `email_verified_at` timestamp NULL DEFAULT NULL, `password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL, `remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Volcado de datos para la tabla `users` -- INSERT INTO `users` (`id`, `name`, `email`, `fullacces`, `email_verified_at`, `password`, `remember_token`, `created_at`, `updated_at`) VALUES (1, 'admin hector', 'flowchino94@gmail.com', '1', NULL, '$2y$10$OF1rgxzYdZAyLpNr8D7PBef6XCLI9mso58rtqdcGHqhIdEOfpk8hm', NULL, '2021-02-12 07:27:33', '2021-02-12 07:27:33'), (2, 'jorge mario', 'helusaba@hotmail.com', '2', NULL, '$2y$10$4hE5S3Bex12ahDB4CfWljOCUZBYyEOR0Vj3ANr8DyvuYb/lcfBpOi', NULL, '2021-02-12 07:27:34', '2021-02-12 07:27:34'), (3, 'jfhdjkagfjkdsgf', 'jelsala@gmail.com', '2', NULL, '$2y$10$gEN18MgLKqLsv0OcAffXpucyCGLZ0aLn/JvnM..d/mJRYon4oRHGO', NULL, '2021-02-14 01:29:43', '2021-02-14 01:29:43'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `votos` -- CREATE TABLE `votos` ( `id` bigint(20) UNSIGNED NOT NULL, `cod_candidato` bigint(20) UNSIGNED DEFAULT NULL, `nombre` varchar(250) COLLATE utf8mb4_unicode_ci DEFAULT NULL, `votos` bigint(20) UNSIGNED DEFAULT NULL, `created_at` timestamp NULL DEFAULT NULL, `updated_at` timestamp NULL DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `alumno` -- ALTER TABLE `alumno` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `candidato` -- ALTER TABLE `candidato` ADD PRIMARY KEY (`id`), ADD KEY `candidato_cod_candidato_foreign` (`cod_candidato`); -- -- Indices de la tabla `cursos` -- ALTER TABLE `cursos` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `failed_jobs` -- ALTER TABLE `failed_jobs` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `failed_jobs_uuid_unique` (`uuid`); -- -- Indices de la tabla `migrations` -- ALTER TABLE `migrations` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `password_resets` -- ALTER TABLE `password_resets` ADD KEY `password_resets_email_index` (`email`); -- -- Indices de la tabla `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `users_email_unique` (`email`); -- -- Indices de la tabla `votos` -- ALTER TABLE `votos` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `alumno` -- ALTER TABLE `alumno` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; -- -- AUTO_INCREMENT de la tabla `candidato` -- ALTER TABLE `candidato` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=28; -- -- AUTO_INCREMENT de la tabla `cursos` -- ALTER TABLE `cursos` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12; -- -- AUTO_INCREMENT de la tabla `failed_jobs` -- ALTER TABLE `failed_jobs` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT de la tabla `migrations` -- ALTER TABLE `migrations` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; -- -- AUTO_INCREMENT de la tabla `users` -- ALTER TABLE `users` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT de la tabla `votos` -- ALTER TABLE `votos` MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT; 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 */;
32.06051
172
0.678554
9edd57faa5df8c4cb4f693a459e2342b93f2e60c
1,816
rs
Rust
src/service/places/request.rs
timeanddate/libtad-rs
c4a3bd4c80780196c17358e7a5b4e39182d857a9
[ "MIT" ]
null
null
null
src/service/places/request.rs
timeanddate/libtad-rs
c4a3bd4c80780196c17358e7a5b4e39182d857a9
[ "MIT" ]
null
null
null
src/service/places/request.rs
timeanddate/libtad-rs
c4a3bd4c80780196c17358e7a5b4e39182d857a9
[ "MIT" ]
null
null
null
use serde::Serialize; #[derive(Default, Serialize)] /// Places API request. /// /// Request is validated when supplied to the client. /// /// Example: /// ``` /// use libtad_rs::{ /// ServiceClient, /// service::places::PlacesRequest, /// }; /// /// let client = ServiceClient::new("access_key".into(), "secret_key".into()); /// let request = PlacesRequest::new() /// .with_placeid("158") /// .set_lang("de") /// .set_geo(false); /// /// let response = client.get_places(&request); /// ``` pub struct PlacesRequest { placeid: Option<Vec<String>>, query: Option<String>, qlimit: Option<u8>, lang: Option<String>, geo: Option<u8>, } impl PlacesRequest { /// Start building a new request. pub fn new() -> Self { Default::default() } /// Set the placeid for the request. pub fn with_placeid(mut self, placeid: impl Into<String>) -> Self { if let Some(ref mut placeids) = self.placeid { placeids.push(placeid.into()); } else { self.placeid.insert(vec![placeid.into()]); } self } /// Set the query for the request. pub fn set_query(mut self, query: impl Into<String>) -> Self { self.query.insert(query.into()); self } /// Set the maximum number of query results to be returned. pub fn set_qlimit(mut self, qlimit: u8) -> Self { self.qlimit.insert(qlimit); self } /// Set the request language for the request. pub fn set_lang(mut self, lang: impl Into<String>) -> Self { self.lang.insert(lang.into()); self } /// Toggle whether to return longitude and latitude for the geo object. pub fn set_geo(mut self, enable: bool) -> Self { self.geo.insert(enable.into()); self } }
23.894737
78
0.585352
68747b783b8e6ee0b7621e5b2d3c554968785da2
59
lua
Lua
package/gluon-ebtables/check_site.lua
RobWei/gluon
15ef885836907b27b2c0481f7ea83d1dd504c5d5
[ "BSD-2-Clause" ]
499
2015-01-07T20:06:02.000Z
2022-03-30T11:56:37.000Z
package/gluon-ebtables/check_site.lua
RobWei/gluon
15ef885836907b27b2c0481f7ea83d1dd504c5d5
[ "BSD-2-Clause" ]
1,849
2015-01-01T04:20:31.000Z
2022-03-31T18:40:27.000Z
package/gluon-ebtables/check_site.lua
RobWei/gluon
15ef885836907b27b2c0481f7ea83d1dd504c5d5
[ "BSD-2-Clause" ]
518
2015-01-04T13:45:27.000Z
2022-03-30T21:52:50.000Z
need_boolean({'mesh', 'filter_membership_reports'}, false)
29.5
58
0.779661
7013b4e6a1fb00a3c474d634a4aea75c55a30781
1,784
go
Go
transpose/transpose.go
charlievieth/utils
57f65151ac366ad3d0d4389a1f56e003ba4d142c
[ "MIT" ]
2
2018-10-24T10:36:28.000Z
2021-07-18T15:51:15.000Z
transpose/transpose.go
charlievieth/utils
57f65151ac366ad3d0d4389a1f56e003ba4d142c
[ "MIT" ]
null
null
null
transpose/transpose.go
charlievieth/utils
57f65151ac366ad3d0d4389a1f56e003ba4d142c
[ "MIT" ]
null
null
null
package main import ( "encoding/csv" "encoding/json" "flag" "fmt" "os" "path/filepath" "runtime" "text/tabwriter" ) var LineCount int var MaxLength int func init() { flag.IntVar(&LineCount, "n", 2, "Number of lines to transpose") flag.IntVar(&MaxLength, "l", -1, "Max line length, -1 means no max length") } func main() { flag.Parse() if flag.NArg() == 0 { Fatal("USAGE: [OPTIONS] FILENAME") } if LineCount <= 0 { Fatal("lines argument '-n' must be greater than 0") } f, err := os.Open(flag.Arg(0)) if err != nil { Fatal(err) } defer f.Close() r := csv.NewReader(f) var lines [][]string for i := 0; i < LineCount; i++ { a, err := r.Read() if err != nil { Fatal(err) } lines = append(lines, a) } w := tabwriter.NewWriter(os.Stdout, 0, 0, 4, ' ', 0) for j := range lines[0] { for i := range lines { // TODO: don't trim the first column line := lines[i][j] if n := MaxLength; n > 0 && len(line) > n { if n > 6 { line = line[:n-len("...")] + "..." } else { line = line[:n] } } if i == 0 { fmt.Fprintf(w, "%s:", line) } else { fmt.Fprintf(w, "\t%s", line) } } fmt.Fprint(w, "\n") } if err := w.Flush(); err != nil { Fatal(err) } } func PrintJSON(v interface{}) { enc := json.NewEncoder(os.Stdout) enc.SetIndent("", " ") if err := enc.Encode(v); err != nil { Fatal(err) } } func Fatal(err interface{}) { if err == nil { return } var s string if _, file, line, ok := runtime.Caller(1); ok && file != "" { s = fmt.Sprintf("Error (%s:%d)", filepath.Base(file), line) } else { s = "Error" } switch err.(type) { case error, string, fmt.Stringer: fmt.Fprintf(os.Stderr, "%s: %s\n", s, err) default: fmt.Fprintf(os.Stderr, "%s: %#v\n", s, err) } os.Exit(1) }
18.778947
76
0.555493
b5788ce60d9c5b12e7ce3e13f669f9c0a9d26edc
908
kt
Kotlin
src/commonMain/kotlin/mqtt/packets/mqttv4/MQTT4Unsuback.kt
LocalCore/KMQTT
8ce2deb9349c7fb83c8d7b3be7706aade55b3056
[ "MIT" ]
40
2020-02-05T21:08:47.000Z
2022-03-31T14:25:46.000Z
src/commonMain/kotlin/mqtt/packets/mqttv4/MQTT4Unsuback.kt
LocalCore/KMQTT
8ce2deb9349c7fb83c8d7b3be7706aade55b3056
[ "MIT" ]
5
2020-11-12T09:47:34.000Z
2022-02-07T15:20:56.000Z
src/commonMain/kotlin/mqtt/packets/mqttv4/MQTT4Unsuback.kt
LocalCore/KMQTT
8ce2deb9349c7fb83c8d7b3be7706aade55b3056
[ "MIT" ]
11
2020-12-03T11:36:13.000Z
2022-03-11T08:25:48.000Z
package mqtt.packets.mqttv4 import mqtt.packets.MQTTControlPacketType import mqtt.packets.MQTTDeserializer import mqtt.packets.mqtt.MQTTUnsuback import socket.streams.ByteArrayInputStream import socket.streams.ByteArrayOutputStream class MQTT4Unsuback( packetIdentifier: UInt ) : MQTTUnsuback(packetIdentifier) { companion object : MQTTDeserializer { override fun fromByteArray(flags: Int, data: UByteArray): MQTT4Unsuback { MQTT4Unsuback.checkFlags(flags) val inStream = ByteArrayInputStream(data) val packetIdentifier = inStream.read2BytesInt() return MQTT4Unsuback(packetIdentifier) } } override fun toByteArray(): UByteArray { val outStream = ByteArrayOutputStream() outStream.write2BytesInt(packetIdentifier) return outStream.wrapWithFixedHeader(MQTTControlPacketType.UNSUBACK, 0) } }
26.705882
81
0.736784
85c4b1a5ddf897d3937a57e46f13a272a3c679f8
3,563
c
C
src/lib/datatypes/sol-arena.c
undeadinu/soletta
5ca6d6a70bead00caf154b445755be94f3f68099
[ "ECL-2.0", "Apache-2.0" ]
266
2015-06-11T00:21:02.000Z
2022-03-27T20:45:17.000Z
src/lib/datatypes/sol-arena.c
undeadinu/soletta
5ca6d6a70bead00caf154b445755be94f3f68099
[ "ECL-2.0", "Apache-2.0" ]
2,224
2015-06-17T17:29:50.000Z
2018-07-20T23:43:40.000Z
src/lib/datatypes/sol-arena.c
undeadinu/soletta
5ca6d6a70bead00caf154b445755be94f3f68099
[ "ECL-2.0", "Apache-2.0" ]
151
2015-06-17T14:42:54.000Z
2022-01-27T17:01:35.000Z
/* * This file is part of the Soletta (TM) Project * * Copyright (C) 2015 Intel Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <errno.h> #include <stdio.h> #include "sol-log.h" #include "sol-arena.h" #include "sol-util-internal.h" /* TODO: check if it's worthwhile to implement this as a single * growing buffer. */ struct sol_arena { struct sol_ptr_vector str_vector; }; SOL_API struct sol_arena * sol_arena_new(void) { struct sol_arena *arena; arena = calloc(1, sizeof(struct sol_arena)); SOL_NULL_CHECK(arena, NULL); sol_ptr_vector_init(&arena->str_vector); return arena; } SOL_API void sol_arena_del(struct sol_arena *arena) { char *s; uint16_t i; SOL_NULL_CHECK(arena); SOL_PTR_VECTOR_FOREACH_IDX (&arena->str_vector, s, i) free(s); sol_ptr_vector_clear(&arena->str_vector); free(arena); } SOL_API int sol_arena_slice_dup_str_n(struct sol_arena *arena, struct sol_str_slice *dst, const char *src, size_t n) { struct sol_str_slice slice; int r; SOL_NULL_CHECK(arena, -EINVAL); SOL_NULL_CHECK(src, -EINVAL); SOL_INT_CHECK(n, <= 0, -EINVAL); slice.data = strndup(src, n); SOL_NULL_CHECK(slice.data, -errno); slice.len = n; r = sol_ptr_vector_append(&arena->str_vector, (char *)slice.data); if (r < 0) { free((char *)slice.data); return r; } *dst = slice; return 0; } SOL_API int sol_arena_slice_dup_str(struct sol_arena *arena, struct sol_str_slice *dst, const char *src) { SOL_NULL_CHECK(src, -EINVAL); return sol_arena_slice_dup_str_n(arena, dst, src, strlen(src)); } SOL_API int sol_arena_slice_dup(struct sol_arena *arena, struct sol_str_slice *dst, struct sol_str_slice src) { return sol_arena_slice_dup_str_n(arena, dst, src.data, src.len); } SOL_API int sol_arena_slice_sprintf(struct sol_arena *arena, struct sol_str_slice *dst, const char *fmt, ...) { va_list ap; char *str; int r; va_start(ap, fmt); r = vasprintf(&str, fmt, ap); va_end(ap); SOL_INT_CHECK(r, < 0, r); dst->data = str; dst->len = r; r = sol_ptr_vector_append(&arena->str_vector, str); if (r < 0) { free(str); return r; } return 0; } SOL_API char * sol_arena_strdup(struct sol_arena *arena, const char *str) { SOL_NULL_CHECK(str, NULL); return sol_arena_str_dup_n(arena, str, strlen(str)); } SOL_API char * sol_arena_str_dup_n(struct sol_arena *arena, const char *str, size_t n) { char *result; int r; SOL_NULL_CHECK(arena, NULL); SOL_NULL_CHECK(str, NULL); SOL_INT_CHECK(n, <= 0, NULL); result = strndup(str, n); SOL_NULL_CHECK(result, NULL); r = sol_ptr_vector_append(&arena->str_vector, result); if (r < 0) { free(result); return NULL; } return result; } SOL_API char * sol_arena_strdup_slice(struct sol_arena *arena, const struct sol_str_slice slice) { return sol_arena_str_dup_n(arena, slice.data, slice.len); }
22.839744
104
0.679764
7bce74ceeaeac0d5f7e963344e31fb1ef0aaae36
7,028
css
CSS
style.css
adalenv/AccountKit-Implemention
c03897efd7b1792d32f87cf32f391cb913043777
[ "Apache-2.0" ]
1
2017-07-26T09:10:05.000Z
2017-07-26T09:10:05.000Z
style.css
adalenv/AccountKit-Implemention
c03897efd7b1792d32f87cf32f391cb913043777
[ "Apache-2.0" ]
null
null
null
style.css
adalenv/AccountKit-Implemention
c03897efd7b1792d32f87cf32f391cb913043777
[ "Apache-2.0" ]
null
null
null
@import url(https://fonts.googleapis.com/css?family=Open+Sans:400,600); * { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } .hide { display: none; } body { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-rendering: optimizeLegibility; background-color: #cfd8dc; font-family: "Open Sans", sans-serif; font-weight: 600; } .wrapper { margin: 50px auto 50px; width: 680px; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; overflow: hidden; background-image: url("https://images.unsplash.com/42/U7Fc1sy5SCUDIu4tlJY3_NY_by_PhilippHenzler_philmotion.de.jpg?ixlib=rb-0.3.5&q=50&fm=jpg&crop=entropy&s=7686972873678f32efaf2cd79671673d"); background-size: cover; background-repeat: none; } .wrapper:after { content: ""; display: table; clear: both; content: ""; background: url(https://images.unsplash.com/42/U7Fc1sy5SCUDIu4tlJY3_NY_by_PhilippHenzler_philmotion.de.jpg?ixlib=rb-0.3.5&q=50&fm=jpg&crop=entropy&s=7686972873678f32efaf2cd79671673d); opacity: 0.5; top: 0; left: 0; bottom: 0; right: 0; position: absolute; z-index: -1; } .wrapper .container { width: 100%; float: left; position: static; clear: both; } header { padding: 42px 49px 0; } header h1 { font-weight: 400; color: #fff; font-size: 24px; letter-spacing: -1px; } section { margin-top: 36px; } section .form, section .change-image { float: left; } section .form { width: 430px; } section .form .input-item { width: 100%; float: left; margin-bottom: 6px; } section .form .input-item .label-part { width: 170px; float: left; padding-left: 50px; height: 48px; line-height: 48px; } section .form .input-item .label-part label, section .form .input-item .label-part span { color: white; font-size: 14px; cursor: default; letter-spacing: -1px; } section .form .input-item .input-part { float: left; display: block; } section .form .input-item .input-part input:not([type='radio']) { width: 260px; height: 48px; -moz-border-radius: 5px; -webkit-border-radius: 5px; border-radius: 5px; border: 0; float: left; padding: 0 15px; background-color:rgba(32, 30, 31, 0.60); font-size: 14px; font-family: "Open Sans", sans-serif; color: #fff; font-weight: 600; } section .form .input-item .input-part input:not([type='radio'])::-webkit-input-placeholder { font-family: "Open Sans", sans-serif; color: #756d70; font-size: 14px; letter-spacing: -1px; } section .form .input-item .input-part input:not([type='radio']):-moz-placeholder { font-family: "Open Sans", sans-serif; color: #756d70; font-size: 14px; letter-spacing: -1px; } section .form .input-item .input-part input:not([type='radio'])::-moz-placeholder { font-family: "Open Sans", sans-serif; color: #756d70; font-size: 14px; letter-spacing: -1px; } section .form .input-item .input-part input:not([type='radio']):-ms-input-placeholder { font-family: "Open Sans", sans-serif; color: #756d70; font-size: 14px; letter-spacing: -1px; } section .form .input-item .input-part input:not([type='radio']):focus { outline: none; border: 1px solid #b7ad88; padding-left: 14px; } section .form .input-item .input-part span { display: block; font-size: 12px; color: #b7ad88; margin-top: 10px; } section .form .input-item.password { margin-bottom: 26px; } section .form .input-item.password input { margin-bottom: 9px; } section .form .input-item.newsletter .label-part { line-height: inherit; } section .form .input-item.newsletter .input-part > div { width: 100%; margin-bottom: 11px; } section .form .input-item.newsletter .input-part > div label { color: #fff; font-size: 13px; display: inline; } section .form .input-item.newsletter .radial-choose { width: 18px; height: 18px; margin: 0; padding: 0; float: left; cursor: pointer; vertical-align: middle; border: none; *display: inline; margin-top: 3px; } section .form .input-item.newsletter .radial-choose:before { background: transparent; border: 1px solid #b7ad88; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; content: ''; float: left; width: 10px; height: 10px; display: inline-block; text-rendering: auto; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } section .form .input-item.newsletter .radial-choose.hover:before, section .form .input-item.newsletter .radial-choose.checked:before { background-color: #b7ad88; } section .change-image { padding: 0 50px; } section .change-image .profile-img-container { width: 150px; height: 150px; text-align: center; position: relative; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; } section .change-image .profile-img-container.active { border: 1px solid #b7ad88; } section .change-image .profile-img-container a { display: block; height: 150px; color: #fff; font-size: 12px; font-weight: 400; width: 150px; line-height: 150px; position: relative; top: 50%; text-decoration: none; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-transform: translate(0, -50%); -ms-transform: translate(0, -50%); -webkit-transform: translate(0, -50%); transform: translate(0, -50%); } section .change-image .profile-img-container a:hover { text-decoration: underline; } section .change-image img.profile { position: absolute; left: 0; top: 0; width: 150px; height: auto; -moz-border-radius: 50%; -webkit-border-radius: 50%; border-radius: 50%; -moz-transition: all 0.3s; -o-transition: all 0.3s; -webkit-transition: all 0.3s; transition: all 0.3s; } section .change-image img.profile.angle-1 { -moz-transform: rotate(90deg); -ms-transform: rotate(90deg); -webkit-transform: rotate(90deg); transform: rotate(90deg); } section .change-image img.profile.angle-2 { -moz-transform: rotate(180deg); -ms-transform: rotate(180deg); -webkit-transform: rotate(180deg); transform: rotate(180deg); } section .change-image img.profile.angle-3 { -moz-transform: rotate(270deg); -ms-transform: rotate(270deg); -webkit-transform: rotate(270deg); transform: rotate(270deg); } section .change-image .edit { width: 100%; text-align: center; margin-top: 28px; } section .change-image .edit img { display: inline-block; } section .change-image .edit .remove { margin-right: 20px; } footer { width: 100%; float: left; border-top: 1px solid #3b3739; background-color: rgba(32, 30, 31, 0.76); padding: 23px 51px; margin-top: 31px; } footer a { display: inline-block; color: #fff; text-transform: uppercase; text-decoration: none; font-size: 12px; } footer a span { color: #b7ad88; } footer a.save { float: right; } footer a.save span { margin-left: 9px; } footer a.cancel { float: left; } footer a.cancel span { margin-right: 9px; } footer a:hover { color: #b7ad88; }
22.892508
193
0.683409
4a2fd17539349f410789a995dcac31298e975063
550
js
JavaScript
output.js
Happyrobot33/CT-AI
61a19c5416763fe0edbf241c588ed8169c233a19
[ "MIT" ]
null
null
null
output.js
Happyrobot33/CT-AI
61a19c5416763fe0edbf241c588ed8169c233a19
[ "MIT" ]
null
null
null
output.js
Happyrobot33/CT-AI
61a19c5416763fe0edbf241c588ed8169c233a19
[ "MIT" ]
null
null
null
const robot = require('robot.js'); // Keyboard & mouse input is done via this module class Output { pauseBuffer() { robot.keyTap('escape'); setTimeout(() => { robot.keyTap('escape'); }, 100); } move(w, a, s, d, space) { robot.keyToggle('w', w ? "down" : "up", "shift"); robot.keyToggle('a', a ? "down" : "up", "shift"); robot.keyToggle('s', s ? "down" : "up", "shift"); robot.keyToggle('d', d ? "down" : "up", "shift"); robot.keyToggle('space', space ? "down" : "up", "shift"); } look(x, y) { robot.moveMouse(x, y); } }
23.913043
84
0.56
c665f22f92e2fed0b2bb4a9c40f8c3fff76b3ea5
217
rb
Ruby
app/controllers/embeddable/external_scripts_controller.rb
sciencelabshs/lara
ee291b238f344c83c8fa8fb5a5bb754e5ff57b9e
[ "MIT" ]
1
2019-08-07T16:24:58.000Z
2019-08-07T16:24:58.000Z
app/controllers/embeddable/external_scripts_controller.rb
sciencelabshs/lara
ee291b238f344c83c8fa8fb5a5bb754e5ff57b9e
[ "MIT" ]
452
2015-01-28T16:11:00.000Z
2022-03-31T23:59:17.000Z
app/controllers/embeddable/external_scripts_controller.rb
sciencelabshs/lara
ee291b238f344c83c8fa8fb5a5bb754e5ff57b9e
[ "MIT" ]
2
2018-10-03T20:46:03.000Z
2020-01-03T09:53:25.000Z
class Embeddable::ExternalScriptsController < Embeddable::EmbeddablesController before_filter :set_embeddable private def set_embeddable @embeddable = Embeddable::ExternalScript.find(params[:id]) end end
24.111111
79
0.801843
93dc6d7bf0017fe1f7cba73d0958ff6bc4b76226
344
swift
Swift
deltatick/Source/Networking/Models/MigrationTokenRequest.swift
jimmya/deltatick
bdc64d87019afc7dc44bb943677918c1d9a9e7c1
[ "MIT" ]
null
null
null
deltatick/Source/Networking/Models/MigrationTokenRequest.swift
jimmya/deltatick
bdc64d87019afc7dc44bb943677918c1d9a9e7c1
[ "MIT" ]
null
null
null
deltatick/Source/Networking/Models/MigrationTokenRequest.swift
jimmya/deltatick
bdc64d87019afc7dc44bb943677918c1d9a9e7c1
[ "MIT" ]
null
null
null
// // MigrationTokenRequest.swift // deltatick // // Created by Jimmy Arts on 22/03/2018. // Copyright © 2018 Jimmy. All rights reserved. // import Foundation struct MigrationTokenRequest: Codable { enum MigrationTokenRequestType: String, Codable { case sync = "SYNC" } let type: MigrationTokenRequestType }
18.105263
53
0.680233
b37551de9dcbf18f1df6b70af5ab43a719a9c668
135
rb
Ruby
spec/factories/users.rb
dukegreene/malontines
4bacedc8bd8a712e5f0c15d90a23d8edc634ce91
[ "CC0-1.0" ]
null
null
null
spec/factories/users.rb
dukegreene/malontines
4bacedc8bd8a712e5f0c15d90a23d8edc634ce91
[ "CC0-1.0" ]
13
2020-05-22T16:56:45.000Z
2022-03-31T00:39:15.000Z
spec/factories/users.rb
dukegreene/malontines
4bacedc8bd8a712e5f0c15d90a23d8edc634ce91
[ "CC0-1.0" ]
null
null
null
FactoryBot.define do factory :user, aliases: [:creator] do username { "g-hops" } password { "anotherSh1pInP0rt?" } end end
19.285714
39
0.659259
5fd417e06f4469e95d1639ce303dae9e10183e14
33,494
c
C
core/vice-3.3/src/lib.c
paulscottrobson/cxp-computer
b43f47d5e8232d3229c6522c9a02d53c1edd3a4d
[ "MIT" ]
1
2020-02-03T16:46:40.000Z
2020-02-03T16:46:40.000Z
third_party/vice-3.3/src/lib.c
xlar54/bmc64
c73f91babaf9e9f75b5073c773bb50e8a8e43505
[ "Apache-2.0" ]
4
2019-06-18T14:45:35.000Z
2019-06-22T17:18:22.000Z
third_party/vice-3.3/src/lib.c
xlar54/bmc64
c73f91babaf9e9f75b5073c773bb50e8a8e43505
[ "Apache-2.0" ]
1
2021-05-14T11:13:44.000Z
2021-05-14T11:13:44.000Z
/* * lib.c - Library functions. * * Written by * Andreas Boose <viceteam@t-online.de> * Marco van den Heuvel <blackystardust68@yahoo.com> * * This file is part of VICE, the Versatile Commodore Emulator. * See README for copyright notice. * * This program 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 2 of the License, or * (at your option) any later version. * * 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA. * */ #include "vice.h" #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "archdep.h" #ifdef AMIGA_SUPPORT #ifndef __USE_INLINE__ #define __USE_INLINE__ #endif #endif #if defined(AMIGA_SUPPORT) || defined(__VBCC__) #include <proto/exec.h> #ifndef AMIGA_SUPPORT #define AMIGA_SUPPORT #endif #endif #include "types.h" #include "debug.h" #define COMPILING_LIB_DOT_C #include "lib.h" #if (defined(sun) || defined(__sun)) && !(defined(__SVR4) || defined(__svr4__)) # ifndef RAND_MAX # define RAND_MAX 32767 # endif #endif #ifdef DEBUG /* enable memory debugging */ # define LIB_DEBUG /* enable pinpointing of memory leaks, don't forget to enable in lib.h */ # define LIB_DEBUG_PINPOINT /* warn on free(NULL) */ /* #define LIB_DEBUG_WARN_FREE_NULL */ # if defined(HAVE_EXECINFO_H) && defined(HAVE_BT_SYMBOLS) # define LIB_DEBUG_CALLER # define DEBUG_BT_MAXDEPTH 16 # include <execinfo.h> # endif #endif #ifdef LIB_DEBUG #define LIB_DEBUG_SIZE 0x10000 #define LIB_DEBUG_GUARD 0x1000 #define LIB_DEBUG_TOPMAX 50 static unsigned int lib_debug_initialized = 0; #ifdef LIB_DEBUG_PINPOINT static const char *lib_debug_filename[LIB_DEBUG_SIZE]; static unsigned int lib_debug_line[LIB_DEBUG_SIZE]; static const char *lib_debug_top_filename[LIB_DEBUG_TOPMAX]; static unsigned int lib_debug_top_line[LIB_DEBUG_TOPMAX]; static const char *lib_debug_pinpoint_filename; static unsigned int lib_debug_pinpoint_line = 0; #endif static void *lib_debug_address[LIB_DEBUG_SIZE]; static unsigned int lib_debug_size[LIB_DEBUG_SIZE]; static unsigned int lib_debug_top_size[LIB_DEBUG_TOPMAX]; static unsigned int lib_debug_current_total = 0; static unsigned int lib_debug_max_total = 0; #ifdef LIB_DEBUG_CALLER static void *lib_debug_bt_caller[LIB_DEBUG_SIZE][DEBUG_BT_MAXDEPTH]; static int lib_debug_bt_numcaller[LIB_DEBUG_SIZE]; #endif #if LIB_DEBUG_GUARD > 0 static char *lib_debug_guard_base[LIB_DEBUG_SIZE]; static unsigned int lib_debug_guard_size[LIB_DEBUG_SIZE]; #endif /*----------------------------------------------------------------------------*/ static void lib_debug_init(void) { memset(lib_debug_address, 0, sizeof(lib_debug_address)); #ifdef LIB_DEBUG_CALLER memset(lib_debug_bt_caller, 0, sizeof(lib_debug_bt_caller)); memset(lib_debug_bt_numcaller, 0, sizeof(lib_debug_bt_numcaller)); #endif #if LIB_DEBUG_GUARD > 0 memset(lib_debug_guard_base, 0, sizeof(lib_debug_guard_base)); #endif #ifdef LIB_DEBUG_PINPOINT memset(lib_debug_line, 0, sizeof(lib_debug_line)); memset(lib_debug_top_size, 0, sizeof(lib_debug_top_size)); #endif lib_debug_initialized = 1; } static void lib_debug_add_top(const char *filename, unsigned int line, unsigned int size) { unsigned int index, i; for (index = 0; index < LIB_DEBUG_TOPMAX; index++) { if (size > lib_debug_top_size[index]) { #if 1 for (i = (LIB_DEBUG_TOPMAX - 1); i > index; i--) { lib_debug_top_size[i] = lib_debug_top_size[i - 1]; lib_debug_top_line[i] = lib_debug_top_line[i - 1]; lib_debug_top_filename[i] = lib_debug_top_filename[i - 1]; } #endif lib_debug_top_size[index] = size; lib_debug_top_line[index] = line; lib_debug_top_filename[index] = filename; break; } } } static void lib_debug_alloc(void *ptr, size_t size, int level) { unsigned int index; if (!lib_debug_initialized) { lib_debug_init(); } index = 0; while (index < LIB_DEBUG_SIZE && lib_debug_address[index] != NULL) { index++; } if (index == LIB_DEBUG_SIZE) { printf("Error: lib_debug_alloc(): Out of debug address slots. (increase LIB_DEBUG_SIZE!)\n"); return; } #ifdef LIB_DEBUG_CALLER lib_debug_bt_numcaller[index] = backtrace(lib_debug_bt_caller[index], DEBUG_BT_MAXDEPTH); #if 0 printf("lib_debug_alloc(): Alloc address %p size %i slot %i from %p.\n", ptr, size, index, func); #endif #endif lib_debug_address[index] = ptr; lib_debug_size[index] = (unsigned int)size; #ifdef LIB_DEBUG_PINPOINT lib_debug_filename[index] = lib_debug_pinpoint_filename; lib_debug_line[index] = lib_debug_pinpoint_line; lib_debug_add_top(lib_debug_pinpoint_filename, lib_debug_pinpoint_line, (unsigned int)size); lib_debug_pinpoint_line = 0; #endif lib_debug_current_total += (unsigned int)size; if (lib_debug_current_total > lib_debug_max_total) { lib_debug_max_total = lib_debug_current_total; } } static void lib_debug_free(void *ptr, unsigned int level, unsigned int fill) { unsigned int index; if (ptr == NULL) { return; } index = 0; while (index < LIB_DEBUG_SIZE && lib_debug_address[index] != ptr) { index++; } if (index == LIB_DEBUG_SIZE) { #if 0 printf("lib_debug_free(): Cannot find debug address!\n"); #endif return; } #if 0 printf("lib_debug_free(): Free address %p size %i slot %i from %p.\n", ptr, lib_debug_size[index], index, func); #endif if (fill) { memset(ptr, 0xdd, lib_debug_size[index]); } lib_debug_address[index] = NULL; lib_debug_current_total -= lib_debug_size[index]; } /*----------------------------------------------------------------------------*/ #if LIB_DEBUG_GUARD > 0 static void lib_debug_guard_add(char *ptr, unsigned int size) { unsigned int index; if (!lib_debug_initialized) { lib_debug_init(); } index = 0; /* find free slot */ while (index < LIB_DEBUG_SIZE && lib_debug_guard_base[index] != NULL) { index++; } if (index == LIB_DEBUG_SIZE) { printf("Error: lib_debug_guard_add(): Out of debug address slots. (increase LIB_DEBUG_SIZE)\n"); return; } #if 0 printf("ADD BASE %p SLOT %d SIZE %d\n", ptr, index, size); #endif lib_debug_guard_base[index] = ptr; lib_debug_guard_size[index] = (unsigned int)size; memset(ptr, 0x55, LIB_DEBUG_GUARD); memset(ptr + LIB_DEBUG_GUARD + size, 0x55, LIB_DEBUG_GUARD); } /* called by lib_debug_libc_free, lib_debug_check (at exit) */ static int lib_debug_guard_remove(char *ptr) { unsigned int index; unsigned int i; index = 0; /* find matching slot */ while (index < LIB_DEBUG_SIZE && lib_debug_guard_base[index] != (ptr - LIB_DEBUG_GUARD)) { index++; } if (index == LIB_DEBUG_SIZE) { #ifdef LIB_DEBUG_PINPOINT printf("%s:%d: ", lib_debug_pinpoint_filename, lib_debug_pinpoint_line); #endif printf("Error: lib_debug_guard_remove(): Cannot find debug address %p! (make sure to use functions from lib.h, do NOT use lib_free on pointers allocated by other functions.)\n", ptr - LIB_DEBUG_GUARD); return 0; } for (i = 0; i < LIB_DEBUG_GUARD; i++) { if (*(ptr - LIB_DEBUG_GUARD + i) != 0x55) { #ifdef LIB_DEBUG_PINPOINT printf("%s:%d: ", lib_debug_pinpoint_filename, lib_debug_pinpoint_line); #endif printf("Error: Memory corruption in lower part of base %p!\n", ptr - LIB_DEBUG_GUARD); break; } } for (i = 0; i < LIB_DEBUG_GUARD; i++) { if (*(ptr + lib_debug_guard_size[index] + i) != 0x55) { #ifdef LIB_DEBUG_PINPOINT printf("%s:%d: ", lib_debug_pinpoint_filename, lib_debug_pinpoint_line); #endif printf("Error: Memory corruption in higher part of base %p!\n", ptr - LIB_DEBUG_GUARD); break; } } #if 0 printf("REM BASE %p SLOT %d\n", ptr - LIB_DEBUG_GUARD, index); #endif lib_debug_guard_base[index] = NULL; return 1; } static unsigned int lib_debug_guard_size_get(char *ptr) { unsigned int index; index = 0; while (index < LIB_DEBUG_SIZE && lib_debug_guard_base[index] != (ptr - LIB_DEBUG_GUARD)) { index++; } if (index == LIB_DEBUG_SIZE) { #ifdef LIB_DEBUG_PINPOINT printf("%s:%d: ", lib_debug_pinpoint_filename, lib_debug_pinpoint_line); #endif printf("Error: lib_debug_guard_size(): Cannot find debug address %p!\n", ptr - LIB_DEBUG_GUARD); return 0; } return lib_debug_guard_size[index]; } #endif /*----------------------------------------------------------------------------*/ static void *lib_debug_libc_malloc(size_t size) { #if LIB_DEBUG_GUARD > 0 char *ptr; ptr = (char *)malloc(size + 2 * LIB_DEBUG_GUARD); lib_debug_guard_add(ptr, (unsigned int)size); return (void *)(ptr + LIB_DEBUG_GUARD); #else return malloc(size); #endif } static void *lib_debug_libc_calloc(size_t nmemb, size_t size) { #if LIB_DEBUG_GUARD > 0 char *ptr; ptr = (char *)malloc(nmemb * size + 2 * LIB_DEBUG_GUARD); lib_debug_guard_add(ptr, (unsigned int)(nmemb * size)); memset(ptr + LIB_DEBUG_GUARD, 0, nmemb * size); return (void *)(ptr + LIB_DEBUG_GUARD); #else return calloc(nmemb, size); #endif } static void lib_debug_libc_free(void *ptr) { #if LIB_DEBUG_GUARD > 0 if (ptr != NULL) { if (lib_debug_guard_remove((char *)ptr)) { free((char *)ptr - LIB_DEBUG_GUARD); } else { free(ptr); } } #ifdef LIB_DEBUG_WARN_FREE_NULL else { #ifdef LIB_DEBUG_PINPOINT printf("%s:%d: ", lib_debug_pinpoint_filename, lib_debug_pinpoint_line); #endif printf("Warning: Pointer passed to lib_debug_libc_free is NULL.\n"); } #endif #else free(ptr); #endif } static void *lib_debug_libc_realloc(void *ptr, size_t size) { #if LIB_DEBUG_GUARD > 0 char *new_ptr = NULL; if (size > 0) { new_ptr = lib_debug_libc_malloc(size); if (ptr != NULL) { size_t old_size; old_size = (size_t)lib_debug_guard_size_get((char *)ptr); if (size >= old_size) { memcpy(new_ptr, ptr, old_size); } else { memcpy(new_ptr, ptr, size); } } } if (ptr != NULL) { lib_debug_libc_free(ptr); } return (void *)new_ptr; #else return realloc(ptr, size); #endif } #endif /*----------------------------------------------------------------------------*/ #ifdef LIB_DEBUG static void printsize(unsigned int size) { if (size > (1024 * 1024)) { printf("%dMiB", size / (1024 * 1024)); } else if (size > (1024)) { printf("%dKiB", size / (1024)); } else { printf("%dB", size); } } #endif #ifdef LIB_DEBUG #ifdef LIB_DEBUG_PINPOINT #define LIB_DEBUG_LEAKLIST_MAX 0x80 unsigned int lib_debug_leaklist_num = 0; const char *lib_debug_leaklist_filename[LIB_DEBUG_LEAKLIST_MAX]; unsigned int lib_debug_leaklist_line[LIB_DEBUG_LEAKLIST_MAX]; unsigned int lib_debug_leaklist_size[LIB_DEBUG_LEAKLIST_MAX]; void *lib_debug_leaklist_address[LIB_DEBUG_LEAKLIST_MAX]; #ifdef LIB_DEBUG_CALLER void *lib_debug_leaklist_bt_caller[LIB_DEBUG_LEAKLIST_MAX][DEBUG_BT_MAXDEPTH]; int lib_debug_leaklist_bt_numcaller[LIB_DEBUG_LEAKLIST_MAX]; #endif static void lib_debug_leaklist_add(unsigned int index) { unsigned int i; #ifdef LIB_DEBUG_CALLER unsigned int j; #endif for (i = 0; i < lib_debug_leaklist_num; i++) { if ((lib_debug_line[index] == lib_debug_leaklist_line[i]) && (!strcmp(lib_debug_filename[index],lib_debug_leaklist_filename[i]))) { lib_debug_leaklist_size[i] += lib_debug_size[index]; return; } } if (i < (LIB_DEBUG_LEAKLIST_MAX - 1)) { lib_debug_leaklist_num++; lib_debug_leaklist_line[i] = lib_debug_line[index]; lib_debug_leaklist_filename[i] = lib_debug_filename[index]; lib_debug_leaklist_size[i] = lib_debug_size[index]; lib_debug_leaklist_address[i] = lib_debug_address[index]; #ifdef LIB_DEBUG_CALLER lib_debug_leaklist_bt_numcaller[i] = lib_debug_bt_numcaller[index]; for (j = 0; j < DEBUG_BT_MAXDEPTH; j++) { lib_debug_leaklist_bt_caller[i][j] = lib_debug_bt_caller[index][j]; } #endif } else { printf("Error: lib_debug_leaklist_add(): Out of slots. (increase LIB_DEBUG_LEAKLIST_MAX!)\n"); } } #endif #endif void lib_debug_check(void) { #ifdef LIB_DEBUG unsigned int index, count; unsigned int leakbytes; #ifdef LIB_DEBUG_CALLER char **btstring; int btidx, spc; #endif count = 0; leakbytes = 0; lib_debug_leaklist_num = 0; for (index = 0; index < LIB_DEBUG_SIZE; index++) { if (lib_debug_address[index] != NULL) { count++; #ifdef LIB_DEBUG_PINPOINT lib_debug_leaklist_add(index); #else printf("Warning: Memory block allocated here was not free'd (Memory leak with size 0x%x at %p).", lib_debug_size[index], lib_debug_address[index]); printf("\n"); #endif leakbytes += lib_debug_size[index]; #if LIB_DEBUG_GUARD > 0 lib_debug_guard_remove((char *)lib_debug_address[index]); #endif } } #ifdef LIB_DEBUG_PINPOINT printf("\n"); for (index = 0; index < lib_debug_leaklist_num; index++) { printf("%s:%d: Warning: Memory block(s) allocated here was not free'd (Memory leak with size 0x%x at %p).", lib_debug_leaklist_filename[index], lib_debug_leaklist_line[index], lib_debug_leaklist_size[index], lib_debug_leaklist_address[index]); #ifdef LIB_DEBUG_CALLER printf("\ncallstack:\n"); btstring = backtrace_symbols(lib_debug_leaklist_bt_caller[index], lib_debug_leaklist_bt_numcaller[index]); if (btstring == NULL) { printf(" lookup failed\n"); } else { for (btidx = 1; btidx < lib_debug_leaklist_bt_numcaller[index]; btidx++) { printf(" "); for (spc = 0; spc < btidx; spc++) { printf(" "); } printf("%s\n", btstring[btidx]); } } free(btstring); #endif printf("\n"); } #endif printf("\nTotal memory leaks: %d", count); #ifdef LIB_DEBUG_PINPOINT printf(" in %d lines", lib_debug_leaklist_num); #endif printf(". Total bytes leaked: 0x%x (", leakbytes); printsize(leakbytes); printf(").\n\nmax. total memory that was allocated: 0x%x bytes. (", lib_debug_max_total); printsize(lib_debug_max_total); printf(")\n"); #ifdef LIB_DEBUG_PINPOINT printf("\nTop %d largest allocated blocks:\n", LIB_DEBUG_TOPMAX); for (index = 0; index < LIB_DEBUG_TOPMAX; index++) { if (lib_debug_top_size[index]) { printf("%8x bytes (", lib_debug_top_size[index]); printsize(lib_debug_top_size[index]); printf(") allocated at %s:%d\n", lib_debug_top_filename[index], lib_debug_top_line[index]); } } #endif #endif } /*----------------------------------------------------------------------------*/ /* like malloc, but abort on out of memory. */ #ifdef LIB_DEBUG_PINPOINT static #endif void *lib_malloc(size_t size) { #ifdef LIB_DEBUG void *ptr = lib_debug_libc_malloc(size); #else void *ptr = malloc(size); #endif #ifndef __OS2__ if (ptr == NULL && size > 0) { fprintf(stderr, "error: lib_malloc failed\n"); archdep_vice_exit(-1); } #endif #ifdef LIB_DEBUG lib_debug_alloc(ptr, size, 3); #endif #if 0 /* clear/fill the block - this should only ever be used for debugging! */ if (ptr) { memset(ptr, 0, size); } #endif return ptr; } #ifdef AMIGA_SUPPORT void *lib_AllocVec(unsigned long size, unsigned long attributes) { #ifdef LIB_DEBUG void *ptr; if (attributes & MEMF_CLEAR) { ptr = lib_debug_libc_calloc(1, size); } else { ptr = lib_debug_libc_malloc(size); } #else void *ptr = AllocVec(size, attributes); #endif #ifndef __OS2__ if (ptr == NULL && size > 0) { fprintf(stderr, "error: lib_AllocVec failed\n"); archdep_vice_exit(-1); } #endif #ifdef LIB_DEBUG lib_debug_alloc(ptr, size, 1); #endif return ptr; } void *lib_AllocMem(unsigned long size, unsigned long attributes) { #ifdef LIB_DEBUG void *ptr; if (attributes & MEMF_CLEAR) { ptr = lib_debug_libc_calloc(1, size); } else { ptr = lib_debug_libc_malloc(size); } #else void *ptr = AllocMem(size, attributes); #endif #ifndef __OS2__ if (ptr == NULL && size > 0) { fprintf(stderr, "error: lib_AllocMem failed\n"); archdep_vice_exit(-1); } #endif #ifdef LIB_DEBUG lib_debug_alloc(ptr, size, 1); #endif return ptr; } #endif /* Like calloc, but abort if not enough memory is available. */ #ifdef LIB_DEBUG_PINPOINT static #endif void *lib_calloc(size_t nmemb, size_t size) { #ifdef LIB_DEBUG void *ptr = lib_debug_libc_calloc(nmemb, size); #else void *ptr = calloc(nmemb, size); #endif #ifndef __OS2__ if (ptr == NULL && (size * nmemb) > 0) { fprintf(stderr, "error: lib_calloc failed\n"); archdep_vice_exit(-1); } #endif #ifdef LIB_DEBUG lib_debug_alloc(ptr, size * nmemb, 1); #endif return ptr; } /* Like realloc, but abort if not enough memory is available. */ #ifdef LIB_DEBUG_PINPOINT static #endif void *lib_realloc(void *ptr, size_t size) { #ifdef LIB_DEBUG void *new_ptr = lib_debug_libc_realloc(ptr, size); #else void *new_ptr = realloc(ptr, size); #endif #ifndef __OS2__ if (new_ptr == NULL) { fprintf(stderr, "error: lib_realloc failed\n"); archdep_vice_exit(-1); } #endif #ifdef LIB_DEBUG lib_debug_free(ptr, 1, 0); lib_debug_alloc(new_ptr, size, 1); #endif return new_ptr; } #ifdef LIB_DEBUG_PINPOINT static #endif void lib_free(const void *constptr) { void * ptr = (void*) constptr; #ifdef LIB_DEBUG lib_debug_free(ptr, 1, 1); #endif #ifdef LIB_DEBUG lib_debug_libc_free(ptr); #else free(ptr); #endif } #ifdef AMIGA_SUPPORT void lib_FreeVec(void *ptr) { #ifdef LIB_DEBUG lib_debug_free(ptr, 1, 1); lib_debug_libc_free(ptr); #else FreeVec(ptr); #endif } void lib_FreeMem(void *ptr, unsigned long size) { #ifdef LIB_DEBUG lib_debug_free(ptr, 1, 1); lib_debug_libc_free(ptr); #else FreeMem(ptr, size); #endif } #endif /*----------------------------------------------------------------------------*/ /* Malloc enough space for `str'; copy `str' into it; then, return its address. */ #ifdef LIB_DEBUG_PINPOINT static #endif char *lib_stralloc(const char *str) { size_t size; char *ptr; if (str == NULL) { #ifdef LIB_DEBUG_PINPOINT fprintf(stderr, "%s:%u: ", lib_debug_pinpoint_filename, lib_debug_pinpoint_line); #endif fprintf(stderr, "error: lib_stralloc(NULL) not allowed.\n"); archdep_vice_exit(-1); } size = strlen(str) + 1; ptr = lib_malloc(size); memcpy(ptr, str, size); return ptr; } #if defined(__CYGWIN32__) || defined(__CYGWIN__) || defined(WIN32_COMPILE) size_t lib_tcstostr(char *str, const char *tcs, size_t len) { strncpy(str, tcs, len); str[len - 1] = 0; return strlen(str); } size_t lib_strtotcs(char *tcs, const char *str, size_t len) { strncpy(tcs, str, len); tcs[len - 1] = 0; return strlen(tcs); } int lib_snprintf(char *str, size_t len, const char *fmt, ...) { va_list args; int ret; va_start(args, fmt); #ifdef HAVE_VSNPRINTF ret = vsnprintf(str, len, fmt, args); #else /* fake version which ignores len */ ret = vsprintf(str, fmt, args); #endif va_end(args); return ret; } #endif /* CYGWIN or WIN32_COMPILE */ #ifdef HAVE_WORKING_VSNPRINTF /* taken shamelessly from printf(3) man page of the Linux Programmer's Manual */ char *lib_mvsprintf(const char *fmt, va_list args) { /* Guess we need no more than 100 bytes. */ int n, size = 100; char *p, *np; if ((p = lib_malloc (size)) == NULL) { return NULL; } while (1) { /* Try to print in the allocated space. */ n = vsnprintf (p, size, fmt, args /* ap */); /* If that worked, return the string. */ if (n > -1 && n < size) { return p; } /* Else try again with more space. */ if (n > -1) { /* glibc 2.1 and C99 */ size = n + 1; /* precisely what is needed */ } else { /* glibc 2.0 */ size *= 2; /* twice the old size */ } if ((np = lib_realloc (p, size)) == NULL) { lib_free(p); return NULL; } else { p = np; } } } #else /* xmsprintf() is like sprintf() but lib_malloc's the buffer by itself. */ #define xmvsprintf_is_digit(c) ((c) >= '0' && (c) <= '9') static int xmvsprintf_skip_atoi(const char **s) { int i = 0; while (xmvsprintf_is_digit(**s)) { i = i * 10 + *((*s)++) - '0'; } return i; } #define ZEROPAD 1 /* pad with zero */ #define SIGN 2 /* unsigned/signed long */ #define PLUS 4 /* show plus */ #define SPACE 8 /* space if plus */ #define LEFT 16 /* left justified */ #define SPECIAL 32 /* 0x */ #define LARGE 64 /* use 'ABCDEF' instead of 'abcdef' */ static inline int xmvsprintf_do_div(long *n, unsigned int base) { int res; res = ((unsigned long)*n) % (unsigned)base; *n = ((unsigned long)*n) / (unsigned)base; return res; } static size_t xmvsprintf_strnlen(const char * s, size_t count) { const char *sc; for (sc = s; count-- && *sc != '\0'; ++sc) { /* nothing */ } return sc - s; } static void xmvsprintf_add(char **buf, unsigned int *bufsize, unsigned int *position, char write) { if (*position == *bufsize) { *bufsize *= 2; *buf = lib_realloc(*buf, *bufsize); } (*buf)[*position] = write; *position += 1; } static void xmvsprintf_number(char **buf, unsigned int *bufsize, unsigned int *position, long num, int base, int size, int precision, int type) { char c, sign, tmp[66]; const char *digits = "0123456789abcdefghijklmnopqrstuvwxyz"; int i; if (type & LARGE) { digits = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; } if (type & LEFT) { type &= ~ZEROPAD; } if (base < 2 || base > 36) { return; } c = (type & ZEROPAD) ? '0' : ' '; sign = 0; if (type & SIGN) { if (num < 0) { sign = '-'; num = -num; size--; } else if (type & PLUS) { sign = '+'; size--; } else if (type & SPACE) { sign = ' '; size--; } } if (type & SPECIAL) { if (base == 16) { size -= 2; } else if (base == 8) { size--; } } i = 0; if (num == 0) { tmp[i++] = '0'; } else { while (num != 0) { tmp[i++] = digits[xmvsprintf_do_div(&num, base)]; } } if (i > precision) { precision = i; } size -= precision; if (!(type & (ZEROPAD + LEFT))) { while (size-- > 0) { xmvsprintf_add(buf, bufsize, position, ' '); } } if (sign) { xmvsprintf_add(buf, bufsize, position, sign); } if (type & SPECIAL) { if (base == 8) { xmvsprintf_add(buf, bufsize, position, '0'); } else if (base == 16) { xmvsprintf_add(buf, bufsize, position, '0'); xmvsprintf_add(buf, bufsize, position, digits[33]); } } if (!(type & LEFT)) { while (size-- > 0) { xmvsprintf_add(buf, bufsize, position, c); } } while (i < precision--) { xmvsprintf_add(buf, bufsize, position, '0'); } while (i-- > 0) { xmvsprintf_add(buf, bufsize, position, tmp[i]); } while (size-- > 0) { xmvsprintf_add(buf, bufsize, position, ' '); } } char *lib_mvsprintf(const char *fmt, va_list args) { char *buf; unsigned int position, bufsize; size_t len; int i, base; unsigned long num; const char *s; int flags; /* flags to number() */ int field_width; /* width of output field */ int precision; /* min. # of digits for integers; max number of chars for from string */ int qualifier; /* 'h', 'l', or 'L' for integer fields */ /* Setup the initial buffer. */ buf = lib_malloc(10); position = 0; bufsize = 10; for (; *fmt; ++fmt) { if (*fmt != '%') { xmvsprintf_add(&buf, &bufsize, &position, *fmt); continue; } /* process flags */ flags = 0; repeat: ++fmt; /* this also skips first '%' */ switch (*fmt) { case '-': flags |= LEFT; goto repeat; case '+': flags |= PLUS; goto repeat; case ' ': flags |= SPACE; goto repeat; case '#': flags |= SPECIAL; goto repeat; case '0': flags |= ZEROPAD; goto repeat; } /* get field width */ field_width = -1; if (xmvsprintf_is_digit(*fmt)) { field_width = xmvsprintf_skip_atoi(&fmt); } else if (*fmt == '*') { ++fmt; /* it's the next argument */ field_width = va_arg(args, int); if (field_width < 0) { field_width = -field_width; flags |= LEFT; } } /* get the precision */ precision = -1; if (*fmt == '.') { ++fmt; if (xmvsprintf_is_digit(*fmt)) { precision = xmvsprintf_skip_atoi(&fmt); } else if (*fmt == '*') { ++fmt; /* it's the next argument */ precision = va_arg(args, int); } if (precision < 0) { precision = 0; } } /* get the conversion qualifier */ qualifier = -1; if (*fmt == 'h' || *fmt == 'l' || *fmt == 'L') { qualifier = *fmt; ++fmt; } /* default base */ base = 10; switch (*fmt) { case 'c': if (!(flags & LEFT)) { while (--field_width > 0) { xmvsprintf_add(&buf, &bufsize, &position, ' '); } } xmvsprintf_add(&buf, &bufsize, &position, (unsigned char) va_arg(args, int)); while (--field_width > 0) { xmvsprintf_add(&buf, &bufsize, &position, ' '); } continue; case 's': s = va_arg(args, char *); if (!s) { s = "<NULL>"; } len = xmvsprintf_strnlen(s, precision); if (!(flags & LEFT)) { while (field_width > 0 && len < field_width--) { xmvsprintf_add(&buf, &bufsize, &position, ' '); } } for (i = 0; i < len; ++i) { xmvsprintf_add(&buf, &bufsize, &position, *s++); } while (field_width > 0 && len < field_width--) { xmvsprintf_add(&buf, &bufsize, &position, ' '); } continue; case 'p': if (field_width == -1) { field_width = 2 * sizeof(void *); flags |= ZEROPAD; } xmvsprintf_number(&buf, &bufsize, &position, vice_ptr_to_uint(va_arg(args, void *)), 16, field_width, precision, flags); continue; case '%': xmvsprintf_add(&buf, &bufsize, &position, '%'); continue; /* integer number formats - set up the flags and "break" */ case 'o': base = 8; break; case 'X': flags |= LARGE; /* FALLTHRU */ /* to lowercase hex */ case 'x': base = 16; break; case 'd': case 'i': flags |= SIGN; /* FALLTHRU */ /* to unsigned dec */ case 'u': break; default: xmvsprintf_add(&buf, &bufsize, &position, '%'); if (*fmt) { xmvsprintf_add(&buf, &bufsize, &position, *fmt); } else { --fmt; } continue; } if (qualifier == 'l') { num = va_arg(args, unsigned long); } else if (qualifier == 'h') { num = (unsigned short) va_arg(args, int); if (flags & SIGN) { num = (short) num; } } else if (flags & SIGN) { num = va_arg(args, int); } else { num = va_arg(args, unsigned int); } xmvsprintf_number(&buf, &bufsize, &position, num, base, field_width, precision, flags); } xmvsprintf_add(&buf, &bufsize, &position, '\0'); /* Trim buffer to final size. */ buf = lib_realloc(buf, strlen(buf) + 1); return buf; } #endif /* #ifdef HAVE_WORKING_VSNPRINTF */ char *lib_msprintf(const char *fmt, ...) { va_list args; char *buf; va_start(args, fmt); buf = lib_mvsprintf(fmt, args); va_end(args); return buf; } /*----------------------------------------------------------------------------*/ #ifdef LIB_DEBUG_PINPOINT void *lib_malloc_pinpoint(size_t size, const char *name, unsigned int line) { lib_debug_pinpoint_filename = name; lib_debug_pinpoint_line = line; return lib_malloc(size); } void lib_free_pinpoint(const void *p, const char *name, unsigned int line) { lib_debug_pinpoint_filename = name; lib_debug_pinpoint_line = line; lib_free(p); } void *lib_calloc_pinpoint(size_t nmemb, size_t size, const char *name, unsigned int line) { lib_debug_pinpoint_filename = name; lib_debug_pinpoint_line = line; return lib_calloc(nmemb, size); } void *lib_realloc_pinpoint(void *p, size_t size, const char *name, unsigned int line) { lib_debug_pinpoint_filename = name; lib_debug_pinpoint_line = line; return lib_realloc(p, size); } char *lib_stralloc_pinpoint(const char *str, const char *name, unsigned int line) { lib_debug_pinpoint_filename = name; lib_debug_pinpoint_line = line; return lib_stralloc(str); } #ifdef AMIGA_SUPPORT void *lib_AllocVec_pinpoint(unsigned long size, unsigned long attributes, char *name, unsigned int line) { lib_debug_pinpoint_filename = name; lib_debug_pinpoint_line = line; return lib_AllocVec(size, attributes); } void lib_FreeVec_pinpoint(void *ptr, char *name, unsigned int line) { lib_debug_pinpoint_filename = name; lib_debug_pinpoint_line = line; return lib_FreeVec(ptr); } void *lib_AllocMem_pinpoint(unsigned long size, unsigned long attributes, char *name, unsigned int line) { lib_debug_pinpoint_filename = name; lib_debug_pinpoint_line = line; return lib_AllocMem(size, attributes); } void lib_FreeMem_pinpoint(void *ptr, unsigned long size, char *name, unsigned int line) { lib_debug_pinpoint_filename = name; lib_debug_pinpoint_line = line; return lib_FreeMem(ptr, size); } #endif /*----------------------------------------------------------------------------*/ #endif /* encapsulated random routines to generate random numbers within a given range. see http://c-faq.com/lib/randrange.html */ /* set random seed for rand() from current time, so things like random startup delay are actually random, ie different on each startup, at all. */ void lib_init_rand(void) { srand((unsigned int)time(NULL)); } unsigned int lib_unsigned_rand(unsigned int min, unsigned int max) { return min + (rand() / ((RAND_MAX / (max - min + 1)) + 1)); } float lib_float_rand(float min, float max) { return min + ((float)rand() / (((float)RAND_MAX / (max - min + 1.0f)) + 1.0f)); }
26.414826
185
0.583836
c8a129fed10bc0b673f1e2601516b7d381ae3bbf
3,211
sql
SQL
db/16-Sept-15.sql
sachintyagi/lokhit
44812b5fd6933e79f40746752197ac5de64b908b
[ "BSD-3-Clause" ]
null
null
null
db/16-Sept-15.sql
sachintyagi/lokhit
44812b5fd6933e79f40746752197ac5de64b908b
[ "BSD-3-Clause" ]
null
null
null
db/16-Sept-15.sql
sachintyagi/lokhit
44812b5fd6933e79f40746752197ac5de64b908b
[ "BSD-3-Clause" ]
null
null
null
/* SQLyog Enterprise - MySQL GUI v7.02 MySQL - 5.5.36 : Database - lokhitnidhi ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!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' */; CREATE DATABASE /*!32312 IF NOT EXISTS*/`lokhitnidhi` /*!40100 DEFAULT CHARACTER SET latin1 */; USE `lokhitnidhi`; /*Table structure for table `employees` */ DROP TABLE IF EXISTS `employees`; CREATE TABLE `employees` ( `id` int(11) NOT NULL AUTO_INCREMENT, `company_id` int(11) NOT NULL, `branch_id` int(11) NOT NULL, `role_id` int(11) NOT NULL, `introducer_code` varchar(20) DEFAULT NULL, `firstname` varchar(100) NOT NULL, `lastname` varchar(100) DEFAULT NULL, `employee_code` varchar(25) NOT NULL, `emailid` varchar(120) DEFAULT NULL, `dob` date DEFAULT NULL, `gender` enum('Male','Female','Others') NOT NULL DEFAULT 'Male', `userid` varchar(20) DEFAULT NULL, `password` varchar(50) DEFAULT NULL, `gardian_name` varchar(100) DEFAULT NULL, `gardian_relation` varchar(50) DEFAULT NULL, `mobile_number` varchar(15) DEFAULT NULL, `nominee_name` varchar(100) DEFAULT NULL, `nominee_relation` varchar(100) DEFAULT NULL, `nominee_address` varchar(100) DEFAULT NULL, `country_id` int(11) DEFAULT '1', `state_id` int(11) DEFAULT NULL, `city_id` varchar(150) DEFAULT NULL, `address` varchar(500) DEFAULT NULL, `member_id` varchar(20) DEFAULT NULL, `status` tinyint(1) DEFAULT '0', `created_at` datetime DEFAULT NULL, `created_by` int(11) NOT NULL, `updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, `updated_by` int(11) NOT NULL, `is_deleted` tinyint(2) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `employee_code` (`employee_code`), UNIQUE KEY `idx_members_customer_id` (`member_id`), UNIQUE KEY `member_id` (`member_id`), UNIQUE KEY `Unique_Member_Id` (`member_id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8; /*Data for the table `employees` */ insert into `employees`(`id`,`company_id`,`branch_id`,`role_id`,`introducer_code`,`firstname`,`lastname`,`employee_code`,`emailid`,`dob`,`gender`,`userid`,`password`,`gardian_name`,`gardian_relation`,`mobile_number`,`nominee_name`,`nominee_relation`,`nominee_address`,`country_id`,`state_id`,`city_id`,`address`,`member_id`,`status`,`created_at`,`created_by`,`updated_at`,`updated_by`,`is_deleted`) values (1,1,1,3,'2353456346','Shiv Kumar','Tyagi','100100000001','sktyagi12345@gmail.com','2015-09-01','Male','100100000001',NULL,'Surendra Tyagi',NULL,'9891274404','Mamta Tyagi','Wife','Test address',95,35,'Noida','This is address aaa','',1,'2015-09-16 21:10:27',1,'2015-09-17 00:40:27',1,0),(2,1,1,3,NULL,'Amit','Verma','100100000002','amitv@lokhitnidhi.com',NULL,'Male',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,1,NULL,NULL,NULL,'100100000002',1,'2015-09-15 22:52:25',0,'2015-09-17 00:42:14',0,0); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
48.651515
899
0.690128
b170ccb2007d0fffaa1040f520e8a406dd80b011
13,891
c
C
rtos/freeRTOS/vendors/gwt/gap8/pmsis/drivers/pwm/pwm_internal.c
00-01/gap_sdk
25444d752b26ccf0b848301c381692d77172852c
[ "Apache-2.0" ]
118
2018-05-22T08:45:59.000Z
2022-03-30T07:00:45.000Z
rtos/freeRTOS/vendors/gwt/gap8/pmsis/drivers/pwm/pwm_internal.c
00-01/gap_sdk
25444d752b26ccf0b848301c381692d77172852c
[ "Apache-2.0" ]
213
2018-07-25T02:37:32.000Z
2022-03-30T18:04:01.000Z
rtos/freeRTOS/vendors/gwt/gap8/pmsis/drivers/pwm/pwm_internal.c
00-01/gap_sdk
25444d752b26ccf0b848301c381692d77172852c
[ "Apache-2.0" ]
76
2018-07-04T08:19:27.000Z
2022-03-24T09:58:05.000Z
/* * Copyright (c) 2019, GreenWaves Technologies, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * o Neither the name of GreenWaves Technologies, Inc. nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "pmsis.h" /******************************************************************************* * Definitions ******************************************************************************/ /******************************************************************************* * Driver data ******************************************************************************/ static struct pwm_data_s *g_pwm_data[ARCHI_NB_PWM] = {NULL}; /******************************************************************************* * Internal functions ******************************************************************************/ static void __pi_pwm_handler(void *arg) { uint32_t event = (uint32_t) arg; uint32_t periph_id = event - SOC_EVENT_PWM(0); struct pwm_data_s *driver_data = g_pwm_data[periph_id]; if (driver_data->event_task != NULL) { pi_task_push(driver_data->event_task); } } static void __pi_pwm_timer_conf_set(uint8_t pwm_id, struct pi_pwm_conf *conf) { uint32_t config = (uint32_t) conf->timer_conf; config |= (conf->input_src << PI_PWM_CONFIG_INSEL_OFFSET); config |= (conf->prescaler << PI_PWM_CONFIG_PRESCALER_OFFSET); hal_pwm_config_mask_set(pwm_id, config); } static void __pi_pwm_threshold_set(uint8_t pwm_id, uint16_t counter_start, uint16_t counter_end) { hal_pwm_threshold_set(pwm_id, counter_start, counter_end); } static void __pi_pwm_channel_config_set(uint8_t pwm_id, pi_pwm_channel_e channel, uint16_t threshold, pi_pwm_ch_config_e config) { hal_pwm_channel_th_mode_set(pwm_id, channel, threshold, config); } static void __pi_pwm_output_event_set(pi_pwm_evt_sel_e evt_sel, pi_pwm_output_evt_e evt_output) { hal_pwm_ctrl_evt_cfg_set(evt_sel, evt_output); } static void __pi_pwm_output_event_clear(pi_pwm_evt_sel_e evt_sel) { hal_pwm_ctrl_evt_cfg_disable(evt_sel); } static int32_t __pi_pwm_user_cb_attach(uint8_t pwm_id, pi_task_t *cb) { struct pwm_data_s *driver_data = g_pwm_data[pwm_id]; if (driver_data == NULL) { PWM_TRACE_ERR("Error PWM(%d) device not opened !\n", driver_data->device_id); return -11; } PWM_TRACE("PWM(%d) attaching event callback=%lx.\n", driver_data->device_id, cb); driver_data->event_task = cb; hal_soc_eu_set_fc_mask(SOC_EVENT_PWM(driver_data->device_id)); return 0; } static void __pi_pwm_command_set(uint8_t pwm_id, pi_pwm_cmd_e cmd) { hal_pwm_cmd_set(pwm_id, cmd); } static void __pi_pwm_timer_freq_reset(uint8_t pwm_id) { struct pwm_data_s *driver_data = g_pwm_data[pwm_id]; /* Stop the PWM timer first. */ PWM_TRACE("Stop PWM(%d) timer and reset frequency to 0.\n", pwm_id); __pi_pwm_command_set(pwm_id, PI_PWM_CMD_STOP); driver_data->frequency = 0; } static void __pi_pwm_freq_cb(void *args) { uint32_t irq = __disable_irq(); uint32_t pwm_ch = (uint32_t) args; uint8_t pwm_id = (uint8_t) PI_PWM_TIMER_ID(pwm_ch); uint8_t ch_id = (uint8_t) PI_PWM_CHANNEL_ID(pwm_ch); struct pwm_data_s *driver_data = g_pwm_data[pwm_id]; /* Counter start and end. */ uint32_t th_hi = 0; uint16_t th_lo = 0; /* th_channel holds duty cycle. */ uint16_t th_channel = th_hi; /* Stop PWM first. */ __pi_pwm_command_set(pwm_id, PI_PWM_CMD_STOP); /* Counter start and end. */ uint32_t periph_freq = pi_freq_get(PI_FREQ_DOMAIN_FC); th_hi = periph_freq / driver_data->frequency; th_lo = 1; if (th_hi > 0xFFFF) { PWM_TRACE_ERR("PWM(%d) error : can not set frequency, SoC frequency is too high." "Use prescaler to slow down clock or lower SoC frequency." "SoC_freq=%ld, PWM_freq=%ld\n", driver_data->device_id, periph_freq, driver_data->frequency); return; } PWM_TRACE("PWM(%d) updating timer threshold=%lx\n", driver_data->device_id, th_hi); /* Set counter start, end. */ __pi_pwm_threshold_set(pwm_id, th_lo, th_hi); /* th_channel holds duty cycle. */ th_channel = th_hi; for (uint8_t i=0; i < (uint8_t) ARCHI_NB_CHANNEL_PER_PWM; i++) { uint8_t duty_cycle = driver_data->duty_cycle[i]; PWM_TRACE("PWM(%d) duty_cycle[%d]=%d\n", driver_data->device_id, i, duty_cycle); if (duty_cycle != 0xFF) { if (duty_cycle == 0) { th_channel = 0; } else if (duty_cycle != 100) { th_channel = (th_hi * (100 - duty_cycle)) / 100; } PWM_TRACE("PWM(%d) setting channel=%d\n", driver_data->device_id, i); /* Set channel threshold, mode. */ __pi_pwm_channel_config_set(pwm_id, ch_id, th_channel, PI_PWM_SET_CLEAR); } } /* Restart PWM after update. */ __pi_pwm_command_set(pwm_id, PI_PWM_CMD_START); __restore_irq(irq); } /******************************************************************************* * API implementation ******************************************************************************/ void __pi_pwm_conf_init(struct pi_pwm_conf *conf) { conf->device = PI_DEVICE_PWM_TYPE; conf->pwm_id = 0; conf->ch_id = PI_PWM_CHANNEL0; conf->input_src = 0; conf->timer_conf = PI_PWM_EVT_EACH_CLK_CYCLE | PI_PWM_CLKSEL_FLL | PI_PWM_UPDOWNSEL_RESET; conf->prescaler = 0; } int32_t __pi_pwm_open(struct pi_pwm_conf *conf, uint32_t **device_data) { if (((uint8_t) ARCHI_NB_PWM < conf->pwm_id) || ((uint8_t) ARCHI_NB_CHANNEL_PER_PWM < conf->ch_id)) { PWM_TRACE_ERR("Wrong parameters : pwm_id=%d, ch_id=%d\n", conf->pwm_id, conf->ch_id); return -11; } struct pwm_data_s *driver_data = g_pwm_data[(uint8_t) conf->pwm_id]; if (driver_data == NULL) { driver_data = (struct pwm_data_s *) pi_l2_malloc(sizeof(struct pwm_data_s)); if (driver_data == NULL) { PWM_TRACE_ERR("Error allocating PWM driver data.\n"); return -12; } driver_data->frequency = 0; driver_data->nb_open = 0; driver_data->device_id = conf->pwm_id; driver_data->event_task = NULL; driver_data->duty_cycle[0] = 0xFF; driver_data->duty_cycle[1] = 0xFF; driver_data->duty_cycle[2] = 0xFF; driver_data->duty_cycle[3] = 0xFF; g_pwm_data[conf->pwm_id] = driver_data; /* Set handler. */ pi_fc_event_handler_set(SOC_EVENT_PWM(driver_data->device_id), __pi_pwm_handler); /* Enable SOC event propagation to FC. */ //hal_soc_eu_set_fc_mask(SOC_EVENT_PWM(driver_data->device_id)); /* Disable PWM CG. */ hal_pwm_ctrl_cg_disable(driver_data->device_id); /* Setup PWM timer. */ __pi_pwm_timer_conf_set(driver_data->device_id, conf); /* Attach freq callback. */ uint32_t pwm_id = conf->pwm_id; pi_freq_callback_init(&(driver_data->pwm_freq_cb), __pi_pwm_freq_cb, (void *) pwm_id); pi_freq_callback_add(&(driver_data->pwm_freq_cb)); } driver_data->nb_open++; PWM_TRACE("PWM(%d) opened %ld times\n", driver_data->device_id, driver_data->nb_open); *device_data = (uint32_t *) ((((uint8_t) conf->ch_id) << PI_PWM_CHANNEL_ID_SHIFT) | (((uint8_t) conf->pwm_id) << PI_PWM_TIMER_ID_SHIFT)); return 0; } void __pi_pwm_close(uint32_t pwm_ch) { uint8_t pwm_id = (uint8_t) PI_PWM_TIMER_ID(pwm_ch); struct pwm_data_s *driver_data = g_pwm_data[pwm_id]; driver_data->nb_open--; PWM_TRACE("PWM(%d) opened %ld times.\n", driver_data->device_id, driver_data->nb_open); if (driver_data->nb_open == 0) { PWM_TRACE("Closing and CG PWM(%d).\n", driver_data->device_id); /* Remove freq callback. */ pi_freq_callback_remove(&(driver_data->pwm_freq_cb)); /* Free allocated structure. */ pi_l2_free(g_pwm_data[pwm_id], sizeof(struct pwm_data_s)); /* Clear handler. */ pi_fc_event_handler_clear(SOC_EVENT_PWM(pwm_id)); /* Disable SOC event propagation to FC. */ hal_soc_eu_clear_fc_mask(SOC_EVENT_PWM(pwm_id)); /* Enable PWM CG. */ hal_pwm_ctrl_cg_enable(pwm_id); } } int32_t __pi_pwm_ioctl(uint32_t pwm_ch, pi_pwm_ioctl_cmd_e cmd, void *arg) { uint8_t pwm_id = (uint8_t) PI_PWM_TIMER_ID(pwm_ch); pi_pwm_cmd_e timer_cmd = (pi_pwm_cmd_e) arg; struct pi_pwm_conf *conf = (struct pi_pwm_conf *) arg; uint32_t threshold = (uint32_t) arg; struct pi_pwm_ioctl_ch_config *ch_conf = (struct pi_pwm_ioctl_ch_config *) arg; struct pi_pwm_ioctl_evt *evt = (struct pi_pwm_ioctl_evt *) arg; pi_task_t *cb_task = (pi_task_t *) arg; switch (cmd) { case PI_PWM_TIMER_COMMAND : __pi_pwm_command_set(pwm_id, timer_cmd); return 0; case PI_PWM_TIMER_CONFIG : __pi_pwm_timer_conf_set(pwm_id, conf); return 0; case PI_PWM_TIMER_THRESH : __pi_pwm_threshold_set(pwm_id, threshold & 0xFFFF, threshold >> 16); return 0; case PI_PWM_CH_CONFIG : __pi_pwm_channel_config_set(pwm_id, ch_conf->channel, ch_conf->ch_threshold, ch_conf->config); return 0; case PI_PWM_EVENT_SET : __pi_pwm_output_event_set(evt->evt_sel, evt->evt_output); return 0; case PI_PWM_EVENT_CLEAR : __pi_pwm_output_event_clear(evt->evt_sel); return 0; case PI_PWM_RESET_FREQ : __pi_pwm_timer_freq_reset(pwm_id); return 0; case PI_PWM_ATTACH_CB : return __pi_pwm_user_cb_attach(pwm_id, cb_task); default : return -1; } } uint32_t __pi_pwm_counter_get(uint32_t pwm_ch) { uint8_t pwm_id = (uint8_t) PI_PWM_TIMER_ID(pwm_ch); return hal_pwm_counter_get(pwm_id); } int32_t __pi_pwm_duty_cycle_set(uint32_t pwm_ch, uint32_t pwm_freq, uint8_t duty_cycle) { uint8_t pwm_id = (uint8_t) PI_PWM_TIMER_ID(pwm_ch); uint8_t ch_id = (uint8_t) PI_PWM_CHANNEL_ID(pwm_ch); struct pwm_data_s *driver_data = g_pwm_data[pwm_id]; if (driver_data == NULL) { PWM_TRACE_ERR("Error PWM(%d) device not opened !\n", driver_data->device_id); return -11; } if ((100 < duty_cycle)) { PWM_TRACE_ERR("Error duty cycle value. It should be 0 <= dc <= 100.\n"); return -12; } /* Counter start and end. */ uint32_t th_hi = 0; uint16_t th_lo = 1; /* th_channel holds duty cycle. */ uint16_t th_channel = th_hi; if (driver_data->frequency == 0) { driver_data->frequency = pwm_freq; uint32_t periph_freq = pi_freq_get(PI_FREQ_DOMAIN_FC); /* Counter start and end. */ th_hi = periph_freq / pwm_freq; th_lo = 1; if (th_hi > 0xFFFF) { PWM_TRACE_ERR("PWM(%d) error : can not set frequency, SoC frequency is too high." "Use prescaler to slow down clock or lower SoC frequency." "SoC_freq=%ld, PWM_freq=%ld\n", driver_data->device_id, periph_freq, pwm_freq); return -13; } /* Set counter start, end. */ __pi_pwm_threshold_set(pwm_id, th_lo, th_hi); } else { th_hi = hal_pwm_threshold_get(pwm_id); //th_lo = 1; th_hi = th_hi >> 16; } if (driver_data->frequency != pwm_freq) { PWM_TRACE_ERR("PWM(%d) error : frequency in use is different, PWM_freq=%ld, freq=%ld\n", driver_data->device_id, driver_data->frequency, pwm_freq); return -14; } driver_data->duty_cycle[ch_id] = duty_cycle; /* th_channel holds duty cycle. */ th_channel = th_hi; if (duty_cycle == 0) { th_channel = 0; } else if (duty_cycle != 100) { th_channel = (th_hi * (100 - duty_cycle)) / 100; } PWM_TRACE("Setting PWM(%d)->CH_%d : freq=%ld, duty_cycle=%d\n", pwm_id, ch_id, pwm_freq, duty_cycle); /* Set channel threshold, mode. */ __pi_pwm_channel_config_set(pwm_id, ch_id, th_channel, PI_PWM_SET_CLEAR); return 0; }
34.298765
96
0.623929
8306546fbf9ade55adb2798a980e77d7c08628ff
204
asm
Assembly
MOS5/TestProgram/test.asm
Mishin870/MOS
cf2a94b0a0ace3380dd58adc4848baed78097df2
[ "MIT" ]
1
2020-10-10T08:31:42.000Z
2020-10-10T08:31:42.000Z
MOS5/TestProgram/test.asm
Mishin870/MOS
cf2a94b0a0ace3380dd58adc4848baed78097df2
[ "MIT" ]
null
null
null
MOS5/TestProgram/test.asm
Mishin870/MOS
cf2a94b0a0ace3380dd58adc4848baed78097df2
[ "MIT" ]
null
null
null
;попытка реализовать простейшую программу на низшем кольце защиты ;(программа от имени юзера). с доступом к апи ядра (к среднему кольцу) use32 ;mov dx, 0x3F8 ;mov al, 'c' ;out dx, al int 30h qwe: jmp qwe
20.4
70
0.75
16790114b8a331939bda895e9715e1af485965cf
1,536
h
C
src/public/g15/ig15.h
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/public/g15/ig15.h
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/public/g15/ig15.h
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//====== Copyright � 1996-2005, Valve Corporation, All rights reserved. ======= // // Purpose: // //============================================================================= #ifndef IG15_H #define IG15_H #ifdef _WIN32 #pragma once #endif typedef void *G15_HANDLE; typedef enum { G15_BUTTON_1, G15_BUTTON_2, G15_BUTTON_3, G15_BUTTON_4 } G15SoftButton; typedef enum { G15_SMALL, G15_MEDIUM, G15_BIG } G15TextSize; typedef enum { G15_SCROLLING_TEXT, G15_STATIC_TEXT, G15_ICON, G15_PROGRESS_BAR, G15_UNKNOWN } G15ObjectType; class IG15 { public: virtual void GetLCDSize(int &w, int &h) = 0; // w, h should match the return value from GetLCDSize!!! // Creates the underlying object virtual bool Init(char const *name) = 0; // Destroys the underlying object virtual void Shutdown() = 0; virtual bool IsConnected() = 0; // Add/remove virtual G15_HANDLE AddText(G15ObjectType type, G15TextSize size, int alignment, int maxLengthPixels) = 0; virtual G15_HANDLE AddIcon(void *icon, int sizeX, int sizeY) = 0; virtual void RemoveAndDestroyObject(G15_HANDLE hObject) = 0; // Change virtual int SetText(G15_HANDLE handle, char const *text) = 0; virtual int SetOrigin(G15_HANDLE handle, int x, int y) = 0; virtual int SetVisible(G15_HANDLE handle, bool visible) = 0; virtual bool ButtonTriggered(int button) = 0; virtual void UpdateLCD(unsigned int dwTimestamp) = 0; }; #define G15_INTERFACE_VERSION "G15_INTERFACE_VERSION001" #endif // IG15_H
24.380952
109
0.672526
b2d93cfb63dcf1ebc579a1abfad61711545c68bf
628
py
Python
app/main/controller/sample_controller.py
Eliotdoesprogramming/python.flask.sqlalchemy.Rest_Api_Template
3f0a98ae4676aef9ecdf0df70eb9d1990fee6182
[ "MIT" ]
null
null
null
app/main/controller/sample_controller.py
Eliotdoesprogramming/python.flask.sqlalchemy.Rest_Api_Template
3f0a98ae4676aef9ecdf0df70eb9d1990fee6182
[ "MIT" ]
null
null
null
app/main/controller/sample_controller.py
Eliotdoesprogramming/python.flask.sqlalchemy.Rest_Api_Template
3f0a98ae4676aef9ecdf0df70eb9d1990fee6182
[ "MIT" ]
null
null
null
from flask import Flask from flask_sqlalchemy import SQLAlchemy from service.api_service import Service class SampleController(object): def __init__(self,app:Flask,db:SQLAlchemy,service:Service) -> None: self.app=app self.db=db self.service=service self.add_routes(app) def add_routes(self,app:Flask): app.add_url_rule('/example',methods=['GET'],view_func=self.example) app.add_url_rule('/example',methods=['POST'],view_func=self.add_example) def example(self): return self.service.example() def add_example(self): return self.service.add_example()
39.25
80
0.703822
0cfa89782c8d3290c0c6ceba7319a0449a110fed
2,585
py
Python
model/embeddings.py
johnnytorres/crisis_conv_crosslingual
a30e762007e08190275bdd83af3c0bbc717fb516
[ "MIT" ]
null
null
null
model/embeddings.py
johnnytorres/crisis_conv_crosslingual
a30e762007e08190275bdd83af3c0bbc717fb516
[ "MIT" ]
null
null
null
model/embeddings.py
johnnytorres/crisis_conv_crosslingual
a30e762007e08190275bdd83af3c0bbc717fb516
[ "MIT" ]
1
2019-12-03T00:29:14.000Z
2019-12-03T00:29:14.000Z
import os import logging import argparse import numpy as np import tensorflow as tf from keras_preprocessing.text import Tokenizer from tqdm import tqdm from data import DataLoader class EmbeddingsBuilder: def __init__(self, args): logging.info('initializing...') self.args = args self.dataset = DataLoader(self.args) self.embeddings_path = args.embeddings_path self.small_embeddings_path = os.path.splitext(self.embeddings_path)[0] + '_small.vec' logging.info('initializing...[ok]') def build_embedding(self, vocab_dict): """ Load embedding vectors from a .txt file. Optionally limit the vocabulary to save memory. `vocab` should be a set. """ num_words = len(vocab_dict) num_found = 0 with open(self.small_embeddings_path, 'w') as out_file: with tf.gfile.GFile(self.embeddings_path) as f: header =next(f) num_embeddings, embeddings_dim = header.split(' ') num_embeddings = int(num_embeddings) out_file.write(header) for _, line in tqdm(enumerate(f), 'loading embeddings', total=num_embeddings): tokens = line.rstrip().split(" ") word = tokens[0] if word in vocab_dict: num_found += 1 out_file.write(line) tf.logging.info("Found embeddings for {} out of {} words in vocabulary".format(num_found, num_words)) def run(self): self.dataset.load() X = self.dataset.X_train_labeled['moment'].values X = np.append(X, self.dataset.X_train_unlabeled['moment'].values, axis=0) X = np.append(X, self.dataset.X_test['moment'].values, axis=0) tokenizer = Tokenizer() tokenizer.fit_on_texts(X) self.build_embedding(tokenizer.word_index) if __name__ == '__main__': logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG) logging.info('initializing task...') parser = argparse.ArgumentParser() parser.add_argument('--data-dir', default='data/claff-happydb') parser.add_argument('--embeddings-path', type=str, default=None) parser.add_argument('--num-unlabeled', type=int, default=1000) parser.add_argument('--use-allfeats', action='store_true', default=False) parser.add_argument('--predict', action='store_true', default=True) builder = EmbeddingsBuilder(args=parser.parse_args()) builder.run() logging.info('task finished...[ok]')
31.91358
109
0.635977
75e147ff08d031c15b62d14418d43f760e0e14c9
2,456
rs
Rust
src/main.rs
MerlinDMC/noderole
7d90012e597502f2623c333f775f3111585b51cc
[ "Apache-2.0", "MIT" ]
null
null
null
src/main.rs
MerlinDMC/noderole
7d90012e597502f2623c333f775f3111585b51cc
[ "Apache-2.0", "MIT" ]
null
null
null
src/main.rs
MerlinDMC/noderole
7d90012e597502f2623c333f775f3111585b51cc
[ "Apache-2.0", "MIT" ]
null
null
null
use clap::{crate_name, AppSettings, Parser}; use figment::{ providers::{Format, Yaml}, Figment, }; use k8s_openapi::api::core::v1::Node; use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta; use kube::api::{Api, Patch, PatchParams}; use kube::Client; use serde::Deserialize; use std::collections::BTreeMap; #[derive(Parser)] #[clap(author, version, about, long_about = None)] #[clap(global_setting(AppSettings::PropagateVersion))] #[clap(global_setting(AppSettings::UseLongFormatForHelpSubcommand))] struct Cli { /// Path to the config file #[clap(parse(from_os_str))] #[clap(short, long, default_value = "/etc/noderole.yml")] config: std::path::PathBuf, /// Kubernetes Node name #[clap(short, long)] #[clap(env = "NODE_NAME")] nodename: String, } #[derive(Deserialize)] struct Config { /// Assignable node roles as a list of strings roles: Option<Vec<String>>, /// KV pairs of additional node labels to assign labels: Option<BTreeMap<String, String>>, } #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { let args = Cli::parse(); let config: Config = Figment::new().merge(Yaml::file(args.config)).extract()?; let client = Client::try_default().await?; let nodes: Api<Node> = Api::all(client.clone()); // try reading the given node and hard fail if not available nodes.get(args.nodename.as_str()).await?; // map of labels to assign let mut node_labels: BTreeMap<String, String> = BTreeMap::new(); // roles defined in the config file will be prefixed accordingly match config.roles { Some(roles) => { for role in roles { node_labels.insert( format!("node-role.kubernetes.io/{}", role), "true".to_string(), ); } } None => {} } // additional raw KV labels will be appended as-is match config.labels { Some(labels) => node_labels.extend(labels), None => {} } let patch = Node { metadata: ObjectMeta { name: Some(args.nodename.clone()), labels: Some(node_labels), ..ObjectMeta::default() }, spec: None, status: None, }; let params = PatchParams::apply(crate_name!()); let patch = Patch::Apply(&patch); nodes.patch(args.nodename.as_str(), &params, &patch).await?; Ok(()) }
27.595506
82
0.607492
72d35874939a1947b03a082b32b4dfaf7ddab3a4
4,543
kt
Kotlin
src/test/kotlin/de/smartsquare/starter/mqttadmin/client/ClientServiceTest.kt
SmartsquareGmbH/mqtt-admin-starter
a73d3544881c5c35e1b4a1e5fb6f889c496563cc
[ "MIT" ]
1
2021-06-04T13:31:31.000Z
2021-06-04T13:31:31.000Z
src/test/kotlin/de/smartsquare/starter/mqttadmin/client/ClientServiceTest.kt
SmartsquareGmbH/mqtt-admin-starter
a73d3544881c5c35e1b4a1e5fb6f889c496563cc
[ "MIT" ]
1
2021-05-06T09:01:03.000Z
2021-05-06T09:01:03.000Z
src/test/kotlin/de/smartsquare/starter/mqttadmin/client/ClientServiceTest.kt
SmartsquareGmbH/mqtt-admin-starter
a73d3544881c5c35e1b4a1e5fb6f889c496563cc
[ "MIT" ]
null
null
null
package de.smartsquare.starter.mqttadmin.client import de.smartsquare.starter.mqttadmin.EmqxExtension import de.smartsquare.starter.mqttadmin.client.AclRule.TopicAction.PUB import de.smartsquare.starter.mqttadmin.client.AclRule.TopicAction.SUB import de.smartsquare.starter.mqttadmin.client.ClientActionResult.Failure import de.smartsquare.starter.mqttadmin.client.ClientActionResult.Success import de.smartsquare.starter.mqttadmin.emqx.EmqxApiClient import de.smartsquare.starter.mqttadmin.emqx.EmqxApiConfiguration import org.amshove.kluent.shouldBe import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeInstanceOf import org.amshove.kluent.shouldBeTrue import org.amshove.kluent.shouldHaveSingleItem import org.amshove.kluent.shouldHaveSize import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest @ExtendWith(EmqxExtension::class) @SpringBootTest(classes = [EmqxApiConfiguration::class, ClientConfiguration::class]) class ClientServiceTest { @Autowired private lateinit var clientService: ClientService @Autowired private lateinit var emqxApiClient: EmqxApiClient private val username = "testusername" private val password = "test" private val aclRule = AclRule( username = username, topic = "testTopic/#", action = SUB, allow = true ) @AfterEach fun cleanUp() { emqxApiClient.unregisterClient(username) } @Test fun `registers client without acl rules`() { val result = clientService.registerClient(username, password) result shouldBe Success } @Test fun `registers client with acl rules`() { val result = clientService.registerClient(username, password, aclRule, aclRule.copy(topic = "anotherTopic")) result shouldBe Success } @Test fun `should not register client twice`() { clientService.registerClient(username, password) val result = clientService.registerClient(username, password) result shouldBeInstanceOf Failure::class } @Test fun `should unregister client`() { clientService.registerClient(username, password) val result = clientService.unregisterClient(username) result shouldBe Success } @Test fun `should unregister client and delete single acl rule`() { clientService.registerClient(username, password, aclRule) val result = clientService.unregisterClient(username) result shouldBe Success } @Test fun `should unregister client and delete multiple acl rules`() { clientService.registerClient(username, password, aclRule, aclRule.copy(topic = "anotherTopic")) val result = clientService.unregisterClient(username) result shouldBe Success } @Test fun `adds acl rule`() { val result = clientService.addAclRules(aclRule) result shouldBe Success } @Test fun `adds multiple acl rules`() { val result = clientService.addAclRules(aclRule, aclRule.copy(topic = "anotherTopic")) result shouldBe Success } @Test fun `deletes all acl rules for a client on a topic`() { clientService.registerClient( username, password, aclRule.copy(action = SUB, allow = true), aclRule.copy(action = PUB, allow = false) ) val result = clientService.deleteAclRules(username, aclRule.topic) result shouldBe Success } @Test fun `gets client registration`() { val registerResult = clientService.registerClient(username, password) registerResult shouldBe Success val result = clientService.getClientRegistrations() result.shouldBeInstanceOf<ClientResult.Success<*>>() result as ClientResult.Success result.data.shouldHaveSingleItem() result.data.first().username shouldBeEqualTo username result.data.first().superuser.shouldBeTrue() } @Test fun `gets multiple client registrations`() { clientService.registerClient(username, password) clientService.registerClient("test2", password) val result = clientService.getClientRegistrations() result.shouldBeInstanceOf<ClientResult.Success<*>>() result as ClientResult.Success result.data.shouldHaveSize(2) } }
31.992958
116
0.712965
e735358ce337c7093b31d7291a1e03c36b966f7d
2,593
lua
Lua
rom/dotos/libraries/termio.lua
development-of-things-software/.OS
e7d2b4f6f42c5339080dd76d900dba01f96d3742
[ "MIT" ]
null
null
null
rom/dotos/libraries/termio.lua
development-of-things-software/.OS
e7d2b4f6f42c5339080dd76d900dba01f96d3742
[ "MIT" ]
null
null
null
rom/dotos/libraries/termio.lua
development-of-things-software/.OS
e7d2b4f6f42c5339080dd76d900dba01f96d3742
[ "MIT" ]
null
null
null
-- terminal I/O library -- local lib = {} local function getHandler() local term = os.getenv("TERM") or "generic" return require("termio."..term) end -------------- Cursor manipulation --------------- function lib.setCursor(x, y) if not getHandler().ttyOut() then return end io.write(string.format("\27[%d;%dH", y, x)) end function lib.getCursor() if not (getHandler().ttyIn() and getHandler().ttyOut()) then return 1, 1 end io.write("\27[6n") getHandler().setRaw(true) local resp = "" repeat local c = io.read(1) resp = resp .. c until c == "R" getHandler().setRaw(false) local y, x = resp:match("\27%[(%d+);(%d+)R") return tonumber(x), tonumber(y) end function lib.getTermSize() local cx, cy = lib.getCursor() lib.setCursor(9999, 9999) local w, h = lib.getCursor() lib.setCursor(cx, cy) return w, h end function lib.cursorVisible(vis) getHandler().cursorVisible(vis) end ----------------- Keyboard input ----------------- local patterns = {} local substitutions = { A = "up", B = "down", C = "right", D = "left", ["5"] = "pageUp", ["6"] = "pageDown" } -- string.unpack isn't a thing in 1.12.2's CC:T 1.89.2, so use this instead -- because this is all we need local function strunpack(str) local result = 0 for c in str:reverse():gmatch(".") do result = bit32.lshift(result, 8) + c:byte() end return result end local function getChar(char) local byte = strunpack(char) if byte + 96 > 255 then return utf8.char(byte) end return string.char(96 + byte) end function lib.readKey() getHandler().setRaw(true) local data = io.stdin:read(1) local key, flags flags = {} if data == "\27" then local intermediate = io.stdin:read(1) if intermediate == "[" then data = "" repeat local c = io.stdin:read(1) data = data .. c if c:match("[a-zA-Z]") then key = c end until c:match("[a-zA-Z]") flags = {} for pat, keys in pairs(patterns) do if data:match(pat) then flags = keys end end key = substitutions[key] or "unknown" else key = io.stdin:read(1) flags = {alt = true} end elseif data:byte() > 31 and data:byte() < 127 then key = data elseif data:byte() == (getHandler().keyBackspace or 127) then key = "backspace" elseif data:byte() == (getHandler().keyDelete or 8) then key = "delete" else key = getChar(data) flags = {ctrl = true} end getHandler().setRaw(false) return key, flags end return lib
19.643939
75
0.587736
cf793572dd6746a7908bee7faf82e944b55cb058
231
swift
Swift
Sources/TMDb/Models/VideoSize.swift
adamayoung/TMDb
35dc1330825cd79ac616d1c5b17ba157232864db
[ "Apache-2.0" ]
14
2020-05-08T00:21:10.000Z
2022-03-26T07:33:35.000Z
Sources/TMDb/Models/VideoSize.swift
adamayoung/TMDb
35dc1330825cd79ac616d1c5b17ba157232864db
[ "Apache-2.0" ]
24
2020-09-14T17:34:54.000Z
2022-03-03T21:59:59.000Z
Sources/TMDb/Models/VideoSize.swift
adamayoung/TMDb
35dc1330825cd79ac616d1c5b17ba157232864db
[ "Apache-2.0" ]
10
2020-05-08T00:21:11.000Z
2022-01-25T04:06:08.000Z
import Foundation /// Video size. public enum VideoSize: Int, Decodable, Equatable, Hashable { /// 360 case s360 = 360 /// 480 case s480 = 480 /// 720 case s720 = 720 /// 1080 case s1080 = 1080 }
14.4375
60
0.571429
aa0c9f10856fc0a78a8d3eb78941665b1c111410
27,030
lua
Lua
Core/Events.lua
shrugal/PersoLootRoll
330b6f322e3966402f469091511a554b4b4ae2e8
[ "MIT" ]
2
2018-06-06T17:38:35.000Z
2018-07-14T15:45:08.000Z
Core/Events.lua
shrugal/PersoLootRoll
330b6f322e3966402f469091511a554b4b4ae2e8
[ "MIT" ]
8
2018-07-08T12:48:29.000Z
2018-10-09T16:35:16.000Z
Core/Events.lua
shrugal/PersoLootRoll
330b6f322e3966402f469091511a554b4b4ae2e8
[ "MIT" ]
4
2018-05-23T09:49:01.000Z
2020-05-31T11:32:34.000Z
---@type string local Name = ... ---@type Addon local Addon = select(2, ...) local AceComm = LibStub("AceComm-3.0") ---@type L local L = LibStub("AceLocale-3.0"):GetLocale(Name) local Comm, Item, Locale, Session, Roll, Unit, Util = Addon.Comm, Addon.Item, Addon.Locale, Addon.Session, Addon.Roll, Addon.Unit, Addon.Util local Self = Addon -- Version check Self.VERSION_CHECK_DELAY = 5 -- Bids via whisper are ignored if we chatted after this many seconds BEFORE the roll started or AFTER the last one ended (max of the two) Self.CHAT_MARGIN_BEFORE = 300 Self.CHAT_MARGIN_AFTER = 30 -- Remember the last item link posted in group chat so we can track random rolls Self.lastPostedRoll = nil -- Remember the last time a version check happened Self.lastVersionCheck = nil -- Remember the last time we chatted with someone and what roll (if any) we chatted about, so we know when to respond Self.lastWhispered = {} Self.lastWhisperedRoll = {} -- Remember which messages to suppress Self.suppressBelow = nil -- Remember the last locked item slot Self.lastLocked = {} -- Remember the bag of the last looted item Self.lastLootedBag = nil -- Notice about disabled collection filters when starting legacy runs Self.collectionFilterNoticeShown = false -- (Un)Register function Self.RegisterEvents() -- Message patterns ---@type string Self.PATTERN_BONUS_LOOT = LOOT_ITEM_BONUS_ROLL:gsub("%%s", ".+") ---@type string Self.PATTERN_CRAFTING = CREATED_ITEM:gsub("%%s", ".+") ---@type string Self.PATTERN_CRAFTING_SELF = LOOT_ITEM_CREATED_SELF:gsub("%%s", ".+") ---@type string Self.PATTERN_ROLL_RESULT = RANDOM_ROLL_RESULT:gsub("%(", "%%("):gsub("%)", "%%)"):gsub("%%%d%$", "%%"):gsub("%%s", "(.+)"):gsub("%%d", "(%%d+)") -- Roster and zone Self:RegisterEvent("GROUP_JOINED", "GROUP_CHANGED") Self:RegisterEvent("GROUP_LEFT", "GROUP_CHANGED") Self:RegisterEvent("RAID_ROSTER_UPDATE", "GROUP_CHANGED") Self:RegisterEvent("PLAYER_ENTERING_WORLD", "ZONE_CHANGED") Self:RegisterEvent("ZONE_CHANGED_NEW_AREA", "ZONE_CHANGED") -- Chat Self:RegisterEvent("CHAT_MSG_SYSTEM") Self:RegisterEvent("CHAT_MSG_LOOT") Self:RegisterEvent("CHAT_MSG_PARTY", "CHAT_MSG_GROUP") Self:RegisterEvent("CHAT_MSG_PARTY_LEADER", "CHAT_MSG_GROUP") Self:RegisterEvent("CHAT_MSG_RAID", "CHAT_MSG_GROUP") Self:RegisterEvent("CHAT_MSG_RAID_LEADER", "CHAT_MSG_GROUP") Self:RegisterEvent("CHAT_MSG_RAID_WARNING", "CHAT_MSG_GROUP") Self:RegisterEvent("CHAT_MSG_INSTANCE_CHAT", "CHAT_MSG_GROUP") Self:RegisterEvent("CHAT_MSG_INSTANCE_CHAT_LEADER", "CHAT_MSG_GROUP") Self:RegisterEvent("CHAT_MSG_WHISPER", Self.CHAT_MSG_WHISPER) Self:RegisterEvent("CHAT_MSG_WHISPER_INFORM", Self.CHAT_MSG_WHISPER_INFORM) ChatFrame_AddMessageEventFilter("CHAT_MSG_WHISPER", Self.CHAT_MSG_WHISPER_FILTER) ChatFrame_AddMessageEventFilter("CHAT_MSG_WHISPER_INFORM", Self.CHAT_MSG_WHISPER_FILTER) -- Item Self:RegisterEvent("ITEM_PUSH") Self:RegisterEvent("ITEM_LOCKED") Self:RegisterEvent("ITEM_UNLOCKED") Self:RegisterEvent("BAG_UPDATE_DELAYED") end function Self.UnregisterEvents() -- Roster and zone Self:UnregisterEvent("GROUP_JOINED") Self:UnregisterEvent("GROUP_LEFT") Self:UnregisterEvent("RAID_ROSTER_UPDATE") Self:UnregisterEvent("PLAYER_ENTERING_WORLD") Self:UnregisterEvent("ZONE_CHANGED_NEW_AREA") -- Chat Self:UnregisterEvent("CHAT_MSG_SYSTEM") Self:UnregisterEvent("CHAT_MSG_LOOT") Self:UnregisterEvent("CHAT_MSG_PARTY") Self:UnregisterEvent("CHAT_MSG_PARTY_LEADER") Self:UnregisterEvent("CHAT_MSG_RAID") Self:UnregisterEvent("CHAT_MSG_RAID_LEADER") Self:UnregisterEvent("CHAT_MSG_RAID_WARNING") Self:UnregisterEvent("CHAT_MSG_INSTANCE_CHAT") Self:UnregisterEvent("CHAT_MSG_INSTANCE_CHAT_LEADER") Self:UnregisterEvent("CHAT_MSG_WHISPER") Self:UnregisterEvent("CHAT_MSG_WHISPER_INFORM") ChatFrame_RemoveMessageEventFilter("CHAT_MSG_WHISPER", Self.CHAT_MSG_WHISPER_FILTER) ChatFrame_RemoveMessageEventFilter("CHAT_MSG_WHISPER_INFORM", Self.CHAT_MSG_WHISPER_FILTER) -- Item Self:UnregisterEvent("ITEM_PUSH") Self:UnregisterEvent("ITEM_LOCKED") Self:UnregisterEvent("ITEM_UNLOCKED") Self:UnregisterEvent("BAG_UPDATE_DELAYED") end ------------------------------------------------------- -- Roster and zone -- ------------------------------------------------------- function Self.GROUP_CHANGED() Self:CheckState(true) end function Self.ZONE_CHANGED() Self:CheckState(true) local f = Self.db.profile.filter if not Self.collectionFilterNoticeShown and f.enabled and not (f.transmog or f.pets) and Self:IsTracking() and Util.IsLegacyRun() then Self.collectionFilterNoticeShown = true Self:Info(L["ERROR_COLLECTION_FILTERS_DISABLED"]) end end ------------------------------------------------------- -- Chat message -- ------------------------------------------------------- -- System ---@param msg string function Self.CHAT_MSG_SYSTEM(_, _, msg) if not Self:IsTracking() then return end -- Check if a player rolled do local unit, result, from, to = msg:match(Self.PATTERN_ROLL_RESULT) if unit and result and from and to then -- The roll result is the first return value in some locales if tonumber(unit) then unit, result, from, to = result, tonumber(unit), tonumber(from), tonumber(to) else result, from, to = tonumber(result), tonumber(from), tonumber(to) end Self:Debug("Events.RandomRoll", unit, result, from, to, msg) -- Rolls lower than 50 will screw with the result scaling if not (unit and result and from and to) or to < 50 then Self:Debug("Events.RandomRoll.Ignore") return end -- We don't get the full names for x-realm players if not UnitExists(unit) then for i=1,GetNumGroupMembers() do local unitGroup = GetRaidRosterInfo(i) if unitGroup and Util.Str.StartsWith(unitGroup, unit) then unit = unitGroup break end end if not UnitExists(unit) then Self:Debug("Events.RandomRoll.UnitNotFound", unit) return end end -- Find the roll local i, roll = to % 50 if i == 0 then roll = Self.lastPostedRoll else roll = Util.Tbl.FirstWhere(Self.rolls, "status", Roll.STATUS_RUNNING, "posted", i) end -- Get the correct bid and scaled roll result local bid = to < 100 and Roll.BID_GREED or Roll.BID_NEED result = Util.Num.Round(result * 100 / to) -- Register the unit's bid if roll and (roll.isOwner or Unit.IsSelf(unit)) and roll:UnitCanBid(unit, bid) then Self:Debug("Events.RandomRoll.Bid", bid, result, roll) roll:Bid(bid, unit, result) else Self:Debug("Events.RandomRoll.Reject", bid, result, roll and (roll.isOwner or Unit.IsSelf(unit)), roll and roll:UnitCanBid(unit, bid), roll) end return end end -- Check if a player left the group/raid for _,pattern in pairs(Comm.PATTERNS_LEFT) do local unit = msg:match(pattern) if unit then -- Clear rolls for id, roll in pairs(Self.rolls) do if roll.owner == unit or roll.item.owner == unit then roll:Clear() elseif roll:CanBeWon(true) then -- Remove from eligible list if roll.item.eligible then roll.item.eligible[unit] = nil end roll.bids[unit] = nil if roll:ShouldEnd() then roll:End() end end end -- Clear version and disabled Self:SetVersion(unit, nil) return end end end -- Loot ---@param msg string ---@param sender string function Self.CHAT_MSG_LOOT(_, _, msg, _, _, _, sender) local unit = Unit(sender) if not Self:IsTracking() or not Unit.InGroup(unit) or not Unit.IsSelf(unit) and Self:UnitIsTracking(unit, true) then return end -- Check for bonus roll or crafting if msg:match(Self.PATTERN_BONUS_LOOT) or msg:match(Self.PATTERN_CRAFTING) or msg:match(Self.PATTERN_CRAFTING_SELF) then return end local item = Item.GetLink(msg) if Item.ShouldBeChecked(item, unit) then Self:Debug("Events.Loot", item, unit, Unit.IsSelf(unit), msg) item = Item.FromLink(item, unit) if item.isOwner then item:SetPosition(Self.lastLootedBag, 0) local owner = Session.GetMasterlooter() or unit local isOwner = Unit.IsSelf(owner) item:OnFullyLoaded(function () if isOwner and item:ShouldBeRolledFor() then Self:Debug("Events.Loot.Start", owner) Roll.Add(item, owner):Start() elseif not Self.db.profile.dontShare and item:GetFullInfo().isTradable then Self:Debug("Events.Loot.Status", owner, isOwner) local roll = Roll.Add(item, owner) if isOwner then roll:Schedule() end roll:SendStatus(true) else Self:Debug("Events.Loot.Cancel", Self.db.profile.dontShare, owner, isOwner, unit, item.isOwner, item:HasSufficientQuality(), item:GetBasicInfo().isEquippable, item:GetFullInfo().isTradable, item:GetNumEligible(true)) Roll.Add(item, unit):Cancel() end end) elseif not Roll.Find(nil, nil, item, nil, unit) then Self:Debug("Events.Loot.Schedule") Roll.Add(item, unit):Schedule() else Self:Debug("Events.Loot.Duplicate") end end end -- Group/Raid/Instance ---@param msg string ---@param sender string function Self.CHAT_MSG_GROUP(_, _, msg, sender) local unit = Unit(sender) if not Self:IsTracking() then return end local link = Item.GetLink(msg) if link then link = select(2, GetItemInfo(link)) or link Self.lastPostedRoll = nil local roll = Roll.Find(nil, unit, link, nil, nil, Roll.STATUS_RUNNING) or Roll.Find(nil, unit, link) if roll then -- Remember the last roll posted to chat Self.lastPostedRoll = roll if not roll:GetOwnerAddon() and roll:CanBeWon(true) then -- Roll for the item in chat if not roll.posted and Self.db.profile.messages.group.roll and roll.bid and Util.In(floor(roll.bid), Roll.BID_NEED, Roll.BID_GREED) then RandomRoll("1", floor(roll.bid) == Roll.BID_GREED and "50" or "100") end -- Remember that the roll has been posted roll.posted = roll.posted or true end end elseif Self.db.profile.messages.group.concise then local roll = Roll.FindWhere("isOwner", true, "item.isOwner", true, "status", Roll.STATUS_RUNNING, "posted", 0) if roll and roll:UnitCanBid(unit, Roll.BID_NEED) then local L, D = Locale.GetCommLocale(unit), Locale.GetCommLocale() msg = strtrim(msg) msg = Util.In(msg, "+", "-") and msg or msg:gsub("[%c%p]+", ""):gsub("%s%s+", " ") local msgLc = msg:lower() for i,bid in Util.Each("NEED", "PASS") do local patterns = Util(","):Join(_G[bid], bid == "NEED" and YES .. ",+" or NO .. ",-", L["MSG_" .. bid], L ~= D and D["MSG_" .. bid] or ""):LcLang()() for p in patterns:gmatch("[^,]+") do if msg:match("^" .. p .. "$") or msgLc:match("^" .. p .. "$") then roll:Bid(Roll["BID_" .. bid], unit) return end end end end end end -- Whisper ---@param msg string ---@param sender string ---@param lineId integer function Self.CHAT_MSG_WHISPER(_, msg, sender, _, _, _, _, _, _, _, _, lineId) local unit = Unit(sender) if not Self:IsTracking() or not Unit.InGroup(unit) then return end -- Log the conversation for i,roll in pairs(Self.rolls) do if roll:IsRecent() and unit == roll:GetActionTarget() then Self:Debug("Events.Whisper", roll.id, unit, lineId) roll:AddChat(msg, unit) end end -- Don't act on whispers from other addon users if Self:UnitIsTracking(unit) then return end local answer, suppress local lastEnded, firstStarted, running, recent, roll = 0 local link = Item.GetLink(msg) -- Check if we should start a roll for the unit if link and Session.IsMasterlooter() and Addon.db.profile.masterloot.rules.startWhisper then local req = msg:gsub(Item.PATTERN_LINK, ""):trim():gsub("[%c%p]+", ""):gsub("%s%s+", " ") local reqLc = req:lower() local patterns = Util.Str.Join(",", "roll", Locale.GetCommLine("MSG_ROLL", unit), Locale.GetCommLine("MSG_ROLL")) for p in patterns:gmatch("[^,]+") do if req:match(p) or reqLc:match(p) then roll = Roll.Find(nil, nil, link, nil, unit) if roll and roll.status < Roll.STATUS_DONE then ---@type function local action = Util.Select(roll.status, Roll.STATUS_CANCELED, Roll.Restart, Roll.STATUS_PENDING, Roll.Start) roll:Adopt(action ~= nil) if action then action(roll) end else roll = Roll.Add(Item.FromLink(link, unit, nil, nil, true)):Schedule() end answer = Comm.GetChatLine("MSG_ROLL_ANSWER_STARTED", unit) break end end end -- Check if the unit wants to bid on one of our rolls if answer == nil then if link then roll = Roll.Find(nil, true, link) else -- Find running or recent rolls and determine firstStarted and lastEnded for i,roll in pairs(Self.rolls) do if roll:CanBeGivenTo(unit) and roll:IsRecent(Self.CHAT_MARGIN_AFTER) then firstStarted = min(firstStarted or roll.started, roll.started) if roll.status == Roll.STATUS_RUNNING then if not running then running = roll else running = true end else if not recent then recent = roll else recent = true end end end if roll.status == Roll.STATUS_DONE and (roll.owner == unit or roll.isOwner and (roll.winner == unit or roll.item:GetEligible(unit))) then lastEnded = max(lastEnded, roll.ended + Self.CHAT_MARGIN_AFTER) end end roll = running or recent end local ignore = -- No roll found not roll -- We talked recently or not link and Self.lastWhispered[unit] and Self.lastWhispered[unit] > min(firstStarted, max(lastEnded, firstStarted - Self.CHAT_MARGIN_BEFORE)) -- We talked about the roll already or roll ~= true and Self.lastWhisperedRoll[unit] == roll.id -- We currently want an item from the sender or Util.Tbl.FindFn(Addon.rolls, function (roll) return roll.owner == unit and roll.bid and roll.bid ~= Roll.BID_PASS and roll.status ~= Roll.STATUS_CANCELED and not roll.traded end) -- Check if we should act on the whisper if ignore then if roll and roll ~= true and Self.lastWhisperedRoll[unit] ~= roll.id and roll:CanBeAwardedTo(unit) and not roll.bids[unit] then Self:Info(L["ROLL_IGNORING_BID"], Comm.GetPlayerLink(unit), roll.item.link, Comm.GetBidLink(roll, unit, Roll.BID_NEED), Comm.GetBidLink(roll, unit, Roll.BID_GREED)) end Self.lastWhispered[unit] = time() else -- Ask for the item link if there is more than one roll right now if roll == true then answer = Comm.GetChatLine("MSG_ROLL_ANSWER_AMBIGUOUS", unit) elseif roll.isOwner then -- Unit has won the item if roll.winner == unit and not roll.traded then answer = roll.item.isOwner and Comm.GetChatLine("MSG_ROLL_ANSWER_YES", unit) or Comm.GetChatLine("MSG_ROLL_ANSWER_YES_MASTERLOOT", unit, Unit.FullName(roll.item.owner)) -- The unit can bid elseif roll:UnitCanBid(unit, Roll.BID_NEED) then roll:Bid(Roll.BID_NEED, unit) -- Answer only if his bid didn't end the roll answer = roll:CanBeAwarded(true) and Comm.GetChatLine("MSG_ROLL_ANSWER_BID", unit, roll.item.link) or false -- The item is not tradable elseif not roll.item.isTradable then answer = Comm.GetChatLine("MSG_ROLL_ANSWER_NOT_TRADABLE", unit) -- I need it for myself elseif roll.status == Roll.STATUS_CANCELED or roll.isWinner then answer = Comm.GetChatLine("MSG_ROLL_ANSWER_NO_SELF", unit) -- Someone else won or got it elseif roll.winner and roll.winner ~= unit or roll.traded and roll.traded ~= unit then answer = Comm.GetChatLine("MSG_ROLL_ANSWER_NO_OTHER", unit) -- Unit isn't eligible elseif roll.item:GetEligible(unit) == nil then answer = Comm.GetChatLine("MSG_ROLL_ANSWER_NOT_ELIGIBLE", unit) -- Probably too late else answer = Comm.GetChatLine("MSG_ROLL_ANSWER_NO", unit) end Self.lastWhisperedRoll[unit] = roll.id end end end -- Suppress the message and/or send an answer if answer ~= nil then suppress = answer ~= nil and Self.db.profile.messages.whisper.suppress answer = Self.db.profile.messages.whisper.answer and answer -- Suppress the message and print an info message instead if suppress then Self:Info(L["ROLL_WHISPER_SUPPRESSED"], Comm.GetPlayerLink(unit), roll.item.link, Comm.GetTooltipLink(msg, L["MESSAGE"], L["MESSAGE"]), answer and Comm.GetTooltipLink(answer, L["ANSWER"], L["ANSWER"]) or L["ANSWER"] .. ": -" ) Self.suppressBelow = lineId + (answer and 1 or 0) end -- Post the answer if answer then Comm.Chat(answer, unit) end end end ---@param msg string ---@param receiver string ---@param lineId integer function Self.CHAT_MSG_WHISPER_INFORM(_, msg, receiver, _, _, _, _, _, _, _, _, lineId) local unit = Unit(receiver) if not Self:IsTracking() or not Unit.InGroup(unit) then return end -- Log the conversation for i,roll in pairs(Self.rolls) do if roll:IsRecent() and unit == roll:GetActionTarget() then Self:Debug("Events.WhisperInform", roll.id, unit, lineId) roll:AddChat(msg) end end -- Remember lastWhispered if msg ~= Comm.lastWhispered then Self.lastWhispered[Unit.Name(receiver)] = time() end end ---@param lineId integer function Self.CHAT_MSG_WHISPER_FILTER(_, _, _, _, _, _, _, _, _, _, _, _, lineId) return lineId <= (Self.suppressBelow or -1) end ------------------------------------------------------- -- Item -- ------------------------------------------------------- ---@param bagId integer function Self.ITEM_PUSH(_, _, bagId) Self.lastLootedBag = bagId == 0 and 0 or (bagId - CharacterBag0Slot:GetID() + 1) end function Self.ITEM_LOCKED(_, _, bagOrEquip, slot) tinsert(Self.lastLocked, {bagOrEquip, slot}) end function Self.ITEM_UNLOCKED(_, _, bagOrEquip, slot) local pos = {bagOrEquip, slot} if #Self.lastLocked == 1 and not Util.Tbl.Equals(pos, Self.lastLocked[1]) then -- The item has been moved local from, to = Self.lastLocked[1], pos for i,roll in pairs(Self.rolls) do if roll.item.isOwner and not roll.traded then if Util.Tbl.Equals(from, roll.item.position) then roll.item:SetPosition(to) break end end end elseif #Self.lastLocked == 2 then -- The item has switched places with another local pos1, pos2 = Self.lastLocked[1], Self.lastLocked[2] local item1, item2 for i,roll in pairs(Self.rolls) do if not item1 and Util.Tbl.Equals(pos1, roll.item.position) then item1 = roll.item elseif not item2 and Util.Tbl.Equals(pos2, roll.item.position) then item2 = roll.item end if item1 and item2 then break end end if item1 then item1:SetPosition(pos2) end if item2 then item2:SetPosition(pos1) end end wipe(Self.lastLocked) end function Self.BAG_UPDATE_DELAYED() for i, entry in pairs(Item.queue) do Self:CancelTimer(entry.timer) entry.fn(unpack(entry.args)) end wipe(Item.queue) end ------------------------------------------------------- -- Addon message -- ------------------------------------------------------- -- Check function Self.EVENT_CHECK(_, data, channel, sender, unit) if not Self.lastVersionCheck or Self.lastVersionCheck + Self.VERSION_CHECK_DELAY < GetTime() then Self.lastVersionCheck = GetTime() if Self.timers.versionCheck then Self:CancelTimer(Self.timers.versionCheck) Self.timers.versionCheck = nil end local target = channel == Comm.TYPE_WHISPER and sender or channel -- Send version Comm.SendData(Comm.EVENT_VERSION, Self.VERSION, target) -- Send disabled state if not Self.db.profile.enabled then Comm.Send(Comm.EVENT_DISABLE, target) end end end Comm.ListenData(Comm.EVENT_CHECK, Self.EVENT_CHECK, true) -- Version function Self.EVENT_VERSION(_, version, channel, sender, unit) Self:SetVersion(unit, version) end Comm.ListenData(Comm.EVENT_VERSION, Self.EVENT_VERSION) -- Enable function Self.EVENT_ENABLE(_, _, _, _, unit) Self.disabled[unit] = nil end Comm.Listen(Comm.EVENT_ENABLE, Self.EVENT_ENABLE, true) -- Disable function Self.EVENT_DISABLE(_, _, _, _, unit) Self.disabled[unit] = true end Comm.Listen(Comm.EVENT_DISABLE, Self.EVENT_DISABLE, true) -- Sync function Self.EVENT_SYNC(_, msg, channel, sender, unit) -- Reset all owner ids and bids for the unit's rolls and items, because he/she doesn't know them anymore for id, roll in pairs(Self.rolls) do if roll.owner == unit then roll.ownerId = nil if roll.status == Roll.STATUS_RUNNING then roll:Restart(roll.started) elseif roll.status < Roll.STATUS_DONE then roll.bid = nil end end if roll.item.owner == unit then roll.itemOwnerId = nil end end if Self:IsTracking() then -- Send rolls for items that we own for _,roll in pairs(Self.rolls) do if roll.item.isOwner and not roll.traded and roll:UnitIsInvolved(unit) then roll:SendStatus(true, unit, roll.isOwner) end end -- As masterlooter we send another update a bit later to inform them about bids and votes if Session.IsMasterlooter() then Self:ScheduleTimer(function () for _,roll in pairs(Self.rolls) do if roll.isOwner and not roll.item.isOwner and not roll.traded and roll:UnitIsInvolved(unit) then roll:SendStatus(nil, unit, true) end end end, Roll.DELAY) end end end Comm.Listen(Comm.EVENT_SYNC, Self.EVENT_SYNC) -- Roll status function Self.EVENT_ROLL_STATUS(_, data, channel, sender, unit) if not Self:IsTracking() then return end data.owner = Unit.Name(data.owner) data.item.owner = Unit.Name(data.item.owner) data.winner = Unit.Name(data.winner) data.traded = data.traded and Unit.Name(data.traded) Roll.Update(data, unit) end Comm.ListenData(Comm.EVENT_ROLL_STATUS, Self.EVENT_ROLL_STATUS) -- Bids function Self.EVENT_BID(_, data, channel, sender, unit) if not Self:IsTracking() then return end local isImport = data.fromUnit ~= nil local owner = isImport and unit or Unit.Name("player") local fromUnit = data.fromUnit or unit local roll = Roll.Find(data.ownerId, owner) if roll then roll:Bid(data.bid, fromUnit, isImport and data.roll, isImport) end end Comm.ListenData(Comm.EVENT_BID, Self.EVENT_BID) -- Bid whisper function Self.EVENT_BID_WHISPER(_, item) if not Self:IsTracking() then return end local roll = Roll.Find(nil, item.owner, item.link) if roll then roll.whispers = roll.whispers + 1 end end Comm.ListenData(Comm.EVENT_BID_WHISPER, Self.EVENT_BID_WHISPER) -- Votes function Self.EVENT_VOTE(_, data, channel, sender, unit) if not Self:IsTracking() then return end local owner = data.fromUnit and unit or nil local fromUnit = data.fromUnit or unit local roll = Roll.Find(data.ownerId, owner) if roll then roll:Vote(data.vote, fromUnit, owner ~= nil) end end Comm.ListenData(Comm.EVENT_VOTE, Self.EVENT_VOTE) -- Declaring interest function Self.EVENT_INTEREST(_, data, channel, sender, unit) if not Self:IsTracking() then return end local roll = Roll.Find(data.ownerId) if roll then roll.item:SetEligible(unit) end end Comm.ListenData(Comm.EVENT_INTEREST, Self.EVENT_INTEREST) -- XRealm function Self.EVENT_XREALM(_, data, channel, sender, unit) local receiver, event, msg = data:match("^([^/]+)/([^/]+)/(.*)") if Unit.IsSelf(Unit(receiver)) then AceComm.callbacks:Fire(Comm.PREFIX .. event, msg, Comm.TYPE_WHISPER, sender) end end Comm.Listen(Comm.EVENT_XREALM, Self.EVENT_XREALM)
37.857143
236
0.603145
9f44766c7a0d6e98b93be61f7a56b02c5491df60
206
sql
SQL
src/functions/auth/logout.sql
postgres-ci/core
a45eab1ad37e96eba05b5eed24cba9cc71926647
[ "MIT" ]
9
2016-05-06T06:12:51.000Z
2020-10-02T14:06:25.000Z
src/functions/auth/logout.sql
postgres-ci/core
a45eab1ad37e96eba05b5eed24cba9cc71926647
[ "MIT" ]
null
null
null
src/functions/auth/logout.sql
postgres-ci/core
a45eab1ad37e96eba05b5eed24cba9cc71926647
[ "MIT" ]
null
null
null
create or replace function auth.logout(_session_id text) returns void as $$ begin DELETE FROM postgres_ci.sessions WHERE session_id = _session_id; end; $$ language plpgsql security definer;
41.2
75
0.747573
1f8326c61ca838a7326b5b2ae2a048b9c7c6459b
9,007
html
HTML
index.html
WorldWideWebb/mitchalyzer
be3eb99bfd33e000c623e11c76739858983ef533
[ "MIT" ]
null
null
null
index.html
WorldWideWebb/mitchalyzer
be3eb99bfd33e000c623e11c76739858983ef533
[ "MIT" ]
null
null
null
index.html
WorldWideWebb/mitchalyzer
be3eb99bfd33e000c623e11c76739858983ef533
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>The Mitchalyzer</title> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@700&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Crimson+Text:wght@400;600&display=swap" rel="stylesheet"> <style type="text/css"> html { background: url(bg.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } body { padding: 4rem; } h1, h4, p, .selections { text-align: center; max-width: 60rem; } h1 { color: #fff; font-family: 'Montserrat', sans-serif; font-size: 3.5rem; margin: 1rem auto; text-shadow: 0 1px 1px rgba(0,0,0,.8); text-transform: uppercase; } h4, p, .selections { font-family: 'Crimson Text', serif; margin: 2rem auto; } h4 { color: #333; font-size: 1.25rem; text-shadow: 0 1px 1px rgba(255,255,255,.75); line-height: 1.4; } p { color: #fff; font-size: 2.5rem; font-weight: 600; line-height: 1.15; margin-top: 5rem; text-shadow: 0 1px 1px rgba(0,0,0,.8); } .selections, .selections a { color: #fff; font-weight: 600; font-size: 1.25rem; text-shadow: 0 1px 1px rgba(0,0,0,.8); text-decoration: none; padding: 0 1rem; outline: none !important; } @media (max-width: 900px) { body { padding: 1rem; } h1 { font-size: 2rem; margin-top: 0; } h4, .selections, .selections a { font-size: 1rem; } p { margin-top: 3rem; font-size: 1.75rem; } } </style> </head> <body> <h1>The Mitchalyzer</h1> <h4>Want to posit deep philosophical questions as the intellectual elite do? Need the perfect insult to dish out on social media? Say no more. The Mitchalyzer is an AI of profound technological advancement. It has analyzed and processed the writings of the world's greatest thinker and can generate new thoughts of its own - for the benefit of all mankind.</h4> <div class="selections"> <a href="#" title="Generate a deep contemplation" id="question">Deep contemplation</a> | <a href="#" title="Generate an unassailable statement of fact" id="statement">Unassailable statement of fact</a> | <a href="#" title="Generate a mind shattering epithet" id="insult">Mind shattering epithet</a> | <a href="#" title="Generate an injustice" id="injustice">Injustice</a> </div> <p id="quote"></p> </body> <script> let things = [ ['board member', 'board members'], ['safety director', 'safety directors'], ['cowardly act', 'cowardly acts'], ['instructor', 'instructors'], ['delusional hyperinflation', 'delusional hyperinflations'], ['grievance hustling perpetually offended by nothing authoritarian psychopath', 'grievance hustling perpetually offended by nothing authoritarian psychopaths'], ['bogus assumption', 'bogus assumptions'], ['most-prolific instructor in the CSS', 'most prolific instructors in the CSS'], ['appropriate flight regime', 'appropriate flight regimes'], ['mindset of the local pilot population', 'mindsets of the local pilot population'], ['student pilot outlanding', 'student pilot outlandings'], ['comptroller at the state budget level', 'comptrollers at the state budget level'], ['modern germaphobic misanthropic political climate', 'modern germaphobic misanthropic political climates'], ['authoritarian fuck space', 'authoritarian fuck spaces'], ['bully pulpit', 'bully pulpits'], ['vested interest', 'vested interests'], ['relevant dialog', 'relevant dialog'], ['competently run membership organization', 'competently run membership organizations'], ['conflict of interest', 'conflicts of interest'], ['billionaire real estate and hotel magnate', 'billionaire real estate and hotel magnates'], ['obvious double standard', 'obvious double standards'], ['safety syllabus for new pilots', 'safety syllabi for new pilots'], ['weenie running the forum', 'weenies running the forum'], ['smarmy insulting prick behavior', 'smarmy insulting prick behaviors'], ['misinformed personal anecdote', 'misinformed personal anecdotes'] ], nameyNouns = [ ['dictator', 'dictators'], ['coward', 'cowards'], ['asshole', 'assholes'], ['fuckface', 'fuckfaces'], ['fucktard', 'fucktards'], ['liar', 'liars'], ['homo', 'homos'], ['stalker', 'stalkers'], ['sociopath', 'sociopaths'], ['unaccountable coward', 'unaccountable cowards'], ['chicken shit', 'chicken shits'], ['sole arbiter', 'sole arbiters'], ['weenie', 'weenies'], ['carpet shitting fucktard', 'carpet shitting fucktards'], ['authoritarian psychopath', 'authoritarian psychopaths'] ], injusticeVerbPhrases = [ 'demonized', 'lied about' ], adjectives = [ 'silly', 'colorful', 'creepy', 'arrogant', 'simple', 'stupid', 'hypocritical', 'disrespectful', 'low resolution', 'imprecise', 'cowardly', 'smarmy', 'insulting', 'paranoid' ], phrasesPositive = [ 'with years of experience running a club', 'perfect like Jesus', 'from a position of knowledge or wisdom gained from 30 fucking years in this business', 'actually understanding the bigger picture here' ], phrasesNegative = [ 'incapable of processing negative critical review', 'with zero experience', 'about nothing but ass licking and whining', 'denying your own disrespectful bullshit', 'until you started acting like a fucking child', 'unless I allow you to blather without critical review', 'pretending superior knowledge', 'offering you a forum to indulge yourself' ], sentenceInsults = [ 'Fuck you, chicken shit.', 'See you around, fuckface.', 'Feeling ronery?', 'Trying to find value in life devoid of meaning?', 'Whine about that all you want.' ]; let itemWithArticle = function (item) { return ((item[0] == 'a') || (item[0] == 'e') || (item[0] == 'i') || (item[0] == 'o') || (item[0] == 'u')) ? ('an ' + item) : ('a ' + item); }; let randomIndex = function(arrayOfThings) { return Math.floor(Math.random() * arrayOfThings.length); }; let generateComparison = function () { let quote = 'The big question ', indexAdj = randomIndex(adjectives), indexThing = randomIndex(things), indexThing2 = randomIndex(things), indexInjVerb = randomIndex(injusticeVerbPhrases), indexNameyNoun = randomIndex(nameyNouns); quote += '(' + things[indexThing][1] + '): ' + adjectives[indexAdj] + ' ' + things[indexThing2][1] + ', or ' + injusticeVerbPhrases[indexInjVerb] + ' ' + nameyNouns[indexNameyNoun][1] + '?'; return quote; }; document.getElementById('question').onclick = function(e){ e.preventDefault(); document.getElementById('quote').innerHTML= generateComparison(); return false; } let generateStatement = function () { let quote = 'A ', indexAdj = randomIndex(adjectives), indexThing = randomIndex(things), indexNameyNoun = randomIndex(nameyNouns); quote += things[indexThing][0] + ' is nothing but ' + itemWithArticle(adjectives[indexAdj]) + ' ' + nameyNouns[indexNameyNoun][0] + '.'; return quote; }; document.getElementById('statement').onclick = function(e){ e.preventDefault(); document.getElementById('quote').innerHTML= generateStatement(); return false; } let generateInsult = function () { let quote = 'You are ', indexAdj = randomIndex(adjectives), indexAdj2 = randomIndex(adjectives), indexPhrase = randomIndex(phrasesNegative), indexNameyNoun = randomIndex(nameyNouns), indexSentence = randomIndex(sentenceInsults); quote += itemWithArticle(adjectives[indexAdj]) + ' ' + adjectives[indexAdj2] + ' ' + nameyNouns[indexNameyNoun][0] + ', ' + phrasesNegative[indexPhrase] + '. ' + sentenceInsults[indexSentence]; return quote; }; document.getElementById('insult').onclick = function(e){ e.preventDefault(); document.getElementById('quote').innerHTML= generateInsult(); return false; } let generateInjustice = function () { let quote = 'I speak ', indexPhrasePos = randomIndex(phrasesPositive), indexInjusticeVerb = randomIndex(injusticeVerbPhrases), indexAdj = randomIndex(adjectives), indexNameyNoun = randomIndex(nameyNouns), indexPhrase = randomIndex(phrasesNegative); quote += phrasesPositive[indexPhrasePos] + ', but have been ' + injusticeVerbPhrases[indexInjusticeVerb] + ' by a bunch of ' + adjectives[indexAdj] + ' ' + nameyNouns[indexNameyNoun][1] + ' ' + phrasesNegative[indexPhrase] + '.'; return quote; }; document.getElementById('injustice').onclick = function(e){ e.preventDefault(); document.getElementById('quote').innerHTML= generateInjustice(); return false; } </script> </html>
34.117424
362
0.678916
f5300f86d7095a9f101af5139ec1627bc4e8e289
402
kt
Kotlin
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/notifications/notificationsservice/WykopNotificationsJobView.kt
mdczaplicki/WykopMobilny
687a9f42af9d17bd8a3227b882fef6232b4d174a
[ "MIT" ]
null
null
null
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/notifications/notificationsservice/WykopNotificationsJobView.kt
mdczaplicki/WykopMobilny
687a9f42af9d17bd8a3227b882fef6232b4d174a
[ "MIT" ]
null
null
null
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/notifications/notificationsservice/WykopNotificationsJobView.kt
mdczaplicki/WykopMobilny
687a9f42af9d17bd8a3227b882fef6232b4d174a
[ "MIT" ]
null
null
null
package io.github.feelfreelinux.wykopmobilny.ui.modules.notifications.notificationsservice import io.github.feelfreelinux.wykopmobilny.base.BaseView import io.github.feelfreelinux.wykopmobilny.models.dataclass.Notification interface WykopNotificationsJobView : BaseView { fun showNotification(notification : Notification) fun showNotificationsCount(count : Int) fun cancelNotification() }
40.2
90
0.840796
3a05049ed325666deba128ff843ce3b397a0a8bf
5,515
swift
Swift
AudioKit/Common/Nodes/Playback/Player/AKAudioPlayer.swift
lxlxlo/audiokit-devel
e0b46ed5f8299620afdbe49b1482a511baf7c792
[ "MIT" ]
2
2018-07-18T23:32:22.000Z
2018-11-14T16:43:50.000Z
AudioKit/Common/Nodes/Playback/Player/AKAudioPlayer.swift
lxlxlo/audiokit-devel
e0b46ed5f8299620afdbe49b1482a511baf7c792
[ "MIT" ]
null
null
null
AudioKit/Common/Nodes/Playback/Player/AKAudioPlayer.swift
lxlxlo/audiokit-devel
e0b46ed5f8299620afdbe49b1482a511baf7c792
[ "MIT" ]
null
null
null
// // AKAudioPlayer.swift // AudioKit // // Created by Aurelius Prochazka, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // import Foundation import AVFoundation /// Simple audio playback class public class AKAudioPlayer: AKNode, AKToggleable { private var audioFileBuffer: AVAudioPCMBuffer private var internalPlayer: AVAudioPlayerNode private var audioFile: AVAudioFile private var internalFile: String private var sampleRate: Double = 1.0 private var totalFrameCount: Int64 private var initialFrameCount: Int64 = -1 private var skippedToTime: Double /// Boolean indicating whether or not to loop the playback public var looping = false private var paused = false /// Output Volume (Default 1) public var volume: Double = 1.0 { didSet { if volume < 0 { volume = 0 } internalPlayer.volume = Float(volume) } } /// Pan (Default Center = 0) public var pan: Double = 0.0 { didSet { if pan < -1 { pan = -1 } if pan > 1 { pan = 1 } internalPlayer.pan = Float(pan) } } /// Whether or not the audio player is currently playing public var isStarted: Bool { return internalPlayer.playing } /// Initialize the player /// /// - parameter file: Path to the audio file /// public init(_ file: String) { internalFile = file let url = NSURL.fileURLWithPath(file, isDirectory: false) audioFile = try! AVAudioFile(forReading: url) let audioFormat = audioFile.processingFormat let audioFrameCount = UInt32(audioFile.length) audioFileBuffer = AVAudioPCMBuffer(PCMFormat: audioFormat, frameCapacity: audioFrameCount) try! audioFile.readIntoBuffer(audioFileBuffer) // added for currentTime calculation later on sampleRate = audioFile.fileFormat.sampleRate totalFrameCount = Int64(audioFrameCount) skippedToTime = 0 internalPlayer = AVAudioPlayerNode() super.init() AudioKit.engine.attachNode(internalPlayer) let mixer = AVAudioMixerNode() AudioKit.engine.attachNode(mixer) AudioKit.engine.connect(internalPlayer, to: mixer, format: audioFormat) self.avAudioNode = mixer internalPlayer.scheduleBuffer( audioFileBuffer, atTime: nil, options: .Loops, completionHandler: nil) internalPlayer.volume = 1.0 } /// Reload the file from the disk public func reloadFile() { let url = NSURL.fileURLWithPath(internalFile, isDirectory: false) let audioFile = try! AVAudioFile(forReading: url) let audioFormat = audioFile.processingFormat let audioFrameCount = UInt32(audioFile.length) audioFileBuffer = AVAudioPCMBuffer(PCMFormat: audioFormat, frameCapacity: audioFrameCount) try! audioFile.readIntoBuffer(audioFileBuffer) } /// Start playback public func start() { if !internalPlayer.playing && !paused { var options = AVAudioPlayerNodeBufferOptions.Interrupts if looping { options = .Loops } internalPlayer.scheduleBuffer( audioFileBuffer, atTime: nil, options: options, completionHandler: nil) } internalPlayer.play() // get the initialFrameCount for currentTime as it's relative to the audio engine's time. if initialFrameCount == -1 { resetFrameCount() } } /// Pause playback public func pause() { paused = true internalPlayer.pause() } /// Stop playback public func stop() { internalPlayer.stop() resetFrameCount() } func resetFrameCount() { if let t = internalPlayer.lastRenderTime { initialFrameCount = t.sampleTime } } /// Current playback time (in seconds) public var currentTime : Double { if internalPlayer.playing { if let nodeTime = internalPlayer.lastRenderTime, let playerTime = internalPlayer.playerTimeForNodeTime(nodeTime) { return Double( Double( playerTime.sampleTime ) / playerTime.sampleRate ) + skippedToTime } } return skippedToTime } /// Play the file back from a certain time (non-looping) /// /// - parameter time: Time into the file at which to start playing back /// public func playFrom(time: Double) { skippedToTime = time let startingFrame = Int64(sampleRate * time) let frameCount = UInt32(totalFrameCount - startingFrame) internalPlayer.prepareWithFrameCount(frameCount) internalPlayer.scheduleSegment( audioFile, startingFrame: startingFrame, frameCount: frameCount, atTime: nil, completionHandler: nil) internalPlayer.play() } /// Replace the current audio file with a new audio file public func replaceFile( newFile : String ) { internalFile = newFile reloadFile() } }
30.638889
104
0.595286
053cf8924b6d12f4d51f6dccd3669d3db1a6480b
220
rb
Ruby
db/migrate/20091102171023_add_response_reset_date_to_committees.rb
joshlin/expo2
21ee9b12cbe83183a75eb935fdc23d6b649a9186
[ "BSD-3-Clause" ]
1
2016-08-31T19:24:06.000Z
2016-08-31T19:24:06.000Z
db/migrate/20091102171023_add_response_reset_date_to_committees.rb
joshlin/expo2
21ee9b12cbe83183a75eb935fdc23d6b649a9186
[ "BSD-3-Clause" ]
17
2020-08-12T14:52:53.000Z
2022-03-30T22:23:42.000Z
db/migrate/20091102171023_add_response_reset_date_to_committees.rb
uwexpd/expo2
3678f96ba9ea999becb8b223ebb5a966bb587cb1
[ "BSD-3-Clause" ]
1
2019-10-02T11:12:58.000Z
2019-10-02T11:12:58.000Z
class AddResponseResetDateToCommittees < ActiveRecord::Migration def self.up add_column :committees, :response_reset_date, :date end def self.down remove_column :committees, :response_reset_date end end
22
64
0.781818
cca8d0f472da89532ea6aea41ef425d6e796886d
719
kt
Kotlin
kotlinui/src/test/java/kotlinx/kotlinui/Modifiers/_AllowsHitTestingModifierTest.kt
bclnet/KotlinUI
8ea61bd04ce4a0b3dd440c36d4b82a5ccf5ec3f2
[ "MIT" ]
null
null
null
kotlinui/src/test/java/kotlinx/kotlinui/Modifiers/_AllowsHitTestingModifierTest.kt
bclnet/KotlinUI
8ea61bd04ce4a0b3dd440c36d4b82a5ccf5ec3f2
[ "MIT" ]
null
null
null
kotlinui/src/test/java/kotlinx/kotlinui/Modifiers/_AllowsHitTestingModifierTest.kt
bclnet/KotlinUI
8ea61bd04ce4a0b3dd440c36d4b82a5ccf5ec3f2
[ "MIT" ]
null
null
null
package kotlinx.kotlinui import kotlinx.serialization.json.Json import org.junit.Assert import org.junit.Test import org.junit.Assert.* class _AllowsHitTestingModifierTest { @Test fun serialize() { val json = Json { prettyPrint = true } // _AllowsHitTestingModifier val orig_ahtm = _AllowsHitTestingModifier(true) val data_ahtm = json.encodeToString(_AllowsHitTestingModifier.Serializer, orig_ahtm) val json_ahtm = json.decodeFromString(_AllowsHitTestingModifier.Serializer, data_ahtm) Assert.assertEquals(orig_ahtm, json_ahtm) Assert.assertEquals("""{ "active": true }""".trimIndent(), data_ahtm) } }
29.958333
95
0.680111
fb03968ac7067a365ad4faaafc005ec8bba2c48f
1,758
go
Go
main.go
JakeBjorke/go-blueprint-chats
5d0ae014fe8f6e36ed42df7d5ff13e60974547c8
[ "MIT" ]
null
null
null
main.go
JakeBjorke/go-blueprint-chats
5d0ae014fe8f6e36ed42df7d5ff13e60974547c8
[ "MIT" ]
null
null
null
main.go
JakeBjorke/go-blueprint-chats
5d0ae014fe8f6e36ed42df7d5ff13e60974547c8
[ "MIT" ]
null
null
null
package main import ( "flag" "html/template" "log" "net/http" "os" "path/filepath" "sync" "trace" "github.com/stretchr/gomniauth" "github.com/stretchr/gomniauth/providers/google" "github.com/stretchr/objx" ) type templateHandler struct { once sync.Once filename string templ *template.Template } //ServeHTTP handles the http Request func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { t.once.Do(func() { t.templ = template.Must(template.ParseFiles(filepath.Join("templates", t.filename))) }) data := map[string]interface{}{ "Host": r.Host, } if authCookie, err := r.Cookie("auth"); err == nil { data["UserData"] = objx.MustFromBase64(authCookie.Value) } t.templ.Execute(w, r) } func main() { //get the address from the command line arguments var addr = flag.String("addr", ":8080", "The addr of the application") flag.Parse() gomniauth.SetSecurityKey("wHR9a0Kt20jjzVQnpkdBFSPdhEmyuV6guB2Nn5LVFSH0yv0Q9skPOBK8wcKahXC") gomniauth.WithProviders( google.New("578717759270-h4oc92fuisc83e75ql95et0960j0l376.apps.googleusercontent.com", "aAqJpqf8bGPKZk1UznGL6FbF", "http://localhost:8080/auth/callback/google"), ) r := newRoom() r.tracer = trace.New(os.Stdout) //direct to the chat client http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"})) //route to the login page http.Handle("/login", &templateHandler{filename: "login.html"}) http.HandleFunc("/auth/", loginHandler) //Bind the room path to the r object http.Handle("/room", r) //start the room in a go-routine go r.run() log.Println("Starting web server on ", *addr) //start the web server if err := http.ListenAndServe(*addr, nil); err != nil { log.Fatal("ListenAndServe: ", err) } }
24.082192
92
0.710466
981f6d8c482a6350e5a3db0187b47a1ad70da8b7
6,090
sql
SQL
db/seed/080_api_opstillingskreds.sql
Septima/gsearch
8ef7b1404da120defb15796f7006c23dfa40e92e
[ "MIT" ]
null
null
null
db/seed/080_api_opstillingskreds.sql
Septima/gsearch
8ef7b1404da120defb15796f7006c23dfa40e92e
[ "MIT" ]
22
2021-10-19T11:14:20.000Z
2022-02-01T10:17:14.000Z
db/seed/080_api_opstillingskreds.sql
Septima/gsearch
8ef7b1404da120defb15796f7006c23dfa40e92e
[ "MIT" ]
null
null
null
CREATE SCHEMA IF NOT EXISTS api; DROP TYPE IF EXISTS api.opstillingskreds CASCADE; CREATE TYPE api.opstillingskreds AS ( id TEXT, "name" TEXT, presentationstring TEXT, geometryWkt TEXT, -- same AS bbox geometryWkt_detail TEXT, valgkredsnr TEXT, storkredsnr TEXT, storkredsnavn TEXT, landsdelsnr TEXT, landsdelsnavn TEXT, geometri geometry, bbox box2d, rang1 double precision, rang2 double precision ); COMMENT ON TYPE api.opstillingskreds IS 'Opstillingskreds'; COMMENT ON COLUMN api.opstillingskreds.presentationstring IS 'Præsentationsform for en opstillingskreds'; COMMENT ON COLUMN api.opstillingskreds."name" IS 'Navn på opstillingskreds'; COMMENT ON COLUMN api.opstillingskreds.id IS 'opstillingskredsnummer'; COMMENT ON COLUMN api.opstillingskreds.geometri IS 'Geometri i valgt koordinatsystem'; COMMENT ON COLUMN api.opstillingskreds.bbox IS 'Geometriens boundingbox i valgt koordinatsystem'; COMMENT ON COLUMN api.opstillingskreds.geometryWkt IS 'Geometriens boundingbox i valgt koordinatsystem (som WKT)'; COMMENT ON COLUMN api.opstillingskreds.geometryWkt_detail IS 'Geometri i valgt koordinatsystem (som WKT)'; DROP TABLE IF EXISTS basic.opstillingskreds_mv; WITH opstillingskredse AS ( SELECT o.opstillingskredsnummer, o.navn, o.valgkredsnummer, o.storkredsnummer, s.navn AS storkredsnavn, st_force2d(o.geometri) AS geometri FROM dagi_500m_nohist_l1.opstillingskreds o LEFT JOIN dagi_500m_nohist_l1.storkreds s on o.storkredsnummer = s.storkredsnummer ) SELECT o.navn || 'kredsen' AS titel, o.opstillingskredsnummer, coalesce(o.navn, '') AS navn, o.valgkredsnummer AS valgkredsnr, o.storkredsnummer AS storkredsnr, o.storkredsnavn, st_multi(st_union(o.geometri)) AS geometri, st_extent(o.geometri) AS bbox INTO basic.opstillingskreds_mv FROM opstillingskredse o GROUP BY o.opstillingskredsnummer, o.navn, o.valgkredsnummer, storkredsnummer, storkredsnavn ; ALTER TABLE basic.opstillingskreds_mv DROP COLUMN IF EXISTS textsearchable_plain_col; ALTER TABLE basic.opstillingskreds_mv ADD COLUMN textsearchable_plain_col tsvector GENERATED ALWAYS AS ( setweight(to_tsvector('simple', split_part(navn, ' ', 1)), 'A') || setweight(to_tsvector('simple', split_part(navn, ' ', 2)), 'B') || setweight(to_tsvector('simple', split_part(navn, ' ', 3)), 'C') || setweight(to_tsvector('simple', basic.split_and_endsubstring(navn, 4)), 'D') ) STORED ; ALTER TABLE basic.opstillingskreds_mv DROP COLUMN IF EXISTS textsearchable_unaccent_col; ALTER TABLE basic.opstillingskreds_mv ADD COLUMN textsearchable_unaccent_col tsvector GENERATED ALWAYS AS ( setweight(to_tsvector('basic.septima_fts_config', split_part(navn, ' ', 1)), 'A') || setweight(to_tsvector('basic.septima_fts_config', split_part(navn, ' ', 2)), 'B') || setweight(to_tsvector('basic.septima_fts_config', split_part(navn, ' ', 3)), 'C') || setweight(to_tsvector('basic.septima_fts_config', basic.split_and_endsubstring(navn, 4)), 'D') ) STORED ; ALTER TABLE basic.opstillingskreds_mv DROP COLUMN IF EXISTS textsearchable_phonetic_col; ALTER TABLE basic.opstillingskreds_mv ADD COLUMN textsearchable_phonetic_col tsvector GENERATED ALWAYS AS ( setweight(to_tsvector('simple', fonetik.fnfonetik(split_part(navn, ' ', 1), 2)), 'A') || setweight(to_tsvector('simple', fonetik.fnfonetik(split_part(navn, ' ', 2), 2)), 'B') || setweight(to_tsvector('simple', fonetik.fnfonetik(split_part(navn, ' ', 3), 2)), 'C') || setweight(to_tsvector('simple', basic.split_and_endsubstring_fonetik(coalesce(navn), 4)), 'D') ) STORED ; CREATE INDEX ON basic.opstillingskreds_mv USING GIN (textsearchable_plain_col); CREATE INDEX ON basic.opstillingskreds_mv USING GIN (textsearchable_unaccent_col); CREATE INDEX ON basic.opstillingskreds_mv USING GIN (textsearchable_phonetic_col); DROP FUNCTION IF EXISTS api.opstillingskreds(text, jsonb, int, int); CREATE OR REPLACE FUNCTION api.opstillingskreds(input_tekst text,filters text,sortoptions integer,rowlimit integer) RETURNS SETOF api.opstillingskreds LANGUAGE plpgsql STABLE AS $function$ DECLARE max_rows integer; query_string TEXT; plain_query_string TEXT; stmt TEXT; BEGIN -- Initialize max_rows = 100; IF rowlimit > max_rows THEN RAISE 'rowlimit skal være <= %', max_rows; END IF; if filters IS NULL THEN filters = '1=1'; END IF; IF btrim(input_tekst) = Any('{.,-, '', \,}') THEN input_tekst = ''; END IF; -- Build the query_string WITH tokens AS (SELECT UNNEST(string_to_array(btrim(input_tekst), ' ')) t) SELECT string_agg(fonetik.fnfonetik(t,2), ':* <-> ') || ':*' FROM tokens INTO query_string; -- build the plain version of the query string for ranking purposes WITH tokens AS (SELECT UNNEST(string_to_array(btrim(input_tekst), ' ')) t) SELECT string_agg(t, ':* <-> ') || ':*' FROM tokens INTO plain_query_string; -- Execute and return the result stmt = format(E'SELECT opstillingskredsnummer, navn, titel, ST_AStext(bbox), ST_AStext(geometri), valgkredsnr, storkredsnr, storkredsnavn, '''' AS landsdelsnr, '''' AS landsdelsnavn, geometri, bbox, basic.combine_rank($2, $2, textsearchable_plain_col, textsearchable_unaccent_col, ''simple''::regconfig, ''basic.septima_fts_config''::regconfig) AS rank1, ts_rank_cd(textsearchable_phonetic_col, to_tsquery(''simple'',$1))::double precision AS rank2 FROM basic.opstillingskreds_mv WHERE ( textsearchable_phonetic_col @@ to_tsquery(''simple'', $1) OR textsearchable_plain_col @@ to_tsquery(''simple'', $2)) AND %s ORDER BY rank1 desc, rank2 desc, navn LIMIT $3 ;', filters); RETURN QUERY EXECUTE stmt using query_string, plain_query_string, rowlimit; END $function$; -- Test cases: /* SELECT (api.opstillingskreds('rønn',NULL, 1, 100)).*; SELECT (api.opstillingskreds('hels',NULL, 1, 100)).*; SELECT (api.opstillingskreds('åkir',NULL, 1, 100)).*; SELECT (api.opstillingskreds('nord',NULL, 1, 100)).*; SELECT (api.opstillingskreds('vest',NULL, 1, 100)).*; */
36.035503
159
0.744663
930cd67a5d976ebbe3df5f97e6bec1d9a2bdd040
196
swift
Swift
MusicshotEntity/Sources/Entity/Entity.swift
sora0077/musicshot-dev
7280f11d9bc4461e787372553bfd3fe7ef45c1d2
[ "MIT" ]
null
null
null
MusicshotEntity/Sources/Entity/Entity.swift
sora0077/musicshot-dev
7280f11d9bc4461e787372553bfd3fe7ef45c1d2
[ "MIT" ]
null
null
null
MusicshotEntity/Sources/Entity/Entity.swift
sora0077/musicshot-dev
7280f11d9bc4461e787372553bfd3fe7ef45c1d2
[ "MIT" ]
null
null
null
// // Entity.swift // MusicshotCore // // Created by 林達也 on 2018/03/04. // Copyright © 2018年 林達也. All rights reserved. // import Foundation public enum Entity { public enum Ranking {} }
14
47
0.658163
368eb780168fbe0d32fc9b115fc5a267dbfa233b
423
lua
Lua
package.lua
james2doyle/lit-text-extensions
21717c8d793c5d28c1b209cc46e08dce9f9b5dea
[ "MIT" ]
null
null
null
package.lua
james2doyle/lit-text-extensions
21717c8d793c5d28c1b209cc46e08dce9f9b5dea
[ "MIT" ]
null
null
null
package.lua
james2doyle/lit-text-extensions
21717c8d793c5d28c1b209cc46e08dce9f9b5dea
[ "MIT" ]
null
null
null
return { name = "james2doyle/text-extensions", version = "0.0.4", homepage = "https://github.com/james2doyle/lit-text-extensions", description = "Get a list of valid text file extensions", tags = { "text", "extensions" }, license = "MIT", author = { name = "James Doyle", email = "james2doyle@gmail.com" }, files = { "*.lua", "!text-test.lua", "!tests", "!examples" } }
20.142857
66
0.574468
aff1165d4da720607f6b34172b8ac88e5641d88e
8,897
rb
Ruby
fastlane/spec/pushify_spec.rb
lyndsey-ferguson/medium-post-fastlane-xcodeproj
430b652a9fec690cf46cbcde29e7e7f2ce27390e
[ "MIT" ]
2
2018-01-12T22:54:20.000Z
2018-02-22T15:42:45.000Z
fastlane/spec/pushify_spec.rb
lyndsey-ferguson/medium-post-fastlane-xcodeproj
430b652a9fec690cf46cbcde29e7e7f2ce27390e
[ "MIT" ]
null
null
null
fastlane/spec/pushify_spec.rb
lyndsey-ferguson/medium-post-fastlane-xcodeproj
430b652a9fec690cf46cbcde29e7e7f2ce27390e
[ "MIT" ]
null
null
null
require_relative '../pushify' # Configure RSpec to allow us to make tests that share 'context' RSpec.configure do |rspec| # This config option will be enabled by default on RSpec 4, # but for reasons of backwards compatibility, you have to # set it on RSpec 3. # # It causes the host group and examples to inherit metadata # from the shared context. rspec.shared_context_metadata_behavior = :apply_to_host_groups end # A shared context that allows our editing of the notification service target # dependencies to be tested without needing real Xcodeproj classes. RSpec # is amazing!! RSpec.shared_context "edit notification service dependencies", shared_context: :metadata do before(:each) do # OpenStruct allows us to add instance variables freely @notification_service_target = OpenStruct.new @notification_service_target.product_reference = OpenStruct.new @ns_product_reference = OpenStruct.new @notification_service_target.product_reference = @ns_product_reference # mock out the methods for the build phase so that Pushify can call it # without crashing and at the same time allowing us to 'expect' the calls @embed_app_extensions_buildphase = OpenStruct.new allow(@embed_app_extensions_buildphase) .to receive(:add_file_reference) allow(@embed_app_extensions_buildphase) .to receive(:remove_file_reference) @target = OpenStruct.new @notification_service_target_dependency = OpenStruct.new @notification_service_target_dependency.target = @notification_service_target dummy_target_dependency = OpenStruct.new dummy_target_dependency.target = OpenStruct.new # make sure that our target has the dependencies so we can check that it # is removed appropriately @target.dependencies = [dummy_target_dependency, @notification_service_target_dependency] allow(@target) .to receive(:add_dependency) .with(@notification_service_target) # a convenience method to return our tracked build phase allow(Pushify) .to receive(:embed_app_extensions_buildphase) .and_return(@embed_app_extensions_buildphase) end after(:each) do # reset Pushify to use the real method when we're done allow(Pushify) .to receive(:embed_app_extensions_buildphase) .and_call_original end end describe Pushify do describe 'GIVEN a call to update_push_entitlements' do before(:each) do @entitlements = { 'aps-environment' => '' } allow(Pushify).to receive(:update_entitlements_file).and_yield(@entitlements) end after(:each) do allow(Pushify).to receive(:update_entitlements_file).and_call_original end describe 'WHEN the push_type is "development"' do it 'THEN the entitlements file aps-environment is "development"' do Pushify.update_push_entitlements('development') expect(@entitlements['aps-environment']).to eq('development') end end describe 'WHEN the push_type is "production"' do it 'THEN the entitlements file aps-environment is "production"' do Pushify.update_push_entitlements('production') expect(@entitlements['aps-environment']).to eq('production') end end describe 'WHEN the push_type is "none"' do it 'THEN the entitlements file aps-environment is removed' do Pushify.update_push_entitlements('none') expect(@entitlements).not_to have_key('aps-environment') end end describe 'WHEN the push_type is nil' do it 'THEN the entitlements file aps-environment is removed' do Pushify.update_push_entitlements(nil) expect(@entitlements).not_to have_key('aps-environment') end end end describe 'GIVEN a call to update_app_capabilities' do before(:each) do @capabilities = { 'com.apple.Push' => { 'enabled' => '' } } allow(Pushify).to receive(:update_app_capabilities).and_yield(@capabilities) end after(:each) do allow(Pushify).to receive(:update_app_capabilities).and_call_original end describe 'WHEN push is enabled' do it 'THEN the push capability is 1' do Pushify.enable_push_capability(true) expect(@capabilities['com.apple.Push']['enabled']).to eq('1') end end describe 'WHEN push is disabled' do it 'THEN the push capability is 0' do Pushify.enable_push_capability(false) expect(@capabilities['com.apple.Push']['enabled']).to eq('0') end end end describe 'GIVEN a call to add_notification_service_dependency' do include_context "edit notification service dependencies" it 'THEN the target depends on the notification service target' do expect(@target) .to receive(:add_dependency) .with(@notification_service_target) Pushify.add_notification_service_dependency( @target, @notification_service_target ) end it 'THEN the target\'s embed app extensions build phase has notification service\'s built product' do expect(@embed_app_extensions_buildphase) .to receive(:add_file_reference) .with(@ns_product_reference, true) Pushify.add_notification_service_dependency( @target, @notification_service_target ) end end describe 'GIVEN a call to remove_notification_service_dependency' do include_context "edit notification service dependencies" it 'THEN the target does not depend on the notification service target' do Pushify.remove_notification_service_dependency( @target, @notification_service_target ) expect(@target.dependencies).not_to include(@notification_service_target_dependency) end it 'THEN the target\'s embed app extensions build phase does not have the notification service\'s built product' do expect(@embed_app_extensions_buildphase) .to receive(:remove_file_reference) .with(@notification_service_target.product_reference) Pushify.remove_notification_service_dependency( @target, @notification_service_target ) end end describe 'GIVEN a call to update_push_target_dependencies' do before(:each) do @target = OpenStruct.new @notification_service_target = OpenStruct.new allow(Pushify) .to receive(:update_notification_service_dependency) .and_yield(@target, @notification_service_target) end after(:each) do allow(Pushify) .to receive(:update_notification_service_dependency) .and_call_original end describe 'WHEN push is enabled' do it 'THEN add_notification_service_dependency is called' do expect(Pushify) .to receive(:add_notification_service_dependency) .with(@target, @notification_service_target) Pushify.update_push_target_dependencies(true) end it 'THEN remove_notification_service_dependency is called' do expect(Pushify) .to receive(:remove_notification_service_dependency) .with(@target, @notification_service_target) Pushify.update_push_target_dependencies(false) end end end describe 'GIVEN a call to enable_push' do describe 'WHEN push_type is "production"' do it 'THEN the correct methods are called with the correct value' do expect(Pushify).to receive(:update_push_entitlements).with('production') expect(Pushify).to receive(:enable_push_capability).with(true) expect(Pushify).to receive(:update_push_target_dependencies).with(true) Pushify.enable_push('production') end end describe 'WHEN push_type is "development"' do it 'THEN the correct methods are called with the correct value' do expect(Pushify).to receive(:update_push_entitlements).with('development') expect(Pushify).to receive(:enable_push_capability).with(true) expect(Pushify).to receive(:update_push_target_dependencies).with(true) Pushify.enable_push('development') end end describe 'WHEN push_type is "none"' do it 'THEN the correct methods are called with the correct value' do expect(Pushify).to receive(:update_push_entitlements).with('none') expect(Pushify).to receive(:enable_push_capability).with(false) expect(Pushify).to receive(:update_push_target_dependencies).with(false) Pushify.enable_push('none') end end describe 'WHEN push_type is not given' do it 'THEN the correct methods are called with the correct value' do expect(Pushify).to receive(:update_push_entitlements).with('none') expect(Pushify).to receive(:enable_push_capability).with(false) expect(Pushify).to receive(:update_push_target_dependencies).with(false) Pushify.enable_push end end end end
35.446215
119
0.714511
dded53ea97d52d1205bb5855251db40cdcde0a55
655
kt
Kotlin
judokit-android/src/main/java/com/judokit/android/ui/common/Constants.kt
volkhinP/JudoKit-Android
ea7fc997a350b7d6e21b079282888cce31d023bc
[ "MIT" ]
null
null
null
judokit-android/src/main/java/com/judokit/android/ui/common/Constants.kt
volkhinP/JudoKit-Android
ea7fc997a350b7d6e21b079282888cce31d023bc
[ "MIT" ]
null
null
null
judokit-android/src/main/java/com/judokit/android/ui/common/Constants.kt
volkhinP/JudoKit-Android
ea7fc997a350b7d6e21b079282888cce31d023bc
[ "MIT" ]
null
null
null
package com.judokit.android.ui.common const val GOOGLE_PAY_API_VERSION = 2 const val GOOGLE_PAY_API_VERSION_MINOR = 0 const val ANIMATION_DURATION_500 = 500L const val PATTERN_CARD_EXPIRATION_DATE = "##/##" const val REGEX_JUDO_ID = "^(([0-9]{9})|([0-9]{3}-[0-9]{3}-[0-9]{3})|([0-9]{6}))?\$" /** * Constant for registering broadcast receiver * Used in [com.judokit.android.ui.pollingstatus.PollingStatusFragment.handleBankSaleResponse] method for sending the broadcast */ const val BR_PBBA_RESULT = "BR_PBBA_RESULT" /** * Constant for acquiring JudoResult of PayByBank app sale response from an intent */ const val PBBA_RESULT = "PBBA_RESULT"
32.75
128
0.745038
85f6e330ab8faedaa0b110d152bbe64acabc9bd3
3,930
sql
SQL
polltest.sql
Liladhar-s/Online-Voting-System
2821ca3c5e4fd342d937abe84c08c82b92670058
[ "MIT" ]
null
null
null
polltest.sql
Liladhar-s/Online-Voting-System
2821ca3c5e4fd342d937abe84c08c82b92670058
[ "MIT" ]
null
null
null
polltest.sql
Liladhar-s/Online-Voting-System
2821ca3c5e4fd342d937abe84c08c82b92670058
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 4.6.4 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Mar 05, 2017 at 09:00 AM -- Server version: 5.7.14 -- PHP Version: 5.6.25 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 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: `polltest` -- -- -------------------------------------------------------- -- -- Table structure for table `languages` -- CREATE TABLE `languages` ( `lan_id` int(100) NOT NULL, `fullname` varchar(10) NOT NULL, `about` varchar(255) NOT NULL, `votecount` int(255) NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `languages` -- INSERT INTO `languages` (`lan_id`, `fullname`, `about`, `votecount`) VALUES (1, 'JAVA', 'java is', 5), (2, 'PYTHON', 'python is', 6), (3, 'C++', 'c++ is', 21), (4, 'PHP', 'php is', 17), (5, '.NET', '.net is ', 4); -- -------------------------------------------------------- -- -- Table structure for table `loginusers` -- CREATE TABLE `loginusers` ( `id` int(200) NOT NULL, `username` varchar(100) NOT NULL, `password` varchar(100) NOT NULL, `rank` varchar(80) NOT NULL DEFAULT 'voter', `status` varchar(10) NOT NULL DEFAULT 'ACTIVE' ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `loginusers` -- INSERT INTO `loginusers` (`id`, `username`, `password`, `rank`, `status`) VALUES (47, 'helllo', 'b373c043b854b0ebb97afe9b0ba47059', 'voter', 'ACTIVE'), (46, 'jaha', 'e3df9353ab12391b79865f25a0d7068e', 'voter', 'ACTIVE'), (45, 'action', '1ace9555f0aafb4fe1e75309e8f79e4d', 'voter', 'ACTIVE'), (44, 'arjun', '451d3eb1573c7ebb70c08dfee9766509', 'voter', 'ACTIVE'), (43, 'niku19', 'ac61ebbe84c06debaa78c0a832330164', 'voter', 'ACTIVE'), (42, 'ejjhed', 'b3f70c0d1b269668e937741a5d5797ab', 'voter', 'ACTIVE'), (41, 'Anirban', '9a7108cfaa7f51efb5fcda9e9d4b7a90', 'voter', 'ACTIVE'), (40, 'dnddd', 'b5d165334b465a7fc42310750430b3f9', 'voter', 'ACTIVE'); -- -------------------------------------------------------- -- -- Table structure for table `voters` -- CREATE TABLE `voters` ( `firstname` varchar(100) NOT NULL, `lastname` varchar(100) NOT NULL, `username` varchar(100) NOT NULL, `status` varchar(10) NOT NULL DEFAULT 'NOTVOTED', `voted` varchar(255) DEFAULT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1; -- -- Dumping data for table `voters` -- INSERT INTO `voters` (`firstname`, `lastname`, `username`, `status`, `voted`) VALUES ('sdjdjdj', 'djdjddjj', 'helllo', 'VOTED', 'python'), ('Anirban', 'oodoododo', 'jaha', 'NOTVOTED', NULL), ('Anirban', 'Dutta', 'action', 'VOTED', 'php'), ('Anirban', 'Dutta', 'arjun', 'NOTVOTED', NULL), ('janemaan', 'lohiid', 'niku19', 'VOTED', 'c++'), ('asdhk', 'ddddnd', 'ejjhed', 'NOTVOTED', NULL), ('Anirban', 'Dutta', 'Anirban', 'VOTED', 'java'), ('ndndnd', 'dhbhdd', 'dnddd', 'NOTVOTED', NULL); -- -- Indexes for dumped tables -- -- -- Indexes for table `languages` -- ALTER TABLE `languages` ADD PRIMARY KEY (`lan_id`); -- -- Indexes for table `loginusers` -- ALTER TABLE `loginusers` ADD PRIMARY KEY (`id`), ADD UNIQUE KEY `username` (`username`); -- -- Indexes for table `voters` -- ALTER TABLE `voters` ADD UNIQUE KEY `username` (`username`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `languages` -- ALTER TABLE `languages` MODIFY `lan_id` int(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT for table `loginusers` -- ALTER TABLE `loginusers` MODIFY `id` int(200) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=48; /*!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 */;
27.291667
84
0.645038
cb8f593bf81163325b16a935ee03841686b1722a
880
asm
Assembly
os/bootloader/32bit_print.asm
stplasim/basic-os
36d951e2e2adcbae75a6066b464552b61a3d7f2c
[ "MIT" ]
2
2021-03-21T09:32:19.000Z
2022-01-28T22:22:41.000Z
os/bootloader/32bit_print.asm
stplasim/basic-os
36d951e2e2adcbae75a6066b464552b61a3d7f2c
[ "MIT" ]
null
null
null
os/bootloader/32bit_print.asm
stplasim/basic-os
36d951e2e2adcbae75a6066b464552b61a3d7f2c
[ "MIT" ]
null
null
null
; This print string routine works in 32-bit mode ; Here we don't have BIOS interrupts. We directly manipulating the VGA video memory instead of calling int 0x10 ; The VGA memory starts at address 0xb8000 and it has a text mode which is useful to avoid manipulating direct pixels. [bits 32] ; using 32-bit protected mode ; this is how constants are defined VIDEO_MEMORY equ 0xb8000 WHITE_ON_BLACK equ 0x0f ; the color byte for each character print_string_pm: pusha mov edx, VIDEO_MEMORY print_string_pm_loop: mov al, [ebx] ; [ebx] is the address of our character mov ah, WHITE_ON_BLACK cmp al, 0 ; check if end of string je print_string_pm_done mov [edx], ax ; store character + attribute in video memory add ebx, 1 ; next char add edx, 2 ; next video memory position jmp print_string_pm_loop print_string_pm_done: popa ret
27.5
118
0.738636
bb214d50525ed35f554d2d27eaedf99c968fa851
11,424
html
HTML
www.w3.org/blog/International/comments/feed/index.html
science-tech02/Birthday
decba4db197724c6c7f7f712fe7dc0279b01163f
[ "Apache-2.0" ]
null
null
null
www.w3.org/blog/International/comments/feed/index.html
science-tech02/Birthday
decba4db197724c6c7f7f712fe7dc0279b01163f
[ "Apache-2.0" ]
null
null
null
www.w3.org/blog/International/comments/feed/index.html
science-tech02/Birthday
decba4db197724c6c7f7f712fe7dc0279b01163f
[ "Apache-2.0" ]
null
null
null
<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" > <channel> <title> Comments for Internationalization Activity Blog </title> <atom:link href="https://www.w3.org/blog/international/comments/feed/" rel="self" type="application/rss+xml" /> <link>https://www.w3.org/blog/International</link> <description></description> <lastBuildDate>Tue, 07 May 2013 09:18:32 +0000</lastBuildDate> <sy:updatePeriod> hourly </sy:updatePeriod> <sy:updateFrequency> 1 </sy:updateFrequency> <generator>https://wordpress.org/?v=5.7.4</generator> <item> <title> Comment on Updated article: The byte-order mark (BOM) in HTML by Otto </title> <link>https://www.w3.org/blog/International/2013/02/01/updated-article/#comment-28140</link> <dc:creator><![CDATA[Otto]]></dc:creator> <pubDate>Tue, 07 May 2013 09:18:32 +0000</pubDate> <guid isPermaLink="false">http://www.w3.org/blog/International/?p=2260#comment-28140</guid> <description><![CDATA[Please note that in contrary to the article and blog post Microsoft stating with IE10 gave the HTTP header a higher precedence than UTF-8 BOM which brings back various problems.]]></description> <content:encoded><![CDATA[<p>Please note that in contrary to the article and blog post Microsoft stating with IE10 gave the HTTP header a higher precedence than UTF-8 BOM which brings back various problems.</p> ]]></content:encoded> </item> <item> <title> Comment on New translations into Russian and Ukrainian by Роман </title> <link>https://www.w3.org/blog/International/2011/11/02/new-translations-into-russian-and-ukrainian/#comment-690</link> <dc:creator><![CDATA[Роман]]></dc:creator> <pubDate>Fri, 18 Nov 2011 07:25:46 +0000</pubDate> <guid isPermaLink="false">http://www.w3.org/blog/International/?p=1990#comment-690</guid> <description><![CDATA[Спасибо большое! побольше бы статей на русском!]]></description> <content:encoded><![CDATA[<p>Спасибо большое! побольше бы статей на русском!</p> ]]></content:encoded> </item> <item> <title> Comment on Internationalization: Awakening the Sleeping Giant by Molly E. Holzschlag [Visitor] </title> <link>https://www.w3.org/blog/International/2006/06/19/internationalization_awakening_the_sleep/#comment-13</link> <dc:creator><![CDATA[Molly E. Holzschlag [Visitor]]]></dc:creator> <pubDate>Fri, 23 Jun 2006 18:44:09 +0000</pubDate> <guid isPermaLink="false">http://www.w3.org/blog/Internationaltmp/2006/06/19/internationalization_awakening_the_sleep/#comment-13</guid> <description><![CDATA[Hi Chris, thanks for your kind words regarding my talk. I unfortunately think that we have a presumption in the English speaking world that English dominates. As I mentioned in my talk, there are actual laws where I live prohibiting teachers to teach in Spanish or even bilingually. To think, the teaching of communication and language - a crime! As with so many things, it&#039;s awareness that can help. It becomes so obvious that the Web is more useful, accessible and downright interesting when it is filled with the many cultures and languages expressed worldwide. I hope to do many more presentations of this nature and encourage everyone to look around the site here. Richard and the i18n Working Group have put together some amazing resources here, some of the quiet best at the W3C. I&#039;m hoping to not keep that so quiet in the future ;-) ]]></description> <content:encoded><![CDATA[<p>Hi Chris, thanks for your kind words regarding my talk.</p> <p>I unfortunately think that we have a presumption in the English speaking world that English dominates. As I mentioned in my talk, there are actual laws where I live prohibiting teachers to teach in Spanish or even bilingually. To think, the teaching of communication and language &#8211; a crime! </p> <p>As with so many things, it&#8217;s awareness that can help. It becomes so obvious that the Web is more useful, accessible and downright interesting when it is filled with the many cultures and languages expressed worldwide.</p> <p>I hope to do many more presentations of this nature and encourage everyone to look around the site here. Richard and the i18n Working Group have put together some amazing resources here, some of the quiet best at the W3C. I&#8217;m hoping to not keep that so quiet in the future 😉</p> ]]></content:encoded> </item> <item> <title> Comment on Internationalization: Awakening the Sleeping Giant by Chris Jennings [Visitor] </title> <link>https://www.w3.org/blog/International/2006/06/19/internationalization_awakening_the_sleep/#comment-12</link> <dc:creator><![CDATA[Chris Jennings [Visitor]]]></dc:creator> <pubDate>Tue, 20 Jun 2006 08:52:15 +0000</pubDate> <guid isPermaLink="false">http://www.w3.org/blog/Internationaltmp/2006/06/19/internationalization_awakening_the_sleep/#comment-12</guid> <description><![CDATA[Such a good talk at the @Media Conference. Molly was very passionate about this subject and the aduience got some really useful advice about addressing the &#039;world&#039; in the &#039;world wide web&#039;. There is also an educational issue - our are schools creating enough linguists who might combine their enthusiasm for web techniologies to create multicultural sites? Or are we presuming that the dominant language of the web is English forever? ]]></description> <content:encoded><![CDATA[<p>Such a good talk at the @Media Conference. Molly was very passionate about this subject and the aduience got some really useful advice about addressing the &#8216;world&#8217; in the &#8216;world wide web&#8217;.</p> <p>There is also an educational issue &#8211; our are schools creating enough linguists who might combine their enthusiasm for web techniologies to create multicultural sites? Or are we presuming that the dominant language of the web is English forever?</p> ]]></content:encoded> </item> <item> <title> Comment on Internationalization Tag Set (ITS) by Richard Ishida [Member] </title> <link>https://www.w3.org/blog/International/2006/05/22/internationalization_tag_set_its_3/#comment-15</link> <dc:creator><![CDATA[Richard Ishida [Member]]]></dc:creator> <pubDate>Fri, 09 Jun 2006 11:37:08 +0000</pubDate> <guid isPermaLink="false">http://www.w3.org/blog/Internationaltmp/2006/05/22/internationalization_tag_set_its_3/#comment-15</guid> <description><![CDATA[Gerard, Please look at our recently published article Understanding the New Language Tags, which talks about RFC3066bis, and how that will incorporate ISO 639-3 codes when they are finalised. This should take care of the zh problem you mentioned. Note that you can already use zh-Hant and zh-Hans for Traditional and Simplified Chinese. ]]></description> <content:encoded><![CDATA[<p>Gerard, Please look at our recently published article Understanding the New Language Tags, which talks about RFC3066bis, and how that will incorporate ISO 639-3 codes when they are finalised. This should take care of the zh problem you mentioned. Note that you can already use zh-Hant and zh-Hans for Traditional and Simplified Chinese.</p> ]]></content:encoded> </item> <item> <title> Comment on Internationalization Tag Set (ITS) by Gerard Meijssen [Visitor] </title> <link>https://www.w3.org/blog/International/2006/05/22/internationalization_tag_set_its_3/#comment-14</link> <dc:creator><![CDATA[Gerard Meijssen [Visitor]]]></dc:creator> <pubDate>Mon, 29 May 2006 15:34:49 +0000</pubDate> <guid isPermaLink="false">http://www.w3.org/blog/Internationaltmp/2006/05/22/internationalization_tag_set_its_3/#comment-14</guid> <description><![CDATA[One of the basis elements of the ITS is that it assumes other standards. Of particular relevance to me is the RFC3066bis that is referred to for language identification. There are two things wrong with this standard; it lacks information on many languages; ISO-639-3 which is sadly still a dis will help out. However this raises issues; zh is Chinese but it is no longer considered one language. There will also be many new languages that do not have any older codes. When this code is meant for identifying resources, any resources, than it is important to be able to identify the specific version of an orthography. This needs to be done in a standard way and there is no standard for this. Consequently; it must be possible to indicate at least ISO-639-3 without any reference to the older codes. There must be a standard way to indicate a version of an orthography. Without this this schema will work for some but will be sadly deficient for others. ]]></description> <content:encoded><![CDATA[<p>One of the basis elements of the ITS is that it assumes other standards. Of particular relevance to me is the RFC3066bis that is referred to for language identification.</p> <p>There are two things wrong with this standard; it lacks information on many languages; ISO-639-3 which is sadly still a dis will help out. However this raises issues; zh is Chinese but it is no longer considered one language. There will also be many new languages that do not have any older codes.</p> <p>When this code is meant for identifying resources, any resources, than it is important to be able to identify the specific version of an orthography. This needs to be done in a standard way and there is no standard for this.</p> <p>Consequently; it must be possible to indicate at least ISO-639-3 without any reference to the older codes. There must be a standard way to indicate a version of an orthography.</p> <p>Without this this schema will work for some but will be sadly deficient for others.</p> ]]></content:encoded> </item> <item> <title> Comment on Request for feedback: Usefulness of ::first-letter in non-Latin scripts by Goutam Kumar Saha [Visitor] </title> <link>https://www.w3.org/blog/International/2006/01/20/request_for_feedback_usefulness_of_first/#comment-16</link> <dc:creator><![CDATA[Goutam Kumar Saha [Visitor]]]></dc:creator> <pubDate>Wed, 10 May 2006 08:53:30 +0000</pubDate> <guid isPermaLink="false">http://www.w3.org/blog/Internationaltmp/2006/01/20/request_for_feedback_usefulness_of_first/#comment-16</guid> <description><![CDATA[Subject: Re: First Letter Styling for Indian languages Hi All, For Devanagari script, Bengali and Assamese scripts etc, we often use first letter styling ( with or with little extended headstrokes or without headstrokes ). Content Editor uses increased font size / style face for the so called &quot;a drop letter.&quot; Question of aligning headstrokes does not arise here. Bengali example: Regards, Goutam ]]></description> <content:encoded><![CDATA[<p>Subject: Re: First Letter Styling for Indian languages</p> <p>Hi All,<br /> For Devanagari script, Bengali and Assamese scripts etc, we often use first letter styling ( with or with little extended headstrokes or without headstrokes ). Content Editor uses increased font size / style face for the so called &#8220;a drop letter.&#8221; Question of aligning headstrokes does not arise here. Bengali example:</p> <p>Regards,<br /> Goutam</p> ]]></content:encoded> </item> </channel> </rss>
70.08589
374
0.758491
fc5af1944bb450accc47de4330a7b0cb7b1e1d9f
17,759
css
CSS
public/themes/default/assets/css/serivceCase.css
hu19891110/keke
9882760992f1fb025e390ab3d6e2edd8b74f6a15
[ "Apache-2.0" ]
null
null
null
public/themes/default/assets/css/serivceCase.css
hu19891110/keke
9882760992f1fb025e390ab3d6e2edd8b74f6a15
[ "Apache-2.0" ]
null
null
null
public/themes/default/assets/css/serivceCase.css
hu19891110/keke
9882760992f1fb025e390ab3d6e2edd8b74f6a15
[ "Apache-2.0" ]
null
null
null
body{ font-family: "Microsoft YaHei"; } .now-position{ height: 44px; line-height: 44px; color: #888; font-size:12px; } .personal-info{ position: relative; width: 100%; height: 195px; background: url(../images/personal_back.png) center no-repeat #000; /*padding: 40px 27px;*/ overflow: hidden; } .personal-info-back-pic{ width: 100%; height: 100%; } .personal-info-words{ position: absolute; top:43px; left: 40px; } .change-back-img-btn{ display: block; width: 20px; height: 20px; position: absolute; right: 0; top: 0; cursor: pointer; background: url(../images/personal_change_back.png) center no-repeat; } .personal-info-pic{ width: 104px; height: 104px; float: left; margin: 5px 20px 5px 0; } .personal-info-block{ color: #fff; margin-left: 124px; width: 990px; } .personal-info-block-name{ position: relative; height: 24px; line-height: 24px; margin-bottom: 15px; } .personal-info-block-name span{ width: 20px; height: 20px; display: inline-block; position: relative; top: 2px; margin: 0 5px; } .personal-info-block-name h3{ margin: 0 5px 0 0; display: inline-block; } .bank-attestation{ background: url(../images/bank-c.png) center no-repeat; } .bank-attestation-no{ background: url(../images/bank-h.png) center no-repeat; } .cd-card-attestation{ background: url(../images/realname-c.png) center no-repeat; } .cd-card-attestation-no{ background: url(../images/realname-h.png) center no-repeat; } .email-attestation{ background: url(../images/email-c.png) center no-repeat; } .email-attestation-no{ background: url(../images/email-h.png) center no-repeat; } .alipay-attestation{ background: url(../images/pay-c.png) center no-repeat; } .alipay-attestation-no{ background: url(../images/pay-h.png) center no-repeat; } .personal-tag{ height: 25px; position: relative; font-size:14px; } .personal-about { font-size:14px; } .personal-tag span{ display: inline-block; padding: 0 10px; border: 1px solid #fff; border-radius: 10px; margin-left: 10px; } .personal-about span{ display: inline-block; width:42px; vertical-align: top; } .personal-about p{ display: inline-block; width: 940px; } .personal-case-detail-list{ padding: 0 22px; margin: 16px 15px; height: 49px; border-bottom: 1px solid #ebebeb; background: #fff; } .personal-case-list, .personal-evaluate-detail{ display: inline-block; height: 49px; line-height: 29px; font-size: 18px; padding: 10px 10px; margin-right:18px; } .personal-add-case-btn{ display: inline-block; width: 108px; height: 36px; line-height: 36px; color: #fff; text-align: center; float: right; margin: 6px 20px 6px 0; background: #2f55a0; font-size: 14px; border-radius: 3px; } .personal-add-case-btn:hover{ color: #fff; } .follow-me{ display: inline-block; width: 75px; height: 22px; position: absolute; top: 2px; right: 0; line-height: 20px; border: 1px solid #ff9934; color: #ff9934; text-align: center; font-size: 14px; } .follow-me:hover{ color: #ff9934; } .followed-me{ display: inline-block; width: 75px; height: 22px; position: absolute; top: 2px; right: 0; line-height: 20px; border: 1px solid #1abc9c; color: #1abc9c; text-align: center; font-size: 14px; } .followed-me:hover{ color: #1abc9c; } .follow-me i,.followed-me i{ height: 20px; margin-right: 5px; font-size: 12px; } .follow-me .glyphicon,.contact-me .glyphicon { font-size:12px; font-weight: normal; } .contact-me{ display: inline-block; width: 75px; height: 22px; position: absolute; top: -4px; right: 0; line-height: 20px; border: 1px solid #fff; color: #fff; text-align: center; font-size: 14px; opacity: .8; } .contact-me i{ height: 20px; font-size: 16px; margin-right: 5px; } .contact-me:hover{ color: #fff; opacity: .8; } .case-list-item{ height:315px; margin-bottom: 20px; } .case-list-item img{ width: 100%; height: 202px; } .case-list-item-name{ background-color: #f7f7f7; height: 51px; font-size: 14px; padding: 15px 10px; overflow: hidden; } .case-list-item-name p{ margin: 0; width: 155px; display: inline-block; overflow: hidden; text-overflow:ellipsis; white-space: nowrap; } .case-list-item-name span{ display: inline-block; float: right; color: #898989; } .case-list-item-admin{ background-color: #f7f7f7; height: 61px; font-size: 14px; padding: 13px 10px; overflow: hidden; border-bottom: 2px solid #f0f0f0; } .case-list-item-admin-info{ height: 35px; float: left; line-height: 35px; } .case-list-item-admin-info img{ width: 35px; height: 35px; margin-right: 5px; display: inline-block; margin-top: -25px; } .case-list-item-admin-info p{ display: inline-block; margin: 0; width: 120px; overflow: hidden; text-overflow:ellipsis; white-space: nowrap; } .case-list-item-admin span{ display: inline-block; color: #999; height: 35px; line-height: 35px; } .case-list-item-admin span i{ color:#d9d9d9; } .case-list-item-admin span .fa-tag { transform: rotateZ(90deg); } .case-page{ margin-bottom: 46px; } .dataTables_paginate .case-page-list{ margin: 0 15px; } .case-page-list li a{ margin: 0 5px; } /*成功案例详情*/ .personal-case-detail-main-area{ border: 1px solid #ebebeb; background: #fff; padding: 0; margin: 20px 0 30px 0; } .personal-case-detail-title-name{ text-align: left; height: 125px; padding: 30px 0 15px 0; margin: 0 20px; border-bottom: 1px solid #ebebeb; } .personal-case-detail-title-name h4{ margin-top: 0; margin-bottom: 20px; font-weight: 800; } .personal-case-detail-tags{ display: inline-block; height: 20px; line-height: 15px; border: 1px solid #c0c6d2; color: #898989; padding: 2px 10px; border-radius: 10px; margin-right: 5px; } .personal-case-detail-time{ float: right; color: #898989; } .personal-case-detail-info-words{ padding: 40px 20px 0 20px; } .personal-case-detail-info-words p{ line-height: 22px; text-indent: 28px; margin-bottom: 35px; } .personal-case-detail-info-img{ text-align: center; margin-bottom: 35px; } .personal-case-detail-info-img img{ display: inline-block; } .personal-case-detail-side-img{ padding: 18px 16px; border: 1px solid #ebebeb; background-color: #fff; } .personal-case-detail-about{ border: 1px solid #eaeaea; background: #fff; padding: 20px; } .personal-case-detail-about ul{ margin: 0 0 -1px 0; overflow: hidden; height: 629px; } .personal-case-detail-about li{ height: 126px; border-bottom: 1px dashed #ccc; padding: 20px 0; } .personal-case-detail-about li img{ width: 86px; height: 86px; } .personal-case-detail-about-info{ padding-left: 20px; } .personal-case-detail-about-info p{ margin-bottom: 5px; } .personal-case-detail-about-info-name{ display: inline-block; width: 120px; overflow: hidden; text-overflow:ellipsis; white-space: nowrap; } .contact-me-modal .modal-header{ padding: 10px 15px; background: #ededed; font-size: 14px; } .contact-me-modal .modal-header .close{ font-size: 24px; } .contact-me-modal .modal-body{ padding: 30px 50px 15px; } .contact-me-modal .modal-footer{ text-align: center; border: none; background: #fff; padding: 0 50px 32px 50px; } .contact-me-modal .btn{ border-radius: 3px; width: 108px; height: 36px; border:none; } .contact-me-modal .btn-primary{ background: #2f55a0!important; /*margin-right:25px;*/ margin-right:15px; } .contact-me-modal .btn-default{ background: #ccc!important; } /*评价详情*/ .personal-evaluate-area{ border: 1px solid #ebebeb; background-color: #fff; color: #898989; margin: 0 15px 30px; } .personal-total-evaluate{ height: 90px; border-bottom: 1px solid #ebebeb; overflow: hidden; } .personal-total-evaluate-num{ width: 220px; height: 52px; float: left; overflow: hidden; padding-right: 40px; margin: 19px 40px; border-right: 1px solid #ebebeb; } .personal-evaluate-cicle-title{ float: left; width: 52px; height: 52px; border: 1px solid #999; border-radius: 50%; font-size: 14px; padding: 8px; text-align: center; line-height: 17px; } .personal-good-evaluate{ width: 123px; height: 52px; padding-left: 10px; float: left; } .personal-good-evaluate p{ margin-bottom: 0; height: 26px; line-height: 18px; font-size:14px; } .personal-good-evaluate p span{ font-size: 20px; color: #ff9934; } .personal-total-evaluate-point{ float: left; margin: 19px 0; overflow: hidden; } .personal-evaluate-starts-list{ float: left; height: 52px; overflow: hidden; } .personal-evaluate-starts-item{ width: 130px; height: 52px; float: left; margin-left: 30px; } .personal-evaluate-starts-item p { font-size:14px; } .personal-star{ width: 130px; height: 18px; display: inline-block; background: url(../images/star1.png) repeat-x ; } .personal-evaluate-star-base{ width: 80px; height: 18px; display: inline-block; background: url(../images/star.png) repeat-x left -52px; } .personal-evaluate-star-base-1{ width: 26px; height: 18px; display: inline-block; background: url(../images/star1.png) repeat-x left -52px; } .personal-evaluate-star-base-2{ width: 52px; height: 18px; display: inline-block; background: url(../images/star1.png) repeat-x left -52px; } .personal-evaluate-star-base-3{ width: 78px; height: 18px; display: inline-block; background: url(../images/star1.png) repeat-x left -52px; } .personal-evaluate-star-base-4{ width: 104px; height: 18px; display: inline-block; background: url(../images/star1.png) repeat-x left -52px; } .personal-evaluate-star-base-5{ width: 130px; height: 18px; display: inline-block; background: url(../images/star1.png) repeat-x left -52px; } .personal-evaluate-list{ min-height: 555px; } .personal-evaluate-list ul{ margin: 0; } .personal-evaluate-list-item{ overflow: hidden; padding: 30px 0 8px 0; margin: 0 19px; border-bottom: 1px dashed #ebebeb; } .personal-case-evaluate-words{ width: 920px; float: left; } .personal-case-evaluate-words a{ color:#2f549f; } .personal-case-evaluate-words h5{ margin: 0; font-size: 16px; } .personal-case-evaluate-words h5 span{ color: #ff9934; padding-right: 15px; } .personal-case-evaluate-words p{ /*width: 100%;*/ height: 45px; padding: 15px 0; margin-bottom: 0; line-height: 15px; font-size: 12px; color: #898989; text-overflow:ellipsis; overflow: hidden; white-space: nowrap; } .personal-case-evaluate-person-time{ float: right; color: #898989; } .personal-case-evaluate-person-time p{ line-height: 17px; position: relative; } .personal-case-evaluate-person-time p span{ color: #ee5751; padding-right:16px; } .personal-case-evaluate-person-time .p-space{ font-style: normal; width:36px; display: inline-block; vertical-align: top; } .evaluate-flowers{ display: inline-block; width: 15px; height: 17px; margin-right: 10px; background: url(../images/flowers.png) center no-repeat; position: relative; top: 3px; } .personal-evaluate-page{ height: 49px; padding: 8px 0; } .personal-evaluate-page li a{ margin: 0 5px; } /* 响应式 */ @media (min-width: 992px) and (max-width: 1200px){ .personal-info{ width: 100%; margin: 0; } .personal-info-back-pic{ width: 100%; } .personal-info-block{ width: 700px; } .personal-case-detail-list{ margin: 16px 15px; } .case-list-box{ margin: 0 15px; } /*.personal-about p{*/ /*width: 485px;*/ /*}*/ .personal-case-evaluate-words{ width: 75%; } } @media (max-width: 991px) and (min-width: 769px) { /*section{*/ /*margin: 15px 0 50px 0;*/ /*}*/ .personal-info{ margin: 0; } .personal-info-back-pic{ width: 100%; } .personal-info-block{ width: 500px; } .add-case.add-case992{ margin: 15px 0 0; } .add-case.add-case992 .col-sm-1{ width: 9.333333%; } .add-case.add-case992 .col-sm-11{ width: 90.66666667%; } .personal-case-detail-list{ margin: 16px 15px; } .personal-evaluate-area{ margin: 0 15px; } .case-list-box{ width: 100%; margin: 0; background: #0058dd; } .personal-case-evaluate-words{ width: 70%; } .personal-total-evaluate{ height:auto; } .personal-total-evaluate-num{ width: 100%; margin: 0; height: auto; padding:15px; border-right: none; } .personal-total-evaluate-point{ width: 100%; margin: 0; padding:0 15px 15px; float: none; overflow: hidden; } .personal-evaluate-starts-list{ width: 70%; height:auto; } .personal-evaluate-starts-item{ width: 30%; margin-left: 10px; } } @media (max-width: 768px) and (min-width: 640px) { /*section{*/ /*margin: 15px 0 50px 0;*/ /*}*/ .personal-info{ width: 100%; margin: 0; height:110px; /*padding:4%;*/ } .personal-info-back-pic{ width: 100%; height:100%; } .personal-info-pic{ width: 60px; height:60px; position: relative; top: -20px; } .personal-info-block{ width: 202%; position: relative; top: -81px; overflow: hidden; margin-left: 79px; } .personal-info-block-name{ margin-bottom: 8px; } .open-close-space-btn{ display: none; } .add-case.add-case992{ margin: 15px 0 0; } .add-case.add-case992 .col-sm-1{ width: 12.333333%; } .add-case.add-case992 .col-sm-11{ width: 87.66666667%; } .add-case.add-case992 .form-group .col-sm-offset-1 { margin-left: 11%; } .task-select a:last-of-type(1), .task-select a:last-of-type(2), .task-select a:last-of-type(3), .task-select a:last-of-type(4){ display: none; } .personal-case-detail-list{ margin: 16px 15px; } .personal-evaluate-area{ margin: 0 15px; } .case-list-box{ width: 100%; margin: 0; background: #0058dd; } .case-list-item img{ width: 100%; } .personal-total-evaluate{ height:auto; } .personal-total-evaluate-num{ width: 100%; margin: 0; height: auto; padding:15px; border-right: none; } .personal-total-evaluate-point{ width: 100%; margin: 0; padding:0 15px 15px; float: none; overflow: hidden; } .personal-evaluate-starts-list{ width: 70%; height:auto; } .personal-evaluate-starts-item{ width: 30%; margin-left: 10px; } .personal-evaluate-list-item{ margin: 0 15px; padding:15px 0 8px; } .personal-case-evaluate-words{ width: 70%; } .personal-case-evaluate-person-time{ width: 28%; text-align: left; } .personal-case-evaluate-words p{ width: 100%; } } @media (max-width: 639px) and (min-width: 320px) { .container{ width: 100%; } /*section{*/ /*margin: 15px 0 50px 0;*/ /*}*/ .personal-info{ /*width: 100%;*/ /*margin: 0 -5px;*/ height:110px; } .personal-info-back-pic{ width: 100%; height: 100%; position: relative; } .open-close-space-btn{ display: none; } .personal-info-words{ position: absolute; left:5px; } .personal-info-block{ width:183%; position: relative; top:-11px; margin-left: 100px; } .personal-info-block-name{ margin-bottom: 8px; } .add-case.add-case992{ margin: 15px 0 0; } .add-case.add-case992 .col-sm-1{ width: 12.333333%; } .add-case.add-case992 .col-sm-11{ width: 87.66666667%; } .add-case.add-case992 .form-group .col-sm-offset-1 { margin-left: 11%; } .task-select a:last-of-type(1), .task-select a:last-of-type(2), .task-select a:last-of-type(3), .task-select a:last-of-type(4){ display: none; } .personal-case-detail-list{ /*width: 100%;*/ margin: 16px 10px; } .personal-evaluate-area{ margin: 0 10px; } .case-list-box{ width: 100%; margin: 0; background: #0058dd; } .personal-add-case-btn{ display: none; } .personal-info-pic{ width: 60px; height:60px; position: relative; top: -20px; left: 20px; } .case-list-item{ height: auto; overflow: hidden; } .case-list-item img{ width: 100%; max-height: 150px; height:auto; } .case-list-item-name{ padding:10px 5px 6px; height:auto; line-height: 1.2; } .case-list-item-admin{ padding:6px 5px; height:auto; line-height: 1.2; } .case-list-item-name p{ width: 100%; } .case-list-item-admin span{ width: 49.5%; height:auto; line-height: 1.5; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .personal-total-evaluate{ height:auto; } .personal-total-evaluate-num{ width: 100%; margin: 0; height: auto; padding:15px; border-right: none; } .personal-total-evaluate-point{ width: 100%; margin: 0; padding:0 15px 15px; float: none; overflow: hidden; } .personal-evaluate-starts-list{ width: 70%; height:auto; } .personal-evaluate-starts-item{ margin-left: 10px; } .personal-evaluate-list-item{ margin: 0 5px; padding:15px 0 8px; } .personal-case-evaluate-words{ width: 60%; } .personal-case-evaluate-person-time{ width: 36%; text-align: right; } .personal-case-evaluate-person-time p:last-child span{ display: inline-block; width: 100%; white-space: nowrap; } } .follow-contact-me{ top:2px; right:81px; } @media (min-width: 992px) { .serivce-caseList{ min-height: 270px; } }
19.013919
71
0.640577
7cd0d34e13cde89496f6e7690d20e351df94ef5d
9,317
rs
Rust
weave/src/matrix/forest/mod.rs
tclchiam/weave-ce
03c7b01b50111c48f6d1b471a23638825d0dbf0e
[ "BSD-3-Clause" ]
2
2018-09-02T03:43:46.000Z
2018-09-05T22:48:50.000Z
weave/src/matrix/forest/mod.rs
tclchiam/bowtie
03c7b01b50111c48f6d1b471a23638825d0dbf0e
[ "BSD-3-Clause" ]
null
null
null
weave/src/matrix/forest/mod.rs
tclchiam/bowtie
03c7b01b50111c48f6d1b471a23638825d0dbf0e
[ "BSD-3-Clause" ]
null
null
null
use std::hash::Hash; use std::iter::FromIterator; use hashbrown::{HashMap, HashSet}; use itertools::Itertools; mod union; mod intersect; mod subset; mod product; /// Forest is an immutable set of sets #[derive(Debug, Clone, Eq, PartialEq)] pub enum Forest<T: Hash + Eq> { Empty, Unit(Vec<T>), Many(HashSet<Vec<T>>), } impl<T: Hash + Eq + Clone + Ord + Sync + Send> Into<Vec<Vec<T>>> for Forest<T> { fn into(self) -> Vec<Vec<T>> { match self { Forest::Empty => Vec::new(), Forest::Unit(set) => vec![set], Forest::Many(matrix) => matrix .into_iter() .collect(), } } } impl<'a, T: Hash + Eq + Clone + Ord + Sync + Send> Into<Vec<Vec<T>>> for &'a Forest<T> { fn into(self) -> Vec<Vec<T>> { match self { Forest::Empty => Vec::new(), Forest::Unit(set) => vec![set.to_vec()], Forest::Many(matrix) => matrix .into_iter() .cloned() .collect(), } } } impl<T: Hash + Eq + Clone + Ord + Sync + Send> Forest<T> { pub fn empty() -> Self { Forest::Empty } pub fn unit(set: &[T]) -> Self { Forest::Unit(Self::filter_repeats(set)) } pub fn many(matrix: &[Vec<T>]) -> Self { match matrix.len() { 0 => Forest::empty(), 1 => Forest::unit(&matrix[0]), _ => { let matrix = matrix.iter() .cloned() .map(|set| Self::filter_repeats(&set)) .unique() .collect(); Forest::Many(matrix) } } } pub fn unique(set: &[T]) -> Self { let matrix: Vec<Vec<T>> = set.iter() .cloned() .map(|element| vec![element]) .collect(); Forest::many(&matrix) } fn filter_repeats<B: FromIterator<T>>(set: &[T]) -> B { set.iter().cloned().sorted().unique().collect::<B>() } pub fn len(&self) -> usize { match self { Forest::Empty => 0, Forest::Unit(_) => 1, Forest::Many(matrix) => matrix.len(), } } pub fn is_empty(&self) -> bool { match self { Forest::Empty => true, _ => false } } pub fn occurrences(&self) -> Vec<(T, usize)> { match self { Forest::Empty => vec![], Forest::Unit(set) => set.iter() .map(|item| (item.clone(), 1)) .collect(), Forest::Many(matrix) => { matrix.iter() .flatten() .fold(HashMap::new(), |mut occurrences, item| { *occurrences.entry(item.clone()).or_insert(0usize) += 1; occurrences }) .into_iter() .sorted_by(|(item1, _), (item2, _)| Ord::cmp(item1, item2)) .collect() } } } pub fn intersect(self, other: Self) -> Self { intersect::intersect(self, other) } pub fn union(self, other: Self) -> Self { union::union(self, other) } pub fn product(self, other: Self) -> Self { product::product(self, other) } pub fn subset(self, element: T) -> Self { subset::subset(self, element) } pub fn subset_not(self, element: T) -> Self { subset::subset_not(self, element) } pub fn subset_all(self, elements: &[T]) -> Self { subset::subset_all(self, elements) } pub fn subset_none(self, elements: &[T]) -> Self { subset::subset_none(self, elements) } } #[cfg(test)] mod eq_forest_tests { use super::Forest; #[test] fn empty_forest() { let forest1: Forest<&str> = Forest::empty(); let forest2: Forest<&str> = Forest::empty(); assert_eq!(forest1, forest2); } #[test] fn unit_forest() { let forest1: Forest<&str> = Forest::unit(&["1", "2"]); let forest2: Forest<&str> = Forest::unit(&["2", "1"]); assert_eq!(forest1, forest2); } #[test] fn many_forest() { let forest1: Forest<&str> = Forest::many(&[vec!["1", "2"]]); let forest2: Forest<&str> = Forest::many(&[vec!["2", "1"]]); assert_eq!(forest1, forest2); } #[test] fn many_forest_with_none() { let forest1 = Forest::<&str>::many(&[]); let forest2 = Forest::<&str>::empty(); assert_eq!(forest1, forest2); } #[test] fn many_forest_with_one() { let forest1 = Forest::many(&[vec!["1"]]); let forest2 = Forest::unit(&["1"]); assert_eq!(forest1, forest2); } } #[cfg(test)] mod empty_forest_tests { use super::Forest; #[test] fn empty_forest_has_size_0() { let forest: Forest<&str> = Forest::empty(); assert_eq!(0, forest.len()); } #[test] fn empty_forest_is_empty() { let forest: Forest<&str> = Forest::empty(); assert_eq!(true, forest.is_empty()); } #[test] fn empty_forest_into() { let forest: Forest<&str> = Forest::empty(); assert_eq!( Vec::<Vec<&str>>::new(), Into::<Vec<_>>::into(forest.clone()) ); } } #[cfg(test)] mod unit_forest_tests { use super::Forest; #[test] fn unit_forest_has_size_1() { let forest: Forest<&str> = Forest::unit(&["1", "2"]); assert_eq!(1, forest.len()); } #[test] fn unit_forest_is_empty() { let forest: Forest<&str> = Forest::unit(&["1", "2"]); assert_eq!(false, forest.is_empty()); } #[test] fn unit_forest_into() { let forest: Forest<&str> = Forest::unit(&["1", "2"]); let expected = vec![vec!["1", "2"]]; assert_eq!( expected, Into::<Vec<_>>::into(forest.clone()) ); } } #[cfg(test)] mod many_forest_tests { use super::Forest; #[test] fn many_forest_has_size_2() { let forest: Forest<&str> = Forest::many(&[ vec!["1", "2"], vec!["2", "3"] ]); assert_eq!(2, forest.len()); } #[test] fn many_forest_is_not_empty() { let forest: Forest<&str> = Forest::many(&[ vec!["1", "2"], vec!["2", "3"] ]); assert_eq!(false, forest.is_empty()); } #[test] fn many_forest_into() { let forest: Forest<&str> = Forest::many(&[ vec!["1", "2"], vec!["2", "3"] ]); let expected = vec![ vec!["1", "2"], vec!["2", "3"], ]; assert_eq!( expected, Into::<Vec<_>>::into(forest.clone()) ); } #[test] fn unique_forest_into() { let forest: Forest<&str> = Forest::unique(&["1", "2"]); let expected = vec![ vec!["2"], vec!["1"], ]; assert_eq!( expected, Into::<Vec<_>>::into(forest.clone()) ); } } #[cfg(test)] mod random_tests { use super::Forest; #[test] fn product_of_two_forests_of_two() { let forest = Forest::unique(&["1-1", "1-2", "1-3"]) .product(Forest::unique(&["2-1", "2-2", "2-3"])); assert_eq!(9, forest.len()); let expected = Forest::many(&[ vec!["1-3", "2-1"], vec!["1-3", "2-2"], vec!["2-3", "1-2"], vec!["1-1", "2-2"], vec!["1-2", "2-2"], vec!["2-1", "1-2"], vec!["1-3", "2-3"], vec!["1-1", "2-1"], vec!["1-1", "2-3"], ]); assert_eq!( expected, forest ); } #[test] fn product_of_three_forests_of_three() { let forest = Forest::unique(&["1-1", "1-2", "1-3"]) .product(Forest::unique(&["2-1", "2-2", "2-3"])) .product(Forest::unique(&["3-1", "3-2", "3-3"])); assert_eq!(27, forest.len()); let expected = Forest::many(&[ vec!["1-1", "2-1", "3-1"], vec!["1-1", "2-1", "3-2"], vec!["1-1", "2-1", "3-3"], vec!["1-1", "2-2", "3-1"], vec!["1-1", "2-2", "3-2"], vec!["1-1", "2-2", "3-3"], vec!["1-1", "2-3", "3-1"], vec!["1-1", "2-3", "3-2"], vec!["1-1", "2-3", "3-3"], vec!["1-2", "2-1", "3-1"], vec!["1-2", "2-1", "3-2"], vec!["1-2", "2-1", "3-3"], vec!["1-2", "2-2", "3-1"], vec!["1-2", "2-2", "3-2"], vec!["1-2", "2-2", "3-3"], vec!["1-2", "2-3", "3-1"], vec!["1-2", "2-3", "3-2"], vec!["1-2", "2-3", "3-3"], vec!["1-3", "2-1", "3-1"], vec!["1-3", "2-1", "3-2"], vec!["1-3", "2-1", "3-3"], vec!["1-3", "2-2", "3-1"], vec!["1-3", "2-2", "3-2"], vec!["1-3", "2-2", "3-3"], vec!["1-3", "2-3", "3-1"], vec!["1-3", "2-3", "3-2"], vec!["1-3", "2-3", "3-3"], ]); assert_eq!( expected, forest ); } }
24.518421
88
0.43104
1640fead24abddf1a8ffc52d36a572dd5eeff484
1,884
h
C
engine/src/ECS/AddEntityMessage.h
targodan/gameProgramming
5c0b36bee271dca65636d0317324a2bb786613f0
[ "MIT" ]
1
2019-07-14T11:32:30.000Z
2019-07-14T11:32:30.000Z
engine/src/ECS/AddEntityMessage.h
targodan/gameProgramming
5c0b36bee271dca65636d0317324a2bb786613f0
[ "MIT" ]
null
null
null
engine/src/ECS/AddEntityMessage.h
targodan/gameProgramming
5c0b36bee271dca65636d0317324a2bb786613f0
[ "MIT" ]
null
null
null
#ifndef ADDENTITYMESSAGE_H #define ADDENTITYMESSAGE_H #include <memory> #include "../util/Array.h" #include "Message.h" #include "MessageHandler.h" #include "Entity.h" #include "Component.h" #define MESSAGE_NAME_ADD_ENTITY_MESSAGE "ADD_ENTITY_MESSAGE" namespace engine { namespace ECS { using engine::util::Array; class AddEntityMessage : public Message { protected: std::string name; Entity* newEntity; Array<std::shared_ptr<Component>> components; static messageId_t messageId; static bool messageRegistered; public: AddEntityMessage(const std::string& name, const Array<std::shared_ptr<Component>>& components, Entity* out_newEntity = nullptr) : Message(AddEntityMessage::messageId), name(name), newEntity(out_newEntity), components(components) {} AddEntityMessage(const AddEntityMessage& orig) : Message(orig), name(orig.name), newEntity(orig.newEntity), components(orig.components) {} AddEntityMessage(AddEntityMessage&& orig) : Message(std::move(orig)), name(std::move(orig.name)), newEntity(std::move(orig.newEntity)), components(std::move(orig.components)) {} const Array<std::shared_ptr<Component>>& getComponents() const { return components; } const std::string& getName() const { return name; } Entity* getNewEntityPtr() const { return newEntity; } static void setMessageId(messageId_t id); static messageId_t getMessageId(); static void registerMessageName(MessageHandler& handler); }; } } #endif /* ADDENTITYMESSAGE_H */
32.482759
155
0.595541
83e9e1017c3c30811ab6df5653f6e82ca6856781
306
rs
Rust
crate/network_session_model/src/lib.rs
Lighty0410/autexousious
99d142d8fdbf2076f3fd929f61b8140d47cf6b86
[ "Apache-2.0", "MIT" ]
41
2020-03-13T04:45:03.000Z
2022-01-17T18:13:09.000Z
crate/network_session_model/src/lib.rs
Lighty0410/autexousious
99d142d8fdbf2076f3fd929f61b8140d47cf6b86
[ "Apache-2.0", "MIT" ]
61
2016-06-19T01:28:12.000Z
2021-07-17T08:21:44.000Z
crate/network_session_model/src/lib.rs
Lighty0410/autexousious
99d142d8fdbf2076f3fd929f61b8140d47cf6b86
[ "Apache-2.0", "MIT" ]
3
2020-03-21T21:53:36.000Z
2021-01-30T01:10:55.000Z
#![deny(missing_debug_implementations, missing_docs)] // kcov-ignore //! Types used during network sessions. pub use crate::{ session_message_event::SessionMessageEvent, session_status_event::SessionStatusEvent, }; pub mod config; pub mod play; mod session_message_event; mod session_status_event;
21.857143
89
0.794118
bd34b0d2aaca2466ff1fda1b981fe7fc3336a3d2
1,104
asm
Assembly
programs/oeis/198/A198263.asm
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
1
2021-03-15T11:38:20.000Z
2021-03-15T11:38:20.000Z
programs/oeis/198/A198263.asm
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
null
null
null
programs/oeis/198/A198263.asm
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
null
null
null
; A198263: Ceiling(n*sqrt(8)). ; 0,3,6,9,12,15,17,20,23,26,29,32,34,37,40,43,46,49,51,54,57,60,63,66,68,71,74,77,80,83,85,88,91,94,97,99,102,105,108,111,114,116,119,122,125,128,131,133,136,139,142,145,148,150,153,156,159,162,165,167,170,173,176,179,182,184,187,190,193,196,198,201,204,207,210,213,215,218,221,224,227,230,232,235,238,241,244,247,249,252,255,258,261,264,266,269,272,275,278,281,283,286,289,292,295,297,300,303,306,309,312,314,317,320,323,326,329,331,334,337,340,343,346,348,351,354,357,360,363,365,368,371,374,377,380,382,385,388,391,394,396,399,402,405,408,411,413,416,419,422,425,428,430,433,436,439,442,445,447,450,453,456,459,462,464,467,470,473,476,479,481,484,487,490,493,495,498,501,504,507,510,512,515,518,521,524,527,529,532,535,538,541,544,546,549,552,555,558,561,563,566,569,572,575,577,580,583,586,589,592,594,597,600,603,606,609,611,614,617,620,623,626,628,631,634,637,640,643,645,648,651,654,657,660,662,665,668,671,674,676,679,682,685,688,691,693,696,699,702,705 mul $0,4 pow $0,2 mov $1,1 mov $2,4 lpb $0 sub $0,1 trn $0,$1 add $1,$2 lpe add $1,$2 sub $1,5 div $1,4
69
961
0.712862
208480a28b40282b201c88de9f0c8954a76d3d86
266
kt
Kotlin
app/src/main/java/com/zg/ccp/customviewassignment/viewholders/ProjectTaskViewHolder.kt
zawhtetnaing10/CustomViewAssignment
5efa3320b3b5a9b4777a83c58345035e5309512e
[ "MIT" ]
2
2020-11-08T16:07:19.000Z
2020-11-26T10:32:32.000Z
app/src/main/java/com/zg/ccp/customviewassignment/viewholders/ProjectTaskViewHolder.kt
zawhtetnaing10/CustomViewAssignment
5efa3320b3b5a9b4777a83c58345035e5309512e
[ "MIT" ]
null
null
null
app/src/main/java/com/zg/ccp/customviewassignment/viewholders/ProjectTaskViewHolder.kt
zawhtetnaing10/CustomViewAssignment
5efa3320b3b5a9b4777a83c58345035e5309512e
[ "MIT" ]
null
null
null
package com.zg.ccp.customviewassignment.viewholders import android.view.View import com.zg.ccp.customviewassignment.data.vos.TaskVO class ProjectTaskViewHolder(itemView: View) : BaseViewHolder<TaskVO>(itemView) { override fun bindData(data: TaskVO) { } }
24.181818
80
0.785714
930e02c260b9ab769dfb6fa46dc70d03ed195ef0
12,531
rs
Rust
src/options/parse.rs
Kilobyte22/dhcp_parser
cc95195d6ddd13ff3e9e0816a6dee00f3816d736
[ "MIT" ]
2
2016-09-05T10:53:09.000Z
2019-07-19T20:12:13.000Z
src/options/parse.rs
Kilobyte22/dhcp_parser
cc95195d6ddd13ff3e9e0816a6dee00f3816d736
[ "MIT" ]
3
2016-01-10T20:19:49.000Z
2019-07-17T06:26:12.000Z
src/options/parse.rs
Kilobyte22/dhcp_parser
cc95195d6ddd13ff3e9e0816a6dee00f3816d736
[ "MIT" ]
5
2015-10-27T15:11:23.000Z
2018-10-10T18:35:59.000Z
use options::{DhcpOption}; use options::DhcpOption::*; use {Result, Error}; use nom::{be_u8, be_u16, be_u32, be_i32, length_value, IResult, sized_buffer}; use std::borrow::{ToOwned}; use std::str; use std::convert::{From}; use std::net::{IpAddr, Ipv4Addr}; use num::{FromPrimitive}; pub fn parse(bytes: &[u8]) -> Result<Vec<DhcpOption>> { Ok(vec![]) } fn u32_to_ip(a: u32) -> IpAddr { IpAddr::V4(Ipv4Addr::from(a)) } fn many_ip_addrs(addrs: Vec<u32>) -> Vec<IpAddr> { addrs.into_iter().map(|a| u32_to_ip(a)).collect() } fn ip_addr_pairs(addrs: Vec<u32>) -> Vec<(IpAddr, IpAddr)> { let (ips, masks): (Vec<_>, Vec<_>) = addrs.into_iter() .map(|e| u32_to_ip(e)) .enumerate() .partition(|&(i, _)| i % 2 == 0); let ips: Vec<_> = ips.into_iter().map(|(_, v)| v).collect(); let masks: Vec<_> = masks.into_iter().map(|(_, v)| v).collect(); ips.into_iter() .zip(masks.into_iter()) .collect() } fn num_u16s(bytes: &[u8]) -> IResult<&[u8], u8> { match be_u8(bytes) { IResult::Done(i, o) => IResult::Done(i, o / 2), a => a, } } fn num_u32s(bytes: &[u8]) -> IResult<&[u8], u8> { match be_u8(bytes) { IResult::Done(i, o) => IResult::Done(i, o / 4), a => a, } } macro_rules! ip_pairs( ($name:ident, $tag:expr, $variant:expr) => ( named!($name<&[u8], DhcpOption>, chain!( tag!([$tag]) ~ addrs: length_value!(num_u32s, be_u32), || { $variant(ip_addr_pairs(addrs)) } ) ); ) ); /// A macro for the options that take the form /// /// [tag, length, ip_addr...] /// /// Since the only thing that really differs, is /// the tag and the Enum variant that is returned macro_rules! many_ips( ($name:ident, $tag:expr, $variant:expr) => ( named!($name<&[u8], DhcpOption>, chain!( tag!([$tag]) ~ addrs: length_value!(num_u32s, be_u32), || { $variant(many_ip_addrs(addrs)) } ) ); ) ); /// A macro for options that are of the form: /// /// [tag, length, somestring] /// /// , since I haven't figured out a way to /// easily construct a parser to take the length /// out of a byte of the input, and parse that /// many bytes into a string macro_rules! length_specific_string( ($name:ident, $tag:expr, $variant:expr) => ( named!($name<&[u8], DhcpOption>, chain!( tag!([$tag]) ~ s: map_res!(sized_buffer, str::from_utf8), || { $variant(s.to_owned()) } ) ); ) ); macro_rules! single_ip( ($name:ident, $tag:expr, $variant:expr) => ( named!($name<&[u8], DhcpOption>, chain!( tag!([$tag]) ~ _length: be_u8 ~ addr: be_u32, || { $variant(u32_to_ip(addr)) } ) ); ) ); macro_rules! bool( ($name:ident, $tag:expr, $variant:expr) => ( named!($name<&[u8], DhcpOption>, chain!( tag!([$tag]) ~ _length: be_u8 ~ val: be_u8, || { $variant(val == 1u8) } ) ); ) ); macro_rules! from_primitive( ($name:ident, $tag:expr, $variant:expr) => ( named!($name<&[u8], DhcpOption>, chain!( tag!([$tag]) ~ _l: be_u8 ~ data: map_opt!(be_u8, FromPrimitive::from_u8), || { $variant(data) } ) ); ) ); single_ip!(subnet_mask, 1u8, SubnetMask); named!(time_offset<&[u8], DhcpOption>, chain!( tag!([2u8]) ~ // length field, always 4 be_u8 ~ time: be_i32, || { TimeOffset(time) } ) ); many_ips!(router, 3u8, Router); many_ips!(time_server, 4u8, TimeServer); many_ips!(name_server, 5u8, NameServer); many_ips!(domain_name_server, 6u8, DomainNameServer); many_ips!(log_server, 7u8, LogServer); many_ips!(cookie_server, 8u8, CookieServer); many_ips!(lpr_server, 9u8, LprServer); many_ips!(impress_server, 10u8, ImpressServer); many_ips!(resource_loc_server, 11u8, ResourceLocationServer); length_specific_string!(hostname, 12u8, HostName); named!(boot_file_size<&[u8], DhcpOption>, chain!( tag!([13u8]) ~ _length: be_u8 ~ s: be_u16, || { BootFileSize(s) } ) ); length_specific_string!(merit_dump_file, 14u8, MeritDumpFile); length_specific_string!(domain_name, 15u8, DomainName); single_ip!(swap_server, 16u8, SwapServer); length_specific_string!(root_path, 17u8, RootPath); length_specific_string!(extensions_path, 18u8, ExtensionsPath); // COLLECT ALL OF THE ABOVE INTO ONE PARSER named!(vendor_extensions_rfc1497<&[u8], DhcpOption>, alt!( chain!(tag!([0u8]), || { Pad } ) | chain!( tag!([255u8]), || { End } ) | subnet_mask | time_offset | router | time_server | name_server // 5 | domain_name_server | log_server | cookie_server | lpr_server | impress_server // 10 | resource_loc_server | hostname | boot_file_size | merit_dump_file | domain_name // 15 | swap_server | root_path | extensions_path ) ); bool!(ip_forwarding, 19u8, IPForwarding); bool!(non_source_local_routing, 20u8, NonLocalSourceRouting); // TODO /* named!(policy_filter<&[u8], DhcpOption>, */ /* chain!( */ /* tag!([21u8]) ~ */ /* s: map!(sized_buffer, ip_addr_pairs), */ /* || { PolicyFilter(s) } */ /* ) */ /* ); */ named!(max_datagram_reassembly_size<&[u8], DhcpOption>, chain!( tag!([22u8]) ~ _len: be_u8 ~ aa: be_u16, || { MaxDatagramReassemblySize(aa) } ) ); named!(default_ip_ttl<&[u8], DhcpOption>, chain!( tag!([23u8]) ~ _length: be_u8 ~ ttl: be_u8, || { DefaultIpTtl(ttl) } ) ); named!(path_mtu_aging_timeout<&[u8], DhcpOption>, chain!( tag!([24u8]) ~ _length: be_u8 ~ timeout: be_u32, || { PathMtuAgingTimeout(timeout) } ) ); named!(path_mtu_plateau_table<&[u8], DhcpOption>, chain!( tag!([25u8]) ~ sizes: length_value!(num_u16s, be_u16), || { PathMtuPlateauTable(sizes) } ) ); // COLLECT named!(ip_layer_parameters_per_host<&[u8], DhcpOption>, alt!( ip_forwarding | non_source_local_routing // 20 /* | policy_filter //TODO */ | max_datagram_reassembly_size | default_ip_ttl | path_mtu_aging_timeout | path_mtu_plateau_table // 25 ) ); named!(interface_mtu<&[u8], DhcpOption>, chain!( tag!([26u8]) ~ _length: be_u8 ~ mtu: be_u16, || { InterfaceMtu(mtu) } ) ); bool!(all_subnets_are_local, 27u8, AllSubnetsAreLocal); single_ip!(broadcast_address, 28u8, BroadcastAddress); bool!(perform_mask_discovery, 29u8, PerformMaskDiscovery); bool!(mask_supplier, 30u8, MaskSupplier); bool!(perform_router_discovery, 31u8, PerformRouterDiscovery); single_ip!(router_solicitation_address, 32u8, RouterSolicitationAddress); ip_pairs!(static_route, 33u8, StaticRoute); // COLLECT named!(ip_layer_parameters_per_interface<&[u8], DhcpOption>, alt!( interface_mtu | all_subnets_are_local | broadcast_address | perform_mask_discovery | mask_supplier // 30 | perform_router_discovery | router_solicitation_address | static_route ) ); bool!(trailer_encapsulation, 34u8, TrailerEncapsulation); named!(arp_cache_timeout<&[u8], DhcpOption>, chain!( tag!([35u8]) ~ _length: be_u8 ~ timeout: be_u32, || { ArpCacheTimeout(timeout) } ) ); bool!(ethernet_encapsulation, 36u8, EthernetEncapsulation); // COLLECT named!(link_layer_parameters_per_interface<&[u8], DhcpOption>, alt!( trailer_encapsulation | arp_cache_timeout // 35 | ethernet_encapsulation ) ); named!(tcp_default_ttl<&[u8], DhcpOption>, chain!( tag!([37u8]) ~ _length: be_u8 ~ ttl: be_u8, || { TcpDefaultTtl(ttl) } ) ); named!(tcp_keepalive_interval<&[u8], DhcpOption>, chain!( tag!([38u8]) ~ _length: be_u8 ~ interval: be_u32, || { TcpKeepaliveInterval(interval) } ) ); bool!(tcp_keepalive_garbage, 39u8, TcpKeepaliveGarbage); // COLLECT named!(tcp_parameters<&[u8], DhcpOption>, alt!( tcp_default_ttl | tcp_keepalive_interval | tcp_keepalive_garbage ) ); length_specific_string!(nis_domain, 40u8, NisDomain); many_ips!(network_information_servers, 41u8, NetworkInformationServers); many_ips!(ntp_servers, 42u8, NtpServers); named!(vendor_extensions<&[u8], DhcpOption>, chain!( tag!([43u8]) ~ bytes: length_value!(be_u8, be_u8), || { VendorExtensions(bytes) } ) ); many_ips!(net_bios_name_servers, 44u8, NetBiosNameServers); many_ips!(net_bios_datagram_distribution_server, 45u8, NetBiosDatagramDistributionServer); named!(net_bios_node_type<&[u8], DhcpOption>, chain!( tag!([46u8]) ~ _length: be_u8 ~ data: map_opt!(be_u8, FromPrimitive::from_u8), || { NetBiosNodeType(data) } ) ); length_specific_string!(net_bios_scope, 47u8, NetBiosScope); many_ips!(xfont_server, 48u8, XFontServer); many_ips!(xdisplay_manager, 49u8, XDisplayManager); // COLLECT named!(application_and_service_parameters<&[u8], DhcpOption>, alt!( nis_domain // 40 | network_information_servers | ntp_servers | vendor_extensions | net_bios_name_servers | net_bios_datagram_distribution_server // 45 | net_bios_node_type | net_bios_scope | xfont_server | xdisplay_manager ) ); single_ip!(requested_ip_address, 50u8, RequestedIpAddress); named!(ip_address_lease_time<&[u8], DhcpOption>, chain!( tag!([51u8]) ~ _length: be_u8 ~ time: be_u32, || { IpAddressLeaseTime(time) } ) ); from_primitive!(option_overload, 52u8, OptionOverload); from_primitive!(message_type, 53u8, MessageType); single_ip!(server_identifier, 54u8, ServerIdentifier); named!(param_request_list<&[u8], DhcpOption>, chain!( tag!([55u8]) ~ data: length_value!(be_u8, be_u8), || { ParamRequestList(data) } ) ); length_specific_string!(message, 56u8, Message); named!(max_message_size<&[u8], DhcpOption>, chain!( tag!([57u8]) ~ _l: be_u8 ~ size_: be_u16, || { MaxMessageSize(size_) } ) ); // COLLECT named!(dhcp_extensions<&[u8], DhcpOption>, alt!( requested_ip_address // 50 | ip_address_lease_time | option_overload | message_type | server_identifier | param_request_list // 55 | message /* | max_message_size */ /* | renewal_time_value */ /* | rebinding_time_value */ /* | class_identifier // 60 */ /* | client_identifier */ ) ); // Main parser named!(dhcp_option(&'a [u8]) -> DhcpOption, alt!( vendor_extensions_rfc1497 | ip_layer_parameters_per_host | ip_layer_parameters_per_interface | link_layer_parameters_per_interface | tcp_parameters | application_and_service_parameters | dhcp_extensions ) ); #[cfg(test)] mod tests { use options::DhcpOption::{Router}; use super::{router}; use nom::{IResult}; use std::net::{IpAddr, Ipv4Addr}; #[test] fn test_many_ip_addresses() { let ips = vec![3u8, 8, 127, 0, 0, 1, 192, 168, 1, 1, ]; match router(&ips) { IResult::Done(i, o) => { if i.len() > 0 { panic!("Remaining input was {:?}", i); } assert_eq!(o, Router(vec![IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1))])); }, e => panic!("Result was {:?}", e), } } }
27.360262
90
0.562365
08808a60498b8f1fe770d4890bef66eaa589836e
1,191
go
Go
models/ledger.go
fanda-india/fanda-api
b14a3f9c6a03e947fc46f552894125da2ec415b4
[ "MIT" ]
null
null
null
models/ledger.go
fanda-india/fanda-api
b14a3f9c6a03e947fc46f552894125da2ec415b4
[ "MIT" ]
null
null
null
models/ledger.go
fanda-india/fanda-api
b14a3f9c6a03e947fc46f552894125da2ec415b4
[ "MIT" ]
null
null
null
package models import "time" // Ledger db model type Ledger struct { ID ID `gorm:"primaryKey;autoIncrement;not null" json:"id,omitempty"` // Code string `gorm:"size:16;index:idx_ledgers_code,unique" json:"code,omitempty"` Name string `gorm:"size:25;index:idx_ledgers_name,unique" json:"name,omitempty"` Description *string `gorm:"size:255" json:"description,omitempty"` GroupID *ID `gorm:"default:NULL" json:"groupId,omitempty"` Group *LedgerGroup `gorm:"foreignKey:GroupID;constraint:OnUpdate:CASCADE,OnDelete:NO ACTION" json:"group,omitempty"` LedgerType byte `gorm:"default:NULL" json:"ledgerType,omitempty"` IsSystem *bool `gorm:"default:false" json:"isSystem,omitempty"` OrgID OrgID `gorm:"index:idx_ledgers_code,unique;index:idx_ledgers_name,unique" json:"orgId,omitempty"` Organization *Organization `gorm:"foreignKey:OrgID;constraint:OnUpdate:CASCADE,OnDelete:NO ACTION" json:"-"` CreatedAt time.Time `json:"createdAt,omitempty"` UpdatedAt time.Time `json:"updatedAt,omitempty"` IsActive *bool `gorm:"default:true" json:"isActive,omitempty"` }
56.714286
125
0.693535
af1fd8fb03e8024c644fedba6f4b0471e1d8684f
1,691
rb
Ruby
lib/gitlab/diff/custom_diff.rb
nowkoai/test
7aca51cce41acd7ec4c393d1bb1185a4a2ca1d07
[ "MIT" ]
null
null
null
lib/gitlab/diff/custom_diff.rb
nowkoai/test
7aca51cce41acd7ec4c393d1bb1185a4a2ca1d07
[ "MIT" ]
2
2020-10-03T01:57:44.000Z
2020-11-05T15:14:35.000Z
lib/gitlab/diff/custom_diff.rb
nowkoai/test
7aca51cce41acd7ec4c393d1bb1185a4a2ca1d07
[ "MIT" ]
null
null
null
# frozen_string_literal: true module Gitlab module Diff module CustomDiff class << self def preprocess_before_diff(path, old_blob, new_blob) return unless path.ends_with? '.ipynb' transformed_diff(old_blob&.data, new_blob&.data)&.tap do transformed_for_diff(new_blob, old_blob) Gitlab::AppLogger.info({ message: 'IPYNB_DIFF_GENERATED' }) end rescue IpynbDiff::InvalidNotebookError, IpynbDiff::InvalidTokenError => e Gitlab::ErrorTracking.log_exception(e) nil end def transformed_diff(before, after) transformed_diff = IpynbDiff.diff(before, after, raise_if_invalid_nb: true, diffy_opts: { include_diff_info: true }).to_s(:text) strip_diff_frontmatter(transformed_diff) end def transformed_blob_language(blob) 'md' if transformed_for_diff?(blob) end def transformed_blob_data(blob) if transformed_for_diff?(blob) IpynbDiff.transform(blob.data, raise_errors: true, include_frontmatter: false) end end def strip_diff_frontmatter(diff_content) diff_content.scan(/.*\n/)[2..]&.join('') if diff_content.present? end def blobs_with_transformed_diffs @blobs_with_transformed_diffs ||= {} end def transformed_for_diff?(blob) blobs_with_transformed_diffs[blob] end def transformed_for_diff(*blobs) blobs.each do |b| blobs_with_transformed_diffs[b] = true if b end end end end end end
29.666667
90
0.615612
b49d7cb8f92f31b74cb8275452749bd608c4586c
245
sql
SQL
back/src/main/resources/schema.sql
kdelfour/spring-angularjs-project
4d32a6b110e07c22f79d66b18dbb7cbe60748f02
[ "MIT" ]
null
null
null
back/src/main/resources/schema.sql
kdelfour/spring-angularjs-project
4d32a6b110e07c22f79d66b18dbb7cbe60748f02
[ "MIT" ]
null
null
null
back/src/main/resources/schema.sql
kdelfour/spring-angularjs-project
4d32a6b110e07c22f79d66b18dbb7cbe60748f02
[ "MIT" ]
null
null
null
CREATE TABLE RULE ( ID INTEGER GENERATED BY DEFAULT AS IDENTITY, TITLE VARCHAR(50) NOT NULL, DESCRIPTION VARCHAR(200), CODE VARCHAR(1024) ); INSERT INTO RULE (TITLE,DESCRIPTION) VALUES (('R1','R1 DESC'),('R2','R2 DESC'), ('R3','R3 DESC'));
30.625
98
0.689796
3176ed3f637edf2c07c35e5e7442bf391497972e
486
sql
SQL
resources/sql/autopatches/20140130.dash.2.panel.sql
Rob--W/phabricator
8272f3f7fa92179931a2fc7ca33909492cfc644d
[ "Apache-2.0" ]
8,840
2015-01-02T03:04:43.000Z
2022-03-29T05:24:18.000Z
resources/sql/autopatches/20140130.dash.2.panel.sql
Rob--W/phabricator
8272f3f7fa92179931a2fc7ca33909492cfc644d
[ "Apache-2.0" ]
73
2015-01-06T11:05:32.000Z
2021-12-02T17:50:10.000Z
resources/sql/autopatches/20140130.dash.2.panel.sql
Rob--W/phabricator
8272f3f7fa92179931a2fc7ca33909492cfc644d
[ "Apache-2.0" ]
1,335
2015-01-04T03:15:40.000Z
2022-03-30T23:34:27.000Z
CREATE TABLE {$NAMESPACE}_dashboard.dashboard_panel ( id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, phid VARCHAR(64) NOT NULL COLLATE utf8_bin, name VARCHAR(255) NOT NULL, viewPolicy VARCHAR(64) NOT NULL COLLATE utf8_bin, editPolicy VARCHAR(64) NOT NULL COLLATE utf8_bin, properties LONGTEXT NOT NULL COLLATE utf8_bin, dateCreated INT UNSIGNED NOT NULL, dateModified INT UNSIGNED NOT NULL, UNIQUE KEY `key_phid` (phid) ) ENGINE=InnoDB, COLLATE=utf8_general_ci;
40.5
54
0.783951
c422863eceb1159d377014a5b863f8b0d50ab68b
12,388
h
C
library/openxlsx/implementation/headers/XLDocument_Impl.h
sezamin/OpenXLSX
9a44c48a3cda934e9b287c015f094a002fd67d1f
[ "BSD-3-Clause" ]
1
2020-04-25T01:40:41.000Z
2020-04-25T01:40:41.000Z
library/openxlsx/implementation/headers/XLDocument_Impl.h
sezamin/OpenXLSX
9a44c48a3cda934e9b287c015f094a002fd67d1f
[ "BSD-3-Clause" ]
null
null
null
library/openxlsx/implementation/headers/XLDocument_Impl.h
sezamin/OpenXLSX
9a44c48a3cda934e9b287c015f094a002fd67d1f
[ "BSD-3-Clause" ]
1
2020-06-12T03:52:04.000Z
2020-06-12T03:52:04.000Z
/* ____ ____ ___ ____ ____ ____ ___ 6MMMMb `MM( )M' `MM' 6MMMMb\`MM( )M' 8P Y8 `MM. d' MM 6M' ` `MM. d' 6M Mb __ ____ ____ ___ __ `MM. d' MM MM `MM. d' MM MM `M6MMMMb 6MMMMb `MM 6MMb `MM. d' MM YM. `MM. d' MM MM MM' `Mb 6M' `Mb MMM9 `Mb `MMd MM YMMMMb `MMd MM MM MM MM MM MM MM' MM dMM. MM `Mb dMM. MM MM MM MM MMMMMMMM MM MM d'`MM. MM MM d'`MM. YM M9 MM MM MM MM MM d' `MM. MM MM d' `MM. 8b d8 MM. ,M9 YM d9 MM MM d' `MM. MM / L ,M9 d' `MM. YMMMM9 MMYMMM9 YMMMM9 _MM_ _MM_M(_ _)MM_ _MMMMMMM MYMMMM9 _M(_ _)MM_ MM MM _MM_ Copyright (c) 2018, Kenneth Troldal Balslev All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of the author nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef OPENXLSX_IMPL_XLDOCUMENT_H #define OPENXLSX_IMPL_XLDOCUMENT_H // ===== Standard Library Includes ===== // #include <string> #include <map> #include <vector> #include <iostream> #include <fstream> // ===== OpenXLSX Includes ===== // #include "XLAppProperties_Impl.h" #include "XLCoreProperties_Impl.h" #include "XLWorkbook_Impl.h" #include "XLEnums_impl.h" #include "XLRelationships_Impl.h" #include "XLException.h" #include "XLXml_Impl.h" #include "XLDefinitions.h" #include <Zippy.h> namespace OpenXLSX::Impl { class XLContentItem; class XLContentTypes; //====================================================================================================================== //========== XLDocument Class ========================================================================================== //====================================================================================================================== /** * @brief This class encapsulates the concept of an excel file. It is different from the XLWorkbook, in that an * XLDocument holds an XLWorkbook together with its metadata, as well as methods for opening, * closing and saving the document.\n<b><em>The XLDocument is the entrypoint for clients * using the RapidXLSX library.</em></b> */ class XLDocument { //---------------------------------------------------------------------------------------------------------------------- // Friends //---------------------------------------------------------------------------------------------------------------------- friend class XLAbstractXMLFile; friend class XLWorkbook; friend class XLSheet; //---------------------------------------------------------------------------------------------------------------------- // Public Member Functions //---------------------------------------------------------------------------------------------------------------------- public: /** * @brief Constructor. The default constructor with no arguments. */ explicit XLDocument(); /** * @brief Constructor. An alternative constructor, taking the path to the .xlsx file as an argument. * @param docPath A std::string with the path to the .xlsx file. */ explicit XLDocument(const std::string& docPath); /** * @brief Copy constructor * @param other The object to copy * @note Copy constructor explicitly deleted. * @todo Consider implementing this, as it may make sense to copy the entire document, although it may not make * sense to copy individual elements (e.g. the XLWorkbook object). Alternatively, implement a 'Clone' function. */ XLDocument(const XLDocument& other) = delete; /** * @brief Destructor */ virtual ~XLDocument(); /** * @brief Open the .xlsx file with the given path * @param fileName The path of the .xlsx file to open * @todo Consider opening the zipped files as streams, instead of unpacking to a temporary folder */ void OpenDocument(const std::string& fileName); /** * @brief Create a new .xlsx file with the given name. * @param fileName The path of the new .xlsx file. */ void CreateDocument(const std::string& fileName); /** * @brief Close the current document */ void CloseDocument(); /** * @brief Save the current document using the current filename, overwriting the existing file. * @return true if successful; otherwise false. */ bool SaveDocument(); /** * @brief Save the document with a new name. If a file exists with that name, it will be overwritten. * @param fileName The path of the file * @return true if successful; otherwise false. */ bool SaveDocumentAs(const std::string& fileName); /** * @brief Get the filename of the current document, e.g. "spreadsheet.xlsx". * @return A std::string with the filename. */ const std::string& DocumentName() const; /** * @brief Get the full path of the current document, e.g. "drive/blah/spreadsheet.xlsx" * @return A std::string with the path. */ const std::string& DocumentPath() const; /** * @brief Get the underlying workbook object. * @return A pointer to the XLWorkbook object */ XLWorkbook* Workbook(); /** * @brief Get the underlying workbook object, as a const object. * @return A const pointer to the XLWorkbook object. */ const XLWorkbook* Workbook() const; /** * @brief Get the requested document property. * @param theProperty The name of the property to get. * @return The property as a string */ std::string GetProperty(XLProperty theProperty) const; /** * @brief Set a property * @param theProperty The property to set. * @param value The value of the property, as a string */ void SetProperty(XLProperty theProperty, const std::string& value); /** * @brief Delete the property from the document * @param propertyName The property to delete from the document */ void DeleteProperty(XLProperty theProperty); //---------------------------------------------------------------------------------------------------------------------- // Protected Member Functions //---------------------------------------------------------------------------------------------------------------------- protected: /** * @brief Method for adding a new (XML) file to the .xlsx package. * @param path The relative path of the new file. * @param content The contents (XML data) of the new file. */ void AddOrReplaceXMLFile(const std::string& path, const std::string& content); /** * @brief Get an XML file from the .xlsx archive. * @param path The relative path of the file. * @return A std::string with the content of the file */ std::string GetXMLFile(const std::string& path); /** * @brief Delete a file from the .xlsx archive. * @param path The path of the file to delete. */ void DeleteXMLFile(const std::string& path); /** * @brief Get the xml node in the app.xml file, for the sheet name. * @param sheetName A std::string with the name of the sheet. * @return A pointer to the XMLNode object. */ XMLNode SheetNameNode(const std::string& sheetName); /** * @brief Get the content item element in the contenttypes.xml file. * @param path A std::string with the relative path to the file in question. * @return A pointer to the XLContentItem. */ XLContentItem ContentItem(const std::string& path); /** * @brief * @param contentPath * @param contentType * @return */ XLContentItem AddContentItem(const std::string& contentPath, XLContentType contentType); /** * @brief * @param item */ void DeleteContentItem(XLContentItem& item); /** * @brief Getter method for the App Properties object. * @return A pointer to the XLDocAppProperties object. */ XLAppProperties* AppProperties(); /** * @brief Getter method for the App Properties object. * @return A pointer to the const XLDocAppProperties object. */ const XLAppProperties* AppProperties() const; /** * @brief Getter method for the Core Properties object. * @return A pointer to the XLDocCoreProperties object. */ XLCoreProperties* CoreProperties(); /** * @brief Getter method for the Core Properties object. * @return A pointer to the const XLDocCoreProperties object. */ const XLCoreProperties* CoreProperties() const; private: template<typename T> typename std::enable_if_t<std::is_base_of<XLAbstractXMLFile, T>::value, std::unique_ptr<T>> CreateItem(const std::string& target) { if (!m_documentRelationships->TargetExists(target)) throw XLException("Target does not exist!"); return std::make_unique<T>(*this, m_documentRelationships->RelationshipByTarget(target).Target().value()); } //---------------------------------------------------------------------------------------------------------------------- // Private Member Variables //---------------------------------------------------------------------------------------------------------------------- private: std::string m_filePath; /**< The path to the original file*/ std::unique_ptr<XLRelationships> m_documentRelationships; /**< A pointer to the document relationships object*/ std::unique_ptr<XLContentTypes> m_contentTypes; /**< A pointer to the content types object*/ std::unique_ptr<XLAppProperties> m_docAppProperties; /**< A pointer to the App properties object */ std::unique_ptr<XLCoreProperties> m_docCoreProperties; /**< A pointer to the Core properties object*/ std::unique_ptr<XLWorkbook> m_workbook; /**< A pointer to the workbook object */ std::unique_ptr<Zippy::ZipArchive> m_archive; /**< */ }; } // namespace OpenXLSX::Impl #endif //OPENXLSX_IMPL_XLDOCUMENT_H
39.705128
128
0.542138
8ab928e461865fa511c336723c790fdcfd96989a
1,361
kt
Kotlin
app/src/main/java/ru/kartsev/dmitry/cinemadetails/mvvm/view/helper/ZoomOutPageTransformer.kt
Jaguarhl/MoviesDetails
d80929fcb461249c074dfff73ce7156ee91ff074
[ "Apache-2.0" ]
null
null
null
app/src/main/java/ru/kartsev/dmitry/cinemadetails/mvvm/view/helper/ZoomOutPageTransformer.kt
Jaguarhl/MoviesDetails
d80929fcb461249c074dfff73ce7156ee91ff074
[ "Apache-2.0" ]
null
null
null
app/src/main/java/ru/kartsev/dmitry/cinemadetails/mvvm/view/helper/ZoomOutPageTransformer.kt
Jaguarhl/MoviesDetails
d80929fcb461249c074dfff73ce7156ee91ff074
[ "Apache-2.0" ]
null
null
null
package ru.kartsev.dmitry.cinemadetails.mvvm.view.helper import android.view.View import androidx.viewpager.widget.ViewPager import kotlin.math.abs import kotlin.math.max private const val MIN_SCALE = 0.85f private const val MIN_ALPHA = 0.5f class ZoomOutPageTransformer : ViewPager.PageTransformer { override fun transformPage(view: View, position: Float) { view.apply { val pageWidth = width val pageHeight = height when { position < -1 -> { alpha = 0f } position <= 1 -> { val scaleFactor = max(MIN_SCALE, 1 - abs(position)) val vertMargin = pageHeight * (1 - scaleFactor) / 2 val horzMargin = pageWidth * (1 - scaleFactor) / 2 translationX = if (position < 0) { horzMargin - vertMargin / 2 } else { horzMargin + vertMargin / 2 } scaleX = scaleFactor scaleY = scaleFactor alpha = (MIN_ALPHA + (((scaleFactor - MIN_SCALE) / (1 - MIN_SCALE)) * (1 - MIN_ALPHA))) } else -> { alpha = 0f } } } } }
31.651163
90
0.47612
ab2c86a6303d1792d29c17e3dfe14bd3592c86ef
275
asm
Assembly
libsrc/games/bit_open.asm
meesokim/z88dk
5763c7778f19a71d936b3200374059d267066bb2
[ "ClArtistic" ]
null
null
null
libsrc/games/bit_open.asm
meesokim/z88dk
5763c7778f19a71d936b3200374059d267066bb2
[ "ClArtistic" ]
null
null
null
libsrc/games/bit_open.asm
meesokim/z88dk
5763c7778f19a71d936b3200374059d267066bb2
[ "ClArtistic" ]
null
null
null
; $Id: bit_open.asm,v 1.2 2015/01/19 01:32:44 pauloscustodio Exp $ ; ; Generic 1 bit sound functions ; ; void bit_open(); ; ; Stefano Bodrato - 2001..2013 ; INCLUDE "games/games.inc" PUBLIC bit_open EXTERN snd_tick .bit_open ld a,(snd_tick) ret
15.277778
66
0.64
66a7dbcf6bda03f030f530f0fe13b3ee98d40fbc
6,888
sql
SQL
misc/drop_many.sql
sql-diaries/plsql-chrestomathy
a346b82143cf15819547c8be23c66953fcc7561e
[ "MIT" ]
1
2018-02-08T11:58:05.000Z
2018-02-08T11:58:05.000Z
misc/drop_many.sql
sql-diaries/plsql-chrestomathy
a346b82143cf15819547c8be23c66953fcc7561e
[ "MIT" ]
null
null
null
misc/drop_many.sql
sql-diaries/plsql-chrestomathy
a346b82143cf15819547c8be23c66953fcc7561e
[ "MIT" ]
1
2015-10-27T05:22:18.000Z
2015-10-27T05:22:18.000Z
-------------------------------------------------------------------------------- -- -- A PL/SQL chrestomathy -- -- Module: misc -- Submodule: drop_many -- Purpose: dropping many interrelated objects -- -- Copyright (c) 2014-5 Roberto Reale -- -- Permission is hereby granted, free of charge, to any person obtaining a -- copy of this software and associated documentation files (the "Software"), -- to deal in the Software without restriction, including without limitation -- the rights to use, copy, modify, merge, publish, distribute, sublicense, -- and/or sell copies of the Software, and to permit persons to whom the -- Software is furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER -- DEALINGS IN THE SOFTWARE. -- -------------------------------------------------------------------------------- -- Note: We must have been granted the ALTER ANY TABLE, DROP ANY TABLE, -- CREATE ANY INDEX and DROP ANY INDEX privileges. CREATE OR REPLACE PACKAGE DROP_MANY AS PROCEDURE DROP_CONSTRAINTS( p_schema IN VARCHAR2, p_table_expr IN VARCHAR2, p_dry_run IN BOOLEAN DEFAULT FALSE); PROCEDURE DROP_TABLES( p_schema IN VARCHAR2, p_table_expr IN VARCHAR2, p_purge IN BOOLEAN DEFAULT FALSE, p_dry_run IN BOOLEAN DEFAULT FALSE); END DROP_MANY; / CREATE OR REPLACE PACKAGE BODY DROP_MANY AS PROCEDURE DISABLE_CONSTRAINTS( p_schema IN VARCHAR2, p_table_expr IN VARCHAR2, p_dry_run IN BOOLEAN DEFAULT FALSE) IS NO_SUCH_CONSTRAINT EXCEPTION; PRAGMA EXCEPTION_INIT(NO_SUCH_CONSTRAINT, -2431); TYPE l_constr_refcur_t IS REF CURSOR; l_constr_refcur l_constr_refcur_t; l_dml_stmt VARCHAR2(4000); l_ddl_stmt VARCHAR2(4000); l_table_name VARCHAR2(30); l_constraint_name VARCHAR2(30); BEGIN l_dml_stmt := 'SELECT c.table_name, c.constraint_name '|| 'FROM DBA_CONSTRAINTS c JOIN DBA_TABLES t ON c.table_name = t.table_name '|| 'WHERE t.owner = '''||p_schema||''' AND t.table_name LIKE '''||p_table_expr||''' '|| 'AND c.status = ''ENABLED''' || 'ORDER BY c.constraint_type DESC'; OPEN l_constr_refcur FOR l_dml_stmt; LOOP FETCH l_constr_refcur INTO l_table_name, l_constraint_name; EXIT WHEN l_constr_refcur%NOTFOUND; l_ddl_stmt := 'ALTER TABLE "'||p_schema||'"."'||l_table_name||'" DISABLE CONSTRAINT "'||l_constraint_name||'"'; DBMS_OUTPUT.PUT_LINE(l_ddl_stmt); IF NOT p_dry_run THEN DBMS_UTILITY.EXEC_DDL_STATEMENT(l_ddl_stmt); END IF; END LOOP; CLOSE l_constr_refcur; EXCEPTION WHEN NO_SUCH_CONSTRAINT THEN -- ORA-02431: cannot disable constraint - no such constraint NULL; END DISABLE_CONSTRAINTS; PROCEDURE DROP_CONSTRAINTS( p_schema IN VARCHAR2, p_table_expr IN VARCHAR2, p_dry_run IN BOOLEAN DEFAULT FALSE) IS NO_SUCH_CONSTRAINT EXCEPTION; PRAGMA EXCEPTION_INIT(NO_SUCH_CONSTRAINT, -2443); TYPE l_constr_refcur_t IS REF CURSOR; l_constr_refcur l_constr_refcur_t; l_dml_stmt VARCHAR2(4000); l_ddl_stmt VARCHAR2(4000); l_table_name VARCHAR2(30); l_constraint_name VARCHAR2(30); BEGIN l_dml_stmt := 'SELECT c.table_name, c.constraint_name '|| 'FROM DBA_CONSTRAINTS c JOIN DBA_TABLES t ON c.table_name = t.table_name '|| 'WHERE t.owner = '''||p_schema||''' AND t.table_name LIKE '''||p_table_expr||''' '|| 'ORDER BY c.constraint_type DESC'; OPEN l_constr_refcur FOR l_dml_stmt; LOOP FETCH l_constr_refcur INTO l_table_name, l_constraint_name; EXIT WHEN l_constr_refcur%NOTFOUND; l_ddl_stmt := 'ALTER TABLE "'||p_schema||'"."'||l_table_name||'" DROP CONSTRAINT "'||l_constraint_name||'"'; DBMS_OUTPUT.PUT_LINE(l_ddl_stmt); IF NOT p_dry_run THEN DBMS_UTILITY.EXEC_DDL_STATEMENT(l_ddl_stmt); END IF; END LOOP; CLOSE l_constr_refcur; EXCEPTION WHEN NO_SUCH_CONSTRAINT THEN -- ORA-02443: Cannot drop constraint - nonexistent constraint NULL; END DROP_CONSTRAINTS; PROCEDURE DROP_TABLES( p_schema IN VARCHAR2, p_table_expr IN VARCHAR2, p_purge IN BOOLEAN DEFAULT FALSE, p_dry_run IN BOOLEAN DEFAULT FALSE) IS TYPE l_table_refcur_t IS REF CURSOR; l_table_refcur l_table_refcur_t; l_dml_stmt VARCHAR2(4000); l_ddl_stmt VARCHAR2(4000); l_table_name VARCHAR2(30); l_purge_clause VARCHAR2(5) := ''; BEGIN DISABLE_CONSTRAINTS(p_schema, p_table_expr, p_dry_run); DROP_CONSTRAINTS(p_schema, p_table_expr, p_dry_run); IF p_purge THEN l_purge_clause := 'PURGE'; END IF; l_dml_stmt := 'SELECT table_name FROM DBA_TABLES '|| 'WHERE owner = '''||p_schema||''' AND table_name LIKE '''||p_table_expr||''''; OPEN l_table_refcur FOR l_dml_stmt; LOOP FETCH l_table_refcur INTO l_table_name; EXIT WHEN l_table_refcur%NOTFOUND; l_ddl_stmt := 'DROP TABLE "'||p_schema||'"."'||l_table_name||'" '||l_purge_clause; DBMS_OUTPUT.PUT_LINE(l_ddl_stmt); IF NOT p_dry_run THEN DBMS_UTILITY.EXEC_DDL_STATEMENT(l_ddl_stmt); END IF; END LOOP; CLOSE l_table_refcur; END DROP_TABLES; END DROP_MANY; / -- ex: ts=4 sw=4 et filetype=sql
33.115385
123
0.581301
4754b79049dbb40ff9d95a959530df3022409f35
28,235
html
HTML
index.html
TigranMelkonian/WebPage
36254489dccc25d5c9ef0b0b6ca7fb868ed659ad
[ "CC-BY-3.0" ]
null
null
null
index.html
TigranMelkonian/WebPage
36254489dccc25d5c9ef0b0b6ca7fb868ed659ad
[ "CC-BY-3.0" ]
null
null
null
index.html
TigranMelkonian/WebPage
36254489dccc25d5c9ef0b0b6ca7fb868ed659ad
[ "CC-BY-3.0" ]
null
null
null
<!DOCTYPE HTML> <html> <head> <title>Tigran Melkonian</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> <link rel="stylesheet" href="assets/css/main.css" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway"> <link rel="icon" type="image/ico" href="assets/www/favicon.ico"> <noscript> <link rel="stylesheet" href="assets/css/noscript.css" /> </noscript> </head> <body class="is-preload"> <!-- Sidebar --> <section id="sidebar"> <div class="inner"> <nav> <ul> <li><a href="#about">About Me</a></li> <li><a href="#experience">Experience</a></li> <li><a href="#education">Education</a></li> <li><a href="#projects">Projects</a></li> <li><a href="contact.html">Get in touch</a></li> </ul> </nav> </div> </section> <!-- Wrapper --> <div id="wrapper"> <!-- Intro --> <section id="intro" class="wrapper style1 fullscreen fade-up"> <div class="inner"> <h1 style="color:white">Welcome!</h1> </div> </section> <!-- About --> <section id="about" class="wrapper style2 spotlights" style="padding:64px 16px;"> <center> <h3>ABOUT ME</h3> </center> <center><img src="images/avatar.jpg" style="width:35%;border-radius: 50%;"></center> <center> <h4>PROFESSIONAL DATA NERD BY DAY</h4> </center> <section> <div class="content" style="padding-bottom: px;"> <div class="inner"> <div class="row"> <div class="col-4 col-12-medium"> <h2 style="text-align: left;"><span class="icon solid fa fa-university" style="font-size: 1.25em;"></span> Mathematics</h2> </div> <div class="col-8 col-12-medium"> <p>I am currently pursuing a Masters of Science in Applied Mathematics, with specialization in Data science, at Norhteastern University. I graduated from Boston University, in May 2018, with a B.A. degree in Pure and Applied Mathematics and a minor in Computer Science. My academic course selection, work experience, and analytical personality point me towards a career as a Data Scientist. My motivation to pursue a graduate school comes from an industry standardized need for individuals who can optimize their work to an unprecedented degree and learn the fundamental methodologies to enable data-driven business success. </p> </div> </div> </div> </div> </section> <section> <div class="content" style="padding-bottom: 0px; padding-top: 0px;"> <div class="inner"> <div class="row"> <div class="col-4 col-12-medium"> <h2 style="text-align: left;"><span class="icon solid fa fa-heart" style="font-size: 1.25em;"></span> Passion</h2> </div> <div class="col-8 col-12-medium"> <p>I enjoy exploring the relationships between numbers and translating digits into meaningful stories. These stories become actionable solutions and strategies for businesses, and I take pride in my ability to make data accessible to everyone. In a time where understanding and innovating with data has the undeniable potential to improve the way society functions, I hope to join the community of data scientists that will use data to drive social change. </p> </div> </div> </div> </div> </section> <section> <div class="content" style="padding-bottom: 0px; padding-top: 0px;"> <div class="inner"> <div class="row"> <div class="col-4 col-12-medium"> <h2 style="text-align: left;"><span class="icon solid fa fa-code" style="font-size: 1.25em;"></span> Data Science</h2> </div> <div class="col-8 col-12-medium"> <p>I have extensive experience leveraging critical data science tools such as Python, R, SQL, and AWS (along with associated packages/libraries) to develop client and internal facing dashboards, carry out extensive exploratory analyses, hack together bots to scrape, clean and process data, and most importantly serve the data needs and requests of data scientists, project stakeholders, and senior management to drive product and business success. </p> </div> </div> </div> </div> </section> </section> <!-- Experience --> <section id="experience" class="wrapper style3 spotlights" style="padding-top: 75px;"> <center> <h3>PROFESSIONAL EXPERIENCE</h3> </center> <section style="background-color: rgb(242, 242, 242);"> <div class="content"> <div class="inner"> <div class="row"> <div class="col-12 col-12-medium" style="margin-left: 15px;margin-right: 15px;"> <strong> <h4>Amazon Robotics</h4> </strong> <strong> <h5>Data Science Co-op (Data Science Engineering)</h5> </strong> <h6 class="text-black"><i class="fa fa-calendar fa-fw margin-right"></i>July 2021 - December 2021</h6> <ul> <li>Developed an operational performance anomaly detection model to support the solutions that facilitate robot drive issue ticketing and resolution for automated Sortation Centers (SCs) </li> <li>Used Jupyter, Python, AWS services(SageMaker, Athena, S3), and machine learning frameworks (scikit-learn) to build, train, validate, and tune multiple data models </li> <li>Deployed the data models I developed and tested into production using Java, GIT, Brazil CLI </li> <li>Proactively interfaced with various data sources using SQL and Athena, to support SC operation related metric / feature computation, data mining, A/B testing, and modeling </li> <li>Collaborated with software / system / data engineers, key stakeholders, and SC operation teams throughout the research and development of data models, metrics, and dashboards </li> </ul> </div> <div class="col-12 col-11-small"> <center> <hr style="height:1px; border-color: #4B4B4C;"> </center> </div> </div> <div class="row"> <div class="col-12 col-12-medium" style="margin-left: 15px;margin-right: 15px; margin-bottom: 5px;"> <strong> <h4>Spotted Media, Inc.</h4> </strong> <strong> <h5>Data Scientist (General)</h5> </strong> <h6><i class="fa fa-calendar fa-fw margin-right"></i>May 2019 - May 2020</h6> <ul> <li>Developed Spotted’s quarterly celebrity growth momentum metric in order to uphold an exclusive partnership with The Hollywood Reporter and $1.2 million a year in advertising </li> <li>Published Analysis: “THR’s Social Climbers.” The Hollywood Reporter 31 July 2019: pp. 75</li> <li>Provided clear visualizations and analyses to management and executive-level stakeholders to drive key decisions necessary in the creation of Spotted’s parametric trigger for celebrity disgrace insurance claims </li> <li>Created and maintained optimal data pipelines, and implemented scalable automated process to assure efficiency, repeatability, and standardization in the use of data within the Data and Insights team and Spotted as a whole </li> </ul> </div> <div class="col-12 col-11-small" style="padding-top: 5px;"> <center> <hr style="height:1px; border-color: #4B4B4C;"> </center> </div> </div> <div class="row"> <div class="col-12 col-12-medium" style="margin-left: 15px;margin-right: 15px;"> <strong> <h4>Spotted Media, Inc.</h4> </strong> <strong> <h5>Data Science Intern</h5> </strong> <h6 class="text-black"><i class="fa fa-calendar fa-fw margin-right"></i>June 2018 - May 2019</h6> <ul> <li>Segmented and analyzed millions of data points across hundreds of data features to better assess Hollywood talents’ unique global consumer appeal and recognition, persona, and disgrace risk using R and SQL </li> <li>Automated data scraping from Crimson Hexagon platform to facilitate celebrity social media sentiment reporting and reduce data collection errors and extraction time by 6 months </li> <li>Implemented dynamic z-score thresholding algorithm to detect anomalous social media negative sentiment spikes using R </li> </ul> </div> <div class="col-12 col-11-small"> <center> <hr style="height:1px; border-color: #4B4B4C;"> </center> </div> </div> <div class="row"> <div class="col-12 col-12-medium" style="margin-left: 15px;margin-right: 15px;"> <strong> <h4>Catalant Technologies</h4> </strong> <strong> <h5>Solutions Engineering Intern</h5> </strong> <h6 class="text-black"><i class="fa fa-calendar fa-fw margin-right"></i>March 2018 - May 2018</h6> <ul> <li>Designed and created Python Selenium tests scripts for automating hypothetical user workflows of Catalant’s web-based platform to test feature developments and updates </li> <li>Delivered premium, enterprise-ready programs for Solutions clients while testing the newest technology platforms </li> <li>Troubleshot and triaged issues with Solutions team to efficiently drive towards feature error identification and resolution </li> </ul> </div> <div class="col-12 col-11-small"> <center> <hr style="height:1px; border-color: #4B4B4C;"> </center> </div> </div> <div class="row"> <div class="col-12 col-12-medium" style="margin-left: 15px;margin-right: 15px;"> <strong> <h4>Trendalyze</h4> </strong> <strong> <h5>Data Science Intern</h5> </strong> <h6 class="text-black"><i class="fa fa-calendar fa-fw margin-right"></i>June 2017 - August 2017</h6> <ul> <li>Developed an application for predicting attrition among MMO gamers using the Trendalyze data visualization platform </li> <li>Analyzed metadata of 10,000 gamers to pinpoint a set of behavioral characteristics necessary to identify attrition trends </li> <li>Performed all necessary data preparation, for uploading gamers’ metadata to Trendalyze platform, using R and SQL </li> </ul> </div> <div class="col-12 col-11-small"> <center> <hr style="height:1px; border-color: #4B4B4C;"> </center> </div> </div> <div class="row"> <div class="col-12 col-12-medium" style="margin-left: 15px;margin-right: 15px;"> <strong> <h4>San Francisco State University Psychology Department</h4> </strong> <strong> <h5>Research Assistant</h5> </strong> <h6 class="text-black"><i class="fa fa-calendar fa-fw margin-right"></i>September 2014 - December 2014</h6> <ul> <li>Created and managed a data organization system by backing up data to ensure results always remain accessible for future reference </li> <li>Recorded graduate student’s assertions and motives for varying the scope of the research and maintained progress reports </li> <li>Analyzed and compiled experimental results and observations using R and Microsoft Excel</li> </ul> </div> </div> </div> </div> </section> </section> <!-- Education --> <section id="education" class="wrapper style2 spotlights" style="padding-top: 75px;padding-left: 25px; padding-right: 25px;"> <center> <h3>EDUCATION</h3> </center> <section style="background-color: rgb(250, 250, 250);"> <div class="image" style="background-color: rgb(250, 250, 250);"><img src="images/NEU_logo.png" alt="" data-position="center center"></img></div> <div class="content"> <div class="inner"> <h2>Northeastern University</h2> <strong> <h4>M.S. Applied Mathematics, Specialization in Data Science</h4> </strong> <strong> <h4>GPA: 3.55</h4> </strong> <h6 class="text-black"><i class="fa fa-calendar fa-fw margin-right"></i>September 2020 - <span class="tag round" style="background-color: rgb(0, 0, 0);color:white;padding:2px">Current</span></h6> <div class="card" style="padding: 2px; background-color: rgb(242, 242, 242);"> <h5> <center><strong> <h4>Relevant Coursework</h4> </strong></center> </h5> <center> <span class="tag" style="padding: 5px">Mathematical Methods and Modeling</span> <span class="tag" style="padding: 5px">Machine Learning</span> <br> <span class="tag" style="padding: 5px">Probability Theory</span> <span class="tag" style="padding: 5px">Applied Statistics</span> <span class="tag" style="padding: 5px">Numerical Analysis 1 & 2</span> <br> <span class="tag" style="padding: 5px">Topology 1</span> <span class="tag" style="padding: 5px">Data Management and Database Design</span> <ul></ul> </center> </div> </div> </div> </section> <section style="background-color: rgb(250, 250, 250);"> <div class="image" style="background-color: rgb(250, 250, 250);"><img src="images/BU_logo.png" alt="" data-position="center center"></img></div> <div class="content"> <div class="inner"> <h2>Boston University</h2> <strong> <h4>B.A. Pure and Applied Mathematics, Minor in Computer Science</h4> </strong> <h6 class="text-black"><i class="fa fa-calendar fa-fw margin-right"></i>January 2015 - May 2018 </h6> <div class="card" style="padding: 2px; background-color: rgb(242, 242, 242);"> <h5> <center><strong> <h4>Relevant Coursework</h4> </strong></center> </h5> <center> <span class="tag" style="padding: 5px">Data Science in R</span> <span class="tag" style="padding: 5px">Time Series Analysis</span> <br> <span class="tag" style="padding: 5px">Advanced Algorithms</span> <span class="tag" style="padding: 5px">Machine Learning</span> <span class="tag" style="padding: 5px">Probability</span> <span class="tag" style="padding: 5px">Stochastic Processes</span> <span class="tag" style="padding: 5px">Programming in Python</span> <span class="tag" style="padding: 5px">Programming in Java</span> <span class="tag" style="padding: 5px">Advanced Calculus</span> <br> <span class="tag" style="padding: 5px">Discrete Math</span> <span class="tag" style="padding: 5px">Linear Algebra</span> <span class="tag" style="padding: 5px">Computer Vision</span> <ul></ul> </center> </div> </div> </div> </section> <center> <h3>CERTIFICATIONS</h3> </center> <section style="background-color: rgb(250, 250, 250);"> <div class="image" style="background-color: rgb(250, 250, 250);"><img src="images/google_icon.png" alt="" data-position="center center"></img></div> <div class="content"> <div class="inner"> <h2>Coursera</h2> <strong> <h4>Google Data Analytics Specialization</h4> </strong> <strong> <h5>Credential ID: UJZ77WT6PR32</h4> </strong> <h6 class="text-black"><i class="fa fa-calendar fa-fw margin-right"></i>May 2021 - May 2021</h6> <ul class="actions"> <li><a href="https://www.coursera.org/account/accomplishments/specialization/certificate/UJZ77WT6PR32" class="button" style="color: black;background-color: rgba(75, 75, 76, 0.100);">See Certification</a></li> </ul> <div class="card" style="padding: 2px; background-color: rgb(242, 242, 242);"> <h5> <center><strong> <h4>Relevant Coursework</h4> </strong></center> </h5> <center> <span class="tag" style="padding: 5px">Process Data from Dirty to Clean</span> <span class="tag" style="padding: 5px">Prepare Data for Exploration</span> <br> <span class="tag" style="padding: 5px">Analyze Data to Answer Questions</span> <span class="tag" style="padding: 5px">Data Analysis with R Programming</span> <span class="tag" style="padding: 5px">Foundations: Data, Data, Everywhere</span> <br> <span class="tag" style="padding: 5px">Ask Questions to Make Data-Driven Decisions</span> <br> <span class="tag" style="padding: 5px">Share Data Through the Art of visualization</span> <ul></ul> </center> </div> </div> </div> </section> </section> <!-- Skills --> <section class="wrapper style3 fade-up" style="padding-top: 75px; padding-bottom: 55px;padding-left: 50px;padding-right: 50px;"> <center> <h3 style="padding-bottom: 25px;">SKILLS</h3> </center> <div class="content"> <div class="inner"> <div class="row"> <div class="col-4"> <div class="card" style="padding: 2px; background-color: rgb(242, 242, 242);"> <h5> <center><strong> <h4>Programming Languages</h4> </strong></center> </h5> <center> <span class="tag" style="padding: 5px">R</span> <span class="tag" style="padding: 5px">Python</span> <span class="tag" style="padding: 5px">SQL</span> <span class="tag" style="padding: 5px">HTML</span> <span class="tag" style="padding: 5px">CSS</span> <span class="tag" style="padding: 5px">JavaScript</span> <ul></ul> </center> </div> </div> <div class="col-4"> <div class="card" style="padding: 2px; background-color: rgb(242, 242, 242);"> <h5> <center><strong> <h4>Libraries & Packages</h4> </strong></center> </h5> <center> <span class="tag" style="padding: 5px">DataExplore</span> <span class="tag" style="padding: 5px">Plotly</span> <span class="tag" style="padding: 5px">Matplotlib</span> <span class="tag" style="padding: 5px">NumPy</span> <span class="tag" style="padding: 5px">Pandas</span> <span class="tag" style="padding: 5px">Flask</span> <span class="tag" style="padding: 5px">Scikit</span> <span class="tag" style="padding: 5px">SciPy</span> <span class="tag" style="padding: 5px">Selenium</span> <span class="tag" style="padding: 5px">Shiny</span> <span class="tag" style="padding: 5px">randomForrest</span> <span class="tag" style="padding: 5px">many more..</span> <ul></ul> </center> </div> </div> <div class="col-4"> <div class="card" style="padding: 2px; background-color: rgb(242, 242, 242); "> <h5> <center><strong> <h4>Analytic Tools & Software</h4> </strong></center> </h5> <center> <span class="tag" style="padding: 5px">AWS</span> <span class="tag" style="padding: 5px">Docker</span> <span class="tag" style="padding: 5px">Excel</span> <span class="tag" style="padding: 5px">Git</span> <span class="tag" style="padding: 5px">GitHub</span> <span class="tag" style="padding: 5px">Hadoop</span> <span class="tag" style="padding: 5px">Redshift</span> <span class="tag" style="padding: 5px">Tableau</span> <span class="tag" style="padding: 5px">DigitalOcean</span> <span class="tag" style="padding: 5px">GCP</span> <span class="tag" style="padding: 5px">EC2</span> <ul></ul> </center> </div> </div> </div> </div> </div> </section> <!-- Projects --> <section id="projects" class="wrapper style2 spotlights" style="padding-top: 75px;padding-left: 25px; padding-right: 25px;background-color: #fafafa;"> <center> <h3>PROJECTS</h3> </center> <section style="background-color: #fafafa;"> <div class="image" style="background-color: #fafafa;"><img src="images/breast_cancer_ribbon.png" alt="" data-position="center center"></img></div> <div class="content"> <div class="inner"> <h2>Breast Cancer Surgery Risk Calculator</h2> <h6 class="text-black"><i class="fa fa-calendar fa-fw margin-right"></i>September 2019 - <span class="tag round" style="background-color: rgb(0, 0, 0);color:white;padding:2px">Current</span></h6> <p>Used R, Shiny, and DigitalOcean to design, develop, and deploy a web-application ‘calculator’ for a surgical research fellow, at Tufts Medical Center; Department of Surgery, to help pre-operative breast cancer surgery patients understand their unique percent likelihood of experiencing a variety of post-operative complications. The web-application and manuscript have recently been approved for publication by The Journal of American Medical Association. The web-application has naturally aquired over 2000+ users to date. </p> <ul class="actions"> <li><a href="https://breastcalc.org/" class="button" style="color: black;background-color: rgba(75, 75, 76, 0.100);">See Project</a></li> <li><a href="https://link.springer.com/article/10.1245/s10434-021-09710-8" class="button" style="color: black;background-color: rgba(75, 75, 76, 0.100);">See Manuscript</a> </li> </ul> </div> </div> </section> <section style="background-color: #fafafa;"> <div class="image" style="background-color: #fafafa;"><img src="images/space_invaders.png" alt="" data-position="center center"></img></div> <div class="content"> <div class="inner"> <h2>REACTOKEY</h2> <h6 class="text-black"><i class="fa fa-calendar fa-fw margin-right"></i>April 2021</h6> <p>Used JavaScript, HTML/CSS, GIT, and DigitalOcean to design, develop, and deploy a typing speed game web-application. Currently experience 10-15 users a week at a 25% retention rate with respect to a 3 month look-back. </p> <ul class="actions"> <li><a href="https://reactokey.com/" class="button" style="color: black;background-color: rgba(75, 75, 76, 0.100);">See Project</a></li> </ul> </div> </div> </section> <section style="background-color: #fafafa;"> <div class="image" style="background-color: #fafafa;"><img src="images/music_icon.png" alt="" data-position="center center"></img></div> <div class="content"> <div class="inner"> <h2>SYNTHR</h2> <h6 class="text-black"><i class="fa fa-calendar fa-fw margin-right"></i>April 2021</h6> <p>Used R, Shiny, GIT, and Shiny.io to design, develop, and deploy a Shiny web application that allows users to alter the frequency pitch of sample audio to various semitones. The higher the semitone the higher the frequency pitch of the users selected audio sample. The lower the semitone the lower the frequency pitch. </p> <ul class="actions"> <li><a href="https://tigranmelkonian.shinyapps.io/synthr/?_ga=2.207923154.1320903146.1617557176-164005183.1565395995" class="button" style="color: black;background-color: rgba(75, 75, 76, 0.100);">See Project</a></li> <li><a href="https://github.com/TigranMelkonian/SynthR" class="button" style="color: black;background-color: rgba(75, 75, 76, 0.100);">See Code</a></li> </ul> </div> </div> </section> <section style="background-color: #fafafa;"> <div class="image" style="background-color: #fafafa;"><img src="images/trend_logo.png" alt="" data-position="center center"></img></div> <div class="content"> <div class="inner"> <h2>Celebrity Hype Dashboard</h2> <h6 class="text-black"><i class="fa fa-calendar fa-fw margin-right"></i>May 2019</h6> <p>Used R, Shiny, Shiny.io, GIT, and pageview to reactively collect historic Wikipedia page view data for over 22000 celebrities on user request. Created a ‘Hype’ score to help highlight the relative trending status of any given list of celebrities. </p> <ul class="actions"> <li><a href="https://tigranmelkonian.shinyapps.io/celebrity_hype_dashboard/" class="button" style="color: black;background-color: rgba(75, 75, 76, 0.100);">See Project</a></li> <li><a href="https://github.com/TigranMelkonian/Celebrity_Hype_Dashboard" class="button" style="color: black;background-color: rgba(75, 75, 76, 0.100);">See Code</a></li> </ul> </div> </div> </section> </section> <!-- News --> <section class="wrapper style3 fade-up" style="padding-top: 75px; padding-bottom: 55px;padding-left: 50px;padding-right: 50px;"> <center> <h3 style="padding-bottom: 25px;">FEATURES</h3> </center> <section style="background-color: rgb(242, 242, 242);"> <div class="content"> <div class="inner"> <h2>Northeastern University College of Science News Feature</h2> <h6 class="text-black"><i class="fa fa-calendar fa-fw margin-right"></i>October 2021</h6> <p>Northeastern COS published a feature article detailing my expereince as a graduate mathematics student! </p> <ul class="actions"> <li><a href="https://cos.northeastern.edu/news/qa-with-tigran-melkonian-ms-in-applied-mathematics/" class="button" style="color: black;background-color: rgba(75, 75, 76, 0.100);">See Article</a></li> </ul> </div> </div> </section> </section> </div> <!-- Footer --> <footer id="footer" class="wrapper style1-alt"> <div class="inner"> <ul class="menu"> <li>Tigran Melkonian</li> <li> <h3 style="color: #4B4B4C;">Social</h3> <ul class="icons"> <li><a href="https://www.linkedin.com/in/tigranmelkonian/" class="icon brands fa-linkedin-in"><span> LinkedIn</span></a></li> <li><a href="https://github.com/TigranMelkonian/" class="icon brands fa-github"><span> GitHub</span></a></li> <li><a href="https://www.facebook.com/tigran.melkonian.7/" class="icon brands fa-facebook-f"><span> Facebook</span></a></li> <li><a href="https://www.instagram.com/tigran.___/" class="icon brands fa-instagram"><span> Instagram</span></a></li> </ul> </li> </ul> </div> </footer> <!-- Scripts --> <script src="assets/js/jquery.min.js"></script> <script src="assets/js/jquery.scrollex.min.js"></script> <script src="assets/js/jquery.scrolly.min.js"></script> <script src="assets/js/browser.min.js"></script> <script src="assets/js/breakpoints.min.js"></script> <script src="assets/js/util.js"></script> <script src="assets/js/main.js"></script> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-153796594-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-153796594-1'); </script> </body> </html>
39.936351
124
0.60425
6b72a0c1da66d98497c156c85c8f2a886e5dea44
9,732
c
C
firmware/coreboot/src/soc/intel/denverton_ns/systemagent.c
fabiojna02/OpenCellular
45b6a202d6b2e2485c89955b9a6da920c4d56ddb
[ "CC-BY-4.0", "BSD-3-Clause" ]
1
2019-11-04T07:11:25.000Z
2019-11-04T07:11:25.000Z
firmware/coreboot/src/soc/intel/denverton_ns/systemagent.c
fabiojna02/OpenCellular
45b6a202d6b2e2485c89955b9a6da920c4d56ddb
[ "CC-BY-4.0", "BSD-3-Clause" ]
13
2018-10-12T21:29:09.000Z
2018-10-25T20:06:51.000Z
firmware/coreboot/src/soc/intel/denverton_ns/systemagent.c
fabiojna02/OpenCellular
45b6a202d6b2e2485c89955b9a6da920c4d56ddb
[ "CC-BY-4.0", "BSD-3-Clause" ]
null
null
null
/* * This file is part of the coreboot project. * * Copyright (C) 2007-2009 coresystems GmbH * Copyright (C) 2014 Google Inc. * Copyright (C) 2015 - 2017 Intel Corporation. * * This program 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; version 2 of the License. * * 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 General Public License for more details. */ #include <console/console.h> #include <arch/acpi.h> #include <arch/io.h> #include <stdint.h> #include <delay.h> #include <device/device.h> #include <device/pci.h> #include <device/pci_ids.h> #include <stdlib.h> #include <string.h> #include <cbmem.h> #include <romstage_handoff.h> #include <delay.h> #include <timer.h> #include <soc/iomap.h> #include <soc/pci_devs.h> #include <soc/ramstage.h> #include <soc/systemagent.h> #define _1ms 1 #define WAITING_STEP 100 static int get_pcie_bar(struct device *dev, unsigned int index, u32 *base, u32 *len) { u32 pciexbar_reg; *base = 0; *len = 0; pciexbar_reg = pci_read_config32(dev, index); if (!(pciexbar_reg & (1 << 0))) return 0; switch ((pciexbar_reg >> 1) & 3) { case 0: /* 256MB */ *base = pciexbar_reg & ((1 << 31) | (1 << 30) | (1 << 29) | (1 << 28)); *len = 256 * 1024 * 1024; return 1; case 1: /* 128M */ *base = pciexbar_reg & ((1 << 31) | (1 << 30) | (1 << 29) | (1 << 28) | (1 << 27)); *len = 128 * 1024 * 1024; return 1; case 2: /* 64M */ *base = pciexbar_reg & ((1 << 31) | (1 << 30) | (1 << 29) | (1 << 28) | (1 << 27) | (1 << 26)); *len = 64 * 1024 * 1024; return 1; } return 0; } static int get_bar(struct device *dev, unsigned int index, u32 *base, u32 *len) { u32 bar; bar = pci_read_config32(dev, index); /* If not enabled don't report it. */ if (!(bar & 0x1)) return 0; /* Knock down the enable bit. */ *base = bar & ~1; return 1; } struct fixed_mmio_descriptor { unsigned int index; u32 size; int (*get_resource)(struct device *dev, unsigned int index, u32 *base, u32 *size); const char *description; }; struct fixed_mmio_descriptor mc_fixed_resources[] = { {PCIEXBAR, 0, get_pcie_bar, "PCIEXBAR"}, {MCHBAR, MCH_BASE_SIZE, get_bar, "MCHBAR"}, }; /* * Add all known fixed MMIO ranges that hang off the host bridge/memory * controller device. */ static void mc_add_fixed_mmio_resources(struct device *dev) { int i; for (i = 0; i < ARRAY_SIZE(mc_fixed_resources); i++) { u32 base; u32 size; struct resource *resource; unsigned int index; size = mc_fixed_resources[i].size; index = mc_fixed_resources[i].index; if (!mc_fixed_resources[i].get_resource(dev, index, &base, &size)) continue; resource = new_resource(dev, mc_fixed_resources[i].index); resource->flags = IORESOURCE_MEM | IORESOURCE_FIXED | IORESOURCE_STORED | IORESOURCE_RESERVE | IORESOURCE_ASSIGNED; resource->base = base; resource->size = size; printk(BIOS_DEBUG, "%s: Adding %s @ %x 0x%08lx-0x%08lx.\n", __func__, mc_fixed_resources[i].description, index, (unsigned long)base, (unsigned long)(base + size - 1)); } } struct map_entry { int reg; int is_64_bit; int is_limit; const char *description; }; static void read_map_entry(struct device *dev, struct map_entry *entry, uint64_t *result) { uint64_t value; uint64_t mask; /* All registers are on a 1MiB granularity. */ mask = ((1ULL << 20) - 1); mask = ~mask; value = 0; if (entry->is_64_bit) { value = pci_read_config32(dev, entry->reg + 4); value <<= 32; } value |= (uint64_t)pci_read_config32(dev, entry->reg); value &= mask; if (entry->is_limit) value |= ~mask; *result = value; } #define MAP_ENTRY(reg_, is_64_, is_limit_, desc_) \ { \ .reg = reg_, .is_64_bit = is_64_, .is_limit = is_limit_, \ .description = desc_, \ } #define MAP_ENTRY_BASE_64(reg_, desc_) MAP_ENTRY(reg_, 1, 0, desc_) #define MAP_ENTRY_LIMIT_64(reg_, desc_) MAP_ENTRY(reg_, 1, 1, desc_) #define MAP_ENTRY_BASE_32(reg_, desc_) MAP_ENTRY(reg_, 0, 0, desc_) enum { TOUUD_REG, TOLUD_REG, TSEG_REG, /* Must be last. */ NUM_MAP_ENTRIES }; static struct map_entry memory_map[NUM_MAP_ENTRIES] = { [TOUUD_REG] = MAP_ENTRY_BASE_64(TOUUD, "TOUUD"), [TOLUD_REG] = MAP_ENTRY_BASE_32(TOLUD, "TOLUD"), [TSEG_REG] = MAP_ENTRY_BASE_32(TSEGMB, "TSEGMB"), }; static void mc_read_map_entries(struct device *dev, uint64_t *values) { int i; for (i = 0; i < NUM_MAP_ENTRIES; i++) read_map_entry(dev, &memory_map[i], &values[i]); } static void mc_report_map_entries(struct device *dev, uint64_t *values) { int i; for (i = 0; i < NUM_MAP_ENTRIES; i++) { printk(BIOS_DEBUG, "MC MAP: %s: 0x%llx\n", memory_map[i].description, values[i]); } } static void mc_add_dram_resources(struct device *dev) { unsigned long base_k, size_k; unsigned long touud_k; unsigned long index; struct resource *resource; uint64_t mc_values[NUM_MAP_ENTRIES]; /* Read in the MAP registers and report their values. */ mc_read_map_entries(dev, &mc_values[0]); mc_report_map_entries(dev, &mc_values[0]); /* * These are the host memory ranges that should be added: * - 0 -> 0xa0000: cacheable * - 0xc0000 -> 0x100000 : reserved * - 0x100000 -> top_of_ram : cacheable * - top_of_ram -> TSEG: uncacheable * - TESG -> TOLUD: cacheable with standard MTRRs and reserved * - 4GiB -> TOUUD: cacheable * * The default SMRAM space is reserved so that the range doesn't * have to be saved during S3 Resume. Once marked reserved the OS * cannot use the memory. This is a bit of an odd place to reserve * the region, but the CPU devices don't have dev_ops->read_resources() * called on them. * * The range 0xa0000 -> 0xc0000 does not have any resources * associated with it to handle legacy VGA memory. If this range * is not omitted the mtrr code will setup the area as cacheable * causing VGA access to not work. * * The TSEG region is mapped as cacheable so that one can perform * SMRAM relocation faster. Once the SMRR is enabled the SMRR takes * precedence over the existing MTRRs covering this region. * * It should be noted that cacheable entry types need to be added in * order. The reason is that the current MTRR code assumes this and * falls over itself if it isn't. * * The resource index starts low and should not meet or exceed * PCI_BASE_ADDRESS_0. */ index = 0; /* 0 - > 0xa0000 */ base_k = 0; size_k = (0xa0000 >> 10) - base_k; ram_resource(dev, index++, base_k, size_k); /* 0x100000 -> top_of_ram */ base_k = 0x100000 >> 10; size_k = (top_of_32bit_ram() >> 10) - base_k; ram_resource(dev, index++, base_k, size_k); /* top_of_ram -> TSEG */ resource = new_resource(dev, index++); resource->base = top_of_32bit_ram(); resource->size = mc_values[TSEG_REG] - resource->base; resource->flags = IORESOURCE_MEM | IORESOURCE_FIXED | IORESOURCE_STORED | IORESOURCE_RESERVE | IORESOURCE_ASSIGNED; /* TSEG -> TOLUD */ resource = new_resource(dev, index++); resource->base = mc_values[TSEG_REG]; resource->size = mc_values[TOLUD_REG] - resource->base; resource->flags = IORESOURCE_MEM | IORESOURCE_FIXED | IORESOURCE_STORED | IORESOURCE_RESERVE | IORESOURCE_ASSIGNED | IORESOURCE_CACHEABLE; printk(BIOS_DEBUG, "SMM memory location: 0x%llx SMM memory size: 0x%llx\n", resource->base, resource->size); /* 4GiB -> TOUUD */ base_k = 4096 * 1024; /* 4GiB */ touud_k = mc_values[TOUUD_REG] >> 10; size_k = touud_k - base_k; if (touud_k > base_k) ram_resource(dev, index++, base_k, size_k); /* * Reserve everything between A segment and 1MB: * * 0xa0000 - 0xbffff: legacy VGA * 0xc0000 - 0xfffff: reserved RAM */ mmio_resource(dev, index++, (0xa0000 >> 10), (0xc0000 - 0xa0000) >> 10); reserved_ram_resource(dev, index++, (0xc0000 >> 10), (0x100000 - 0xc0000) >> 10); } static void systemagent_read_resources(struct device *dev) { /* Read standard PCI resources. */ pci_dev_read_resources(dev); /* Add all fixed MMIO resources. */ mc_add_fixed_mmio_resources(dev); /* Calculate and add DRAM resources. */ mc_add_dram_resources(dev); } static void systemagent_init(struct device *dev) { struct stopwatch sw; void *bios_reset_cpl = (void *)(DEFAULT_MCHBAR + MCH_BAR_BIOS_RESET_CPL); uint32_t reg = read32(bios_reset_cpl); /* Stage0 BIOS Reset Complete (RST_CPL) */ reg |= RST_CPL_BIT; write32(bios_reset_cpl, reg); /* * Poll for bit 8 in same reg (RST_CPL). * We wait here till 1 ms for the bit to get set. */ stopwatch_init_msecs_expire(&sw, _1ms); while (!(read32(bios_reset_cpl) & PCODE_INIT_DONE)) { if (stopwatch_expired(&sw)) { printk(BIOS_DEBUG, "Failed to set RST_CPL bit\n"); return; } udelay(WAITING_STEP); } printk(BIOS_DEBUG, "Set BIOS_RESET_CPL\n"); } static struct device_operations systemagent_ops = { .read_resources = &systemagent_read_resources, .set_resources = &pci_dev_set_resources, .enable_resources = &pci_dev_enable_resources, .init = &systemagent_init, .ops_pci = &soc_pci_ops, }; /* IDs for System Agent device of Intel Denverton SoC */ static const unsigned short systemagent_ids[] = { SA_DEVID, /* DVN System Agent */ SA_DEVID_DNVAD, /* DVN-AD System Agent */ 0 }; static const struct pci_driver systemagent_driver __pci_driver = { .ops = &systemagent_ops, .vendor = PCI_VENDOR_ID_INTEL, .devices = systemagent_ids };
27.108635
79
0.677353
6b91ce701a02902db35d86e3bcd2279b4cf1710a
206
h
C
src/CppSample/VTableApp.h
andreabalducci/MFCTraining
9751c2f730ba525b309186385cedb8f48d211bab
[ "MIT" ]
null
null
null
src/CppSample/VTableApp.h
andreabalducci/MFCTraining
9751c2f730ba525b309186385cedb8f48d211bab
[ "MIT" ]
null
null
null
src/CppSample/VTableApp.h
andreabalducci/MFCTraining
9751c2f730ba525b309186385cedb8f48d211bab
[ "MIT" ]
null
null
null
#pragma once class VTableApp { public: VTableApp(); ~VTableApp(); void Run(); }; class Base { private: int m_v; }; class Enh : public Base { private: int m_v; public: Enh() {} virtual ~Enh(){ } };
8.583333
23
0.616505
fd99b279a17f545c94c7e1a9c67e313f17a9098b
186
asm
Assembly
data/pokemon/dex_entries/zangoose.asm
AtmaBuster/pokeplat-gen2
fa83b2e75575949b8f72cb2c48f7a1042e97f70f
[ "blessing" ]
6
2021-06-19T06:41:19.000Z
2022-02-15T17:12:33.000Z
data/pokemon/dex_entries/zangoose.asm
AtmaBuster/pokeplat-gen2-old
01e42c55db5408d72d89133dc84a46c699d849ad
[ "blessing" ]
null
null
null
data/pokemon/dex_entries/zangoose.asm
AtmaBuster/pokeplat-gen2-old
01e42c55db5408d72d89133dc84a46c699d849ad
[ "blessing" ]
3
2021-01-15T18:45:40.000Z
2021-10-16T03:35:27.000Z
db "CAT FERRET@" ; species name db "Its fur will stand" next "on end if it" next "smells a SEVIPER" page "nearby. It uses" next "its sharp claws to" next "tear up its foes.@"
18.6
32
0.655914
e7720ef242a8d253d6ceb437a360eb438732c32e
3,297
js
JavaScript
resources/assets/js/videoplayers.js
SSR-online/DLM
9173f59c88e5337199ba54219b92318a8c99cd70
[ "MIT" ]
null
null
null
resources/assets/js/videoplayers.js
SSR-online/DLM
9173f59c88e5337199ba54219b92318a8c99cd70
[ "MIT" ]
4
2020-02-17T14:03:49.000Z
2021-11-02T15:47:38.000Z
resources/assets/js/videoplayers.js
SSR-online/DLM
9173f59c88e5337199ba54219b92318a8c99cd70
[ "MIT" ]
null
null
null
document.addEventListener('turbolinks:load', function(e) { setupPlayers(); }); var players = []; function setupPlayers() { let containerdivs = document.querySelectorAll('.mediaplayercontainer'); for (var i = containerdivs.length - 1; i >= 0; i--) { var playerdiv = containerdivs[i].querySelector('.player'); var playerid = playerdiv.id; var player = new Mediasite.Player(playerid, { url: playerdiv.dataset.src, events: { 'ready': function () { onMediaplayerReady(); }, 'error': function (errorData) { console.log('Error: ' + Mediasite.ErrorDescription[errorData.errorCode] + (errorData.details ? ' (' + errorData.details + ')' : '')); }, 'playstatechanged': onMediaplayerPlayStateChanged, 'timedeventreached': onMediaPlayerTimedEvent } } ); players.push( { element: containerdivs[i], player: player } ); } } function onMediaplayerPlayStateChanged(playState) { console.log('changed state' + playState); } function onMediaplayerReady() { for (var i = players.length - 1; i >= 0; i--) { var player = players[i].player; var element = players[i].element; var blocks = element.querySelectorAll('.video-overlay'); for (var j = blocks.length - 1; j >= 0; j--) { player.addTimedEvent(Number(blocks[j].dataset.timestamp), 'showBlock', {id: blocks[j].dataset.id, playerIndex: i}); } } } function onMediaPlayerTimedEvent(event) { var payload = event.timedEventPayload; var player = players[payload.playerIndex].player; showBlock(event.timedEventPayload.id, player); player.pause(); } function showBlock(id, player) { var block = document.getElementById('video-block-' + id); var playButton = block.querySelector('button.play'); playButton.addEventListener('click', function(e) { player.play(); block.classList.add('hidden'); }); block.classList.remove('hidden'); block.addEventListener('submit', function(e) { e.preventDefault(); // Form can be the question form or the reset form (assumes only one is shown at a time) form = e.currentTarget.querySelector('form'); postQuestion(id); }); } function postQuestion(id) { var block = document.getElementById('video-block-' + id); var form = block.querySelector('form'); var request = new XMLHttpRequest(); request.overrideMimeType("application/json"); request.open('POST', form.action, true); request.setRequestHeader('X-CSRF-TOKEN', document.querySelector('meta[name=csrf-token]').content); request.onload = function() { if (this.status >= 200 && this.status < 400) { // Success! var data = JSON.parse(this.response); var replaceNode = block.querySelector('.replacenode'); replaceNode.textContent = ''; replaceNode.insertAdjacentHTML('afterbegin', data.content); } else { // We reached our target server, but it returned an error console.log('error'); } }; request.onerror = function() { console.log('connection error'); }; var data = new FormData(form); data.append('returnJson', true); request.send(data); }
32.009709
119
0.629663
7d171e3e56c034533b19a0e9e07ed7a5555ec9e8
8,030
kt
Kotlin
compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/loops/ProgressionLoopHeader.kt
Mu-L/kotlin
5c3ce66e9979d2b3592d06961e181fa27fa88431
[ "ECL-2.0", "Apache-2.0" ]
151
2019-11-06T03:32:39.000Z
2022-03-25T15:06:58.000Z
compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/loops/ProgressionLoopHeader.kt
Mu-L/kotlin
5c3ce66e9979d2b3592d06961e181fa27fa88431
[ "ECL-2.0", "Apache-2.0" ]
3
2020-07-27T00:44:27.000Z
2021-12-30T20:21:23.000Z
compiler/ir/backend.common/src/org/jetbrains/kotlin/backend/common/lower/loops/ProgressionLoopHeader.kt
Mu-L/kotlin
5c3ce66e9979d2b3592d06961e181fa27fa88431
[ "ECL-2.0", "Apache-2.0" ]
69
2019-11-18T10:25:35.000Z
2021-12-27T14:15:47.000Z
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.backend.common.lower.loops import org.jetbrains.kotlin.backend.common.CommonBackendContext import org.jetbrains.kotlin.backend.common.lower.DeclarationIrBuilder import org.jetbrains.kotlin.backend.common.lower.irIfThen import org.jetbrains.kotlin.ir.IrStatement import org.jetbrains.kotlin.ir.builders.createTmpVariable import org.jetbrains.kotlin.ir.builders.irGet import org.jetbrains.kotlin.ir.builders.irNotEquals import org.jetbrains.kotlin.ir.declarations.IrVariable import org.jetbrains.kotlin.ir.expressions.IrExpression import org.jetbrains.kotlin.ir.expressions.IrLoop import org.jetbrains.kotlin.ir.expressions.impl.IrDoWhileLoopImpl class ProgressionLoopHeader( headerInfo: ProgressionHeaderInfo, builder: DeclarationIrBuilder, context: CommonBackendContext ) : NumericForLoopHeader<ProgressionHeaderInfo>(headerInfo, builder, context) { private val preferJavaLikeCounterLoop = context.preferJavaLikeCounterLoop private val javaLikeCounterLoopBuilder = JavaLikeCounterLoopBuilder(context) // For this loop: // // for (i in first()..last() step step()) // // ...the functions may have side effects, so we need to call them in the following order: first() (inductionVariable), last(), step(). // Additional variables come first as they may be needed to the subsequent variables. // // In the case of a reversed range, the `inductionVariable` and `last` variables are swapped, therefore the declaration order must be // swapped to preserve the correct evaluation order. override val loopInitStatements = headerInfo.additionalStatements + ( if (headerInfo.isReversed) listOfNotNull(lastVariableIfCanCacheLast, inductionVariable) else listOfNotNull(inductionVariable, lastVariableIfCanCacheLast) ) + listOfNotNull(stepVariable) private var loopVariable: IrVariable? = null override fun initializeIteration( loopVariable: IrVariable?, loopVariableComponents: Map<Int, IrVariable>, builder: DeclarationIrBuilder, backendContext: CommonBackendContext, ): List<IrStatement> = with(builder) { // loopVariable is used in the loop condition if it can overflow. If no loopVariable was provided, create one. this@ProgressionLoopHeader.loopVariable = if (headerInfo.canOverflow && loopVariable == null) { scope.createTmpVariable( irGet(inductionVariable), nameHint = "loopVariable", isMutable = true ) } else { loopVariable?.initializer = irGet(inductionVariable).let { headerInfo.progressionType.run { if (this is UnsignedProgressionType) { // The induction variable is signed for unsigned progressions but the loop variable should be unsigned. it.asUnsigned() } else it } } loopVariable } // loopVariable = inductionVariable // inductionVariable = inductionVariable + step listOfNotNull(this@ProgressionLoopHeader.loopVariable, incrementInductionVariable(this)) } override fun buildLoop(builder: DeclarationIrBuilder, oldLoop: IrLoop, newBody: IrExpression?) = with(builder) { if (headerInfo.canOverflow || preferJavaLikeCounterLoop && headerInfo.progressionType is UnsignedProgressionType && headerInfo.isLastInclusive ) { // If the induction variable CAN overflow, we cannot use it in the loop condition. // Loop is lowered into something like: // // if (inductionVar <= last) { // // Loop is not empty // do { // val loopVar = inductionVar // inductionVar += step // // Loop body // } while (loopVar != last) // } // // This loop form is also preferable for loops over unsigned progressions on JVM, // because HotSpot doesn't recognize unsigned integer comparison as a counter loop condition. // Unsigned integer equality is fine, though. // See KT-49444 for performance comparison example. val newLoopOrigin = if (preferJavaLikeCounterLoop) this@ProgressionLoopHeader.context.doWhileCounterLoopOrigin else oldLoop.origin val newLoop = IrDoWhileLoopImpl(oldLoop.startOffset, oldLoop.endOffset, oldLoop.type, newLoopOrigin).apply { val loopVariableExpression = irGet(loopVariable!!).let { headerInfo.progressionType.run { if (this is UnsignedProgressionType) { // The loop variable is signed but bounds are signed for unsigned progressions. it.asSigned() } else it } } label = oldLoop.label condition = irNotEquals(loopVariableExpression, lastExpression) body = newBody } if (preferJavaLikeCounterLoop) { javaLikeCounterLoopBuilder.moveInductionVariableUpdateToLoopCondition(newLoop) } val loopCondition = buildLoopCondition(this@with) LoopReplacement(newLoop, irIfThen(loopCondition, newLoop)) } else if (preferJavaLikeCounterLoop && !headerInfo.isLastInclusive) { // It is critically important for loop code performance on JVM to "look like" a simple counter loop in Java when possible // (`for (int i = first; i < lastExclusive; ++i) { ... }`). // Otherwise loop-related optimizations will not kick in, resulting in significant performance degradation. // // Use a do-while loop: // do { // if ( !( inductionVariable < last ) ) break // val loopVariable = inductionVariable // <body> // } while ( { inductionVariable += step; true } ) // This loop form is equivalent to the Java counter loop shown above. val newLoopCondition = buildLoopCondition(this@with) javaLikeCounterLoopBuilder.buildJavaLikeDoWhileCounterLoop( oldLoop, newLoopCondition, newBody, this@ProgressionLoopHeader.context.doWhileCounterLoopOrigin ) } else { // Use an if-guarded do-while loop (note the difference in loop condition): // // if (inductionVar <= last) { // do { // val loopVar = inductionVar // inductionVar += step // // Loop body // } while (inductionVar <= last) // } // val newLoop = IrDoWhileLoopImpl(oldLoop.startOffset, oldLoop.endOffset, oldLoop.type, oldLoop.origin).apply { label = oldLoop.label condition = buildLoopCondition(this@with) body = newBody } val loopCondition = buildLoopCondition(this@with) LoopReplacement(newLoop, irIfThen(loopCondition, newLoop)) } } }
48.373494
139
0.592279
14ec0669482ff125646790d05aeca9234687f19c
344
kt
Kotlin
shared/src/commonTest/kotlin/cat/alexgluque/paraulogicsolver/viewModel/InsertWordsUseCaseFake.kt
alexluque/ParaulogicSolver
4d1d0b78d4c5d8b9a9d7c20a75e1fc857e9b1ccf
[ "Apache-2.0" ]
null
null
null
shared/src/commonTest/kotlin/cat/alexgluque/paraulogicsolver/viewModel/InsertWordsUseCaseFake.kt
alexluque/ParaulogicSolver
4d1d0b78d4c5d8b9a9d7c20a75e1fc857e9b1ccf
[ "Apache-2.0" ]
null
null
null
shared/src/commonTest/kotlin/cat/alexgluque/paraulogicsolver/viewModel/InsertWordsUseCaseFake.kt
alexluque/ParaulogicSolver
4d1d0b78d4c5d8b9a9d7c20a75e1fc857e9b1ccf
[ "Apache-2.0" ]
null
null
null
package cat.alexgluque.paraulogicsolver.viewModel import cat.alexgluque.paraulogicsolver.usecase.InsertWordsUseCase import kotlin.native.concurrent.ThreadLocal @ThreadLocal object InsertWordsUseCaseFake : InsertWordsUseCase { var insertWordsIsCalled = false override suspend fun invoke() { insertWordsIsCalled = true } }
24.571429
65
0.799419
bb5d3edcea5769b6d94aee3fd624cef2e4635a6f
3,958
kt
Kotlin
numeriko-core/src/main/kotlin/tomasvolker/numeriko/core/interfaces/array1d/generic/MutableArray1D.kt
TomasVolker/numeriko
1e9d64140ec70b692b1b64ecdcd8b63cf41f97af
[ "Apache-2.0" ]
4
2018-11-19T21:48:21.000Z
2020-05-10T21:12:37.000Z
numeriko-core/src/main/kotlin/tomasvolker/numeriko/core/interfaces/array1d/generic/MutableArray1D.kt
TomasVolker/numeriko
1e9d64140ec70b692b1b64ecdcd8b63cf41f97af
[ "Apache-2.0" ]
10
2018-11-08T17:10:33.000Z
2019-03-12T14:54:28.000Z
numeriko-core/src/main/kotlin/tomasvolker/numeriko/core/interfaces/array1d/generic/MutableArray1D.kt
TomasVolker/numeriko
1e9d64140ec70b692b1b64ecdcd8b63cf41f97af
[ "Apache-2.0" ]
1
2018-12-07T21:44:22.000Z
2018-12-07T21:44:22.000Z
package tomasvolker.numeriko.core.interfaces.array1d.generic import tomasvolker.numeriko.core.config.NumerikoConfig import tomasvolker.numeriko.core.index.Index import tomasvolker.numeriko.core.index.IndexProgression import tomasvolker.numeriko.core.interfaces.array0d.generic.MutableArray0D import tomasvolker.numeriko.core.interfaces.array1d.generic.view.DefaultArray1DHigherRankView import tomasvolker.numeriko.core.interfaces.array1d.generic.view.DefaultReshapedView import tomasvolker.numeriko.core.interfaces.array1d.generic.view.defaultArray0DView import tomasvolker.numeriko.core.interfaces.array1d.generic.view.defaultArray1DView import tomasvolker.numeriko.core.interfaces.array1d.integer.IntArray1D import tomasvolker.numeriko.core.interfaces.array2d.generic.Array2D import tomasvolker.numeriko.core.interfaces.array2d.generic.MutableArray2D import tomasvolker.numeriko.core.interfaces.arraynd.generic.ArrayND import tomasvolker.numeriko.core.interfaces.arraynd.generic.MutableArrayND import tomasvolker.numeriko.core.interfaces.factory.intArray1DOf import tomasvolker.numeriko.core.preconditions.requireSameSize import tomasvolker.numeriko.core.view.ElementOrder interface MutableArray1D<T>: Array1D<T>, MutableArrayND<T> { override fun setValue(value: T, vararg indices: Int) { requireValidIndices(indices) return setValue(value, indices[0]) } override fun withShape(shape0: Int, shape1: Int, order: ElementOrder): MutableArray2D<T> = withShape(intArray1DOf(shape0, shape1), order).as2D() override fun withShape(shape: IntArray1D, order: ElementOrder): MutableArrayND<T> = DefaultReshapedView( shape = shape.copy(), array = this, offset = 0, order = order ) override fun lowerRank(axis: Int): MutableArray0D<T> { require(shape(axis) == 1) return defaultArray0DView(this, 0) } override fun higherRank(axis: Int): MutableArray2D<T> { require(axis in 0..1) return DefaultArray1DHigherRankView(this, axis) } fun setValue(value: T, i0: Int) fun setValue(value: T, i0: Index) = setValue(value, i0.computeValue(size)) fun setValue(other: Array1D<T>) { requireSameSize(other, this) // Anti alias copy val copy = other.copy() for (i in indices) { setValue(copy.getValue(i), i) } } override fun setValue(value: T) { for (i in indices) { setValue(value, i) } } override fun getView(i0: Int ): MutableArray0D<T> = defaultArray0DView(this, i0) override fun getView(i0: Index): MutableArray0D<T> = getView(i0.compute()) override fun getView(i0: IntProgression): MutableArray1D<T> = defaultArray1DView(this, i0) override fun getView(i0: IndexProgression): MutableArray1D<T> = getView(i0.compute()) fun setView(value: Array1D<T>, i0: IndexProgression): Unit = setView(value, i0.compute()) fun setView(value: Array1D<T>, i0: IntProgression ): Unit = getView(i0).setValue(value) fun setView(value: T, i0: IndexProgression): Unit = setView(value, i0.compute()) fun setView(value: T, i0: IntProgression ): Unit = getView(i0).setValue(value) } // Setter functions defined as extensions to avoid boxing when using get syntax on primitive specializations operator fun <T> MutableArray1D<T>.set(i0: Int, value: T) = setValue(value, i0) operator fun <T> MutableArray1D<T>.set(i0: Index, value: T) = setValue(value, i0) operator fun <T> MutableArray1D<T>.set(i0: IntProgression, value: Array1D<T>) = setView(value, i0) operator fun <T> MutableArray1D<T>.set(i0: IndexProgression, value: Array1D<T>) = setView(value, i0) operator fun <T> MutableArray1D<T>.set(i0: IntProgression, value: T) = setView(value, i0) operator fun <T> MutableArray1D<T>.set(i0: IndexProgression, value: T) = setView(value, i0)
42.106383
108
0.719555
bcc5364ea3e75c5ea9ee023b6ec780f135b2ffda
355
js
JavaScript
NextTech.ChaChing123.UI.Web/Areas/Admin/Scripts/spa_admin/assets/js/services/common.services.js
vinaphuc/123ChaChing-Web
50b85f5a18f5f1efdfbfe62fa668a7420eabe5eb
[ "MIT" ]
2
2019-12-14T14:30:10.000Z
2020-01-16T00:54:06.000Z
NextTech.ChaChing123.UI.Web/Areas/Admin/Scripts/spa_admin/assets/js/services/common.services.js
vinaphuc/123ChaChing-Web
50b85f5a18f5f1efdfbfe62fa668a7420eabe5eb
[ "MIT" ]
1
2020-01-09T01:20:56.000Z
2020-01-09T01:20:56.000Z
NextTech.ChaChing123.UI.Web/Areas/Admin/Scripts/spa_admin/assets/js/services/common.services.js
vinaphuc/123ChaChing-Web
50b85f5a18f5f1efdfbfe62fa668a7420eabe5eb
[ "MIT" ]
3
2020-01-06T04:27:10.000Z
2021-07-31T02:55:23.000Z
// set the virtual directory for the application // in production, the url will start from /OLS.... // set the application virtual directory here var virtualDirectory = angular.element('input[name="__virtualDirectory"]').attr('value'); (function () { "use strict"; angular .module("common.services", ["ngResource"]) }());
29.583333
89
0.656338
61c3f919a19aab7e888dd05b5f44631574d09074
3,790
css
CSS
frontend/web/css/detail/functionMenu.css
louis3385/wechat-smart-hotel
6612686737a89ba3f55de0901b552ab947b80037
[ "Apache-2.0", "BSD-3-Clause" ]
3
2017-12-14T03:14:22.000Z
2018-08-15T03:35:44.000Z
frontend/web/css/detail/functionMenu.css
louis3385/wechat-smart-hotel
6612686737a89ba3f55de0901b552ab947b80037
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
frontend/web/css/detail/functionMenu.css
louis3385/wechat-smart-hotel
6612686737a89ba3f55de0901b552ab947b80037
[ "Apache-2.0", "BSD-3-Clause" ]
2
2018-08-15T03:37:30.000Z
2020-12-10T09:11:01.000Z
.menu_detail_vue{ bottom:0; left:0; position:fixed; z-index:11; width:100%; padding:6px 8px 6px 28px; background-color:rgb(250,250,252); box-shadow:0 1px 0 0 rgba(216,219,235,0.9); box-sizing: border-box; border-top:1px solid rgba(216,219,235,0.9); display: -webkit-flex; display: -ms-flexbox; display: flex; -webkit-align-items: center; -ms-flex-align: center; align-items: center; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; } .menu_detail_vue.review{ padding:6px 8px 6px 8px; -webkit-justify-content: center; -ms-flex-pack: center; justify-content: center; } .iconPost_menu_dv, .iconTele_menu_dv, .iconCancel_menu_dv, .iconProof_menu_dv, .iconReview_menu_dv{ background-size:22px 22px; width:22px; height:22px; display: inline-block; position:relative; } .txtPost_menu_dv, .txtTele_menu_dv, .txtCancel_menu_dv, .txtProof_menu_dv, .txtReview_menu_dv{ font-size: 9px; color: rgb(135,142,168); text-align: center; margin-top:3px; /*position: absolute; font-size: 9px; color: rgb(135,142,168); white-space: nowrap; bottom: -12px; left: 50%; transform: translateX(-50%);*/ } .iconPost_menu_dv{ background-image:url('/images/detail/icAddActivity@2x.png') ; } .iconTele_menu_dv{ background-image:url('/images/detail/icCall@2x.png') ; } .iconCancel_menu_dv{ background-image:url('/images/detail/icCancel@2x.png') ; } .iconProof_menu_dv{ background-image:url('/images/detail/icQRCode@2x.png') ; } .iconReview_menu_dv{ background-image:url('/images/detail/icComment@2x.png') ; } .state_menu_dv{ padding: 9px; display: inline-block; font-size: 17px; color: rgb(182,184,191); background-color: rgb(237,239,242); height: 37px; box-sizing: border-box; -webkit-flex: 1; -ms-flex: 1; flex: 1; text-align: center; border:1px solid rgba(0,0,0,0.12); } .state_men_dv.over{ background-color:rgb(168,170,179); color:white; } .boxTele_menu_dv, .boxCancel_menu_dv, .boxProof_menu_dv, .boxReview_menu_dv{ margin-left:35px; } .state_menu_dv,.bookAction_menu_dv{ text-align: center; margin-left:38px; } .bookAction_menu_dv{ padding:9px; box-sizing: border-box; color:white; background-color:rgb(108,126,217); -webkit-flex:1; -ms-flex:1; flex:1; } .bookAction_menu_dv.wp{ background-color:rgb(106,119,184); } .popQrcode{ position:fixed; left:0; top:0; width:100%; height:100vh; z-index:23; background-color:rgba(0,0,0,0.5); } .info_popQrcode{ padding: 28px 32px; background-color: white; display: inline-block; position: absolute; left: 50%; top: 50%; border-radius:6px; -webkit-transform: translateX(-50%)translateY(-50%); -ms-transform: translateX(-50%)translateY(-50%); transform: translateX(-50%)translateY(-50%); } .canvas_info_popQrcode{ width: 225px; height: 225px; padding-top: 10px; text-align: center; box-sizing: border-box; } .tip_info_popQrcode{ text-align:center; font-size:12px; color:rgb(61,61,61); margin:12px 0 24px 0; } .name_detail_ip::after, .fee_detail_ip::after, .time_detail_ip::after{ content:''; clear:both; display: block; } .left_name_dip, .left_fee_dip, .left_time_dip{ float:left; } .right_name_dip, .right_fee_dip, .right_time_dip{ float:right; } .detail_info_popQrcode{ font-size:14px; color:rgb(61,61,61); } .name_detail_ip{ font-size:16px; } .fee_detail_ip{ margin:12px 0 8px 0; } .popQrcode{ text-align:center; }
20.939227
63
0.644591
fc2b32372215999f0fcb70e22c37bf6e06e343d6
14,720
swift
Swift
SUICompanionApp/SUICompanionApp/Molecules/ExampleMolecules.swift
hmrc/ios-swiftui-components
fb804f98b5a00164cabc14a7183f02ae40dcc234
[ "Apache-2.0" ]
null
null
null
SUICompanionApp/SUICompanionApp/Molecules/ExampleMolecules.swift
hmrc/ios-swiftui-components
fb804f98b5a00164cabc14a7183f02ae40dcc234
[ "Apache-2.0" ]
3
2021-08-19T06:43:35.000Z
2022-02-11T14:22:13.000Z
SUICompanionApp/SUICompanionApp/Molecules/ExampleMolecules.swift
hmrc/ios-swiftui-components
fb804f98b5a00164cabc14a7183f02ae40dcc234
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 HM Revenue & Customs * * 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. */ import SwiftUI import SUIComponents extension Components.Molecules.IconButtonView: Examplable { static var title: String { "IconButtonView" } static var exampleBackgroundColor: Color { Color.Semantic.pageBackground } static func withPlaceholders() -> AnyView { AnyView( Components.Molecules.IconButtonView( model: .init( icon: Example.Images.info.image, title: "Title", iconTintColor: TextStyle.link.textColor, accessibilityHint: "AccessibilityHint", accessibilityIdentifier: "AccessibilityIdentifier", handler: { print("Icon Button View Tapped") } ) ) ) } static func examples() -> AnyView { AnyView(VStack(spacing: .spacer16) { Components.Molecules.IconButtonView( model: .init( icon: Example.Images.help.image, title: "About the calculator", iconTintColor: TextStyle.link.textColor, accessibilityHint: "AccessibilityHint", accessibilityIdentifier: "AccessibilityIdentifier", handler: { print("About the calculator Tapped") } ) ).cardView() Components.Molecules.IconButtonView( model: .init( icon: Example.Images.help.image, title: Example.Text.longerIpsum, iconTintColor: TextStyle.link.textColor, accessibilityHint: "AccessibilityHint", accessibilityIdentifier: "AccessibilityIdentifier", handler: { print("Lorem Ipsum tapped") } ) ).cardView() }) } } extension Components.Molecules.StatusView: Examplable { static var title: String { "StatusView" } static var exampleBackgroundColor: Color { Color.Semantic.pageBackground } static func withPlaceholders() -> AnyView { AnyView( Components.Molecules.StatusView( model: .init( icon: Example.Images.maintenance.image, title: "Title", body: "Body" ) ) ) } static func examples() -> AnyView { AnyView(VStack(spacing: .spacer16) { Components.Molecules.StatusView( model: .init( icon: Example.Images.maintenance.image, title: "Service unavailable", body: "You'll need to try again later." ) ).cardView() Components.Molecules.StatusView( model: .init( icon: Example.Images.info.image, title: "Your Help to Save account closed on 21 May 2018" ) ).cardView() Components.Molecules.StatusView( model: .init( icon: Example.Images.coins.image, title: Example.Text.longerIpsum, body: Example.Text.longestIpsum, iconTintColor: Color.Semantic.primaryButtonBackground ) ).cardView() }) } } extension Components.Molecules.TitleBodyView: Examplable { static var title: String { "TitleBodyView" } static var exampleBackgroundColor: Color { Color.Semantic.pageBackground } static func withPlaceholders() -> AnyView { AnyView( Components.Molecules.TitleBodyView( model: .init( title: "Title", body: "Body", style: .H3 ) ) ) } static func examples() -> AnyView { AnyView(VStack(spacing: .spacer16) { Components.Molecules.TitleBodyView( model: .init( title: "Pay As You Earn", body: "6 April 2018 to 5 April 2019", style: .H4 ) ).cardView() Components.Molecules.TitleBodyView( model: .init( title: "You don't have any money in this account.", body: "Your closing balance of £240 was transferred to your UK bank account on 28 February 2020.", style: .H5 ) ).cardView() Components.Molecules.TitleBodyView( model: .init( title: "Date and time", body: "7 February 2019 at 17:12:45 GMT", style: .bold ) ).cardView() Components.Molecules.TitleBodyView( model: .init( title: "Body label is only added shown if body parameter present", body: "", style: .bold ) ).cardView() }) } } extension Components.Molecules.SwitchRowView: Examplable { static var title: String { "SwitchRowView" } static var exampleBackgroundColor: Color { Color.Semantic.pageBackground } static func withPlaceholders() -> AnyView { AnyView( exampleView( initialState: false, titleBodyModel: .init( title: "Switch Row Title", body: "Switch Row Body", style: .bold ) ) ) } static func examples() -> AnyView { AnyView( VStack { exampleView( initialState: true, titleBodyModel: .init( title: "Start of the month", body: "Get a reminder on the first day of each month", style: .bold ) ).cardView() exampleView( initialState: false, titleBodyModel: .init( title: "End of the month", body: "Get a reminder 5 days before the end of each month", style: .bold ) ).cardView() exampleView( initialState: false, titleBodyModel: .init( title: "Fingerprint ID", body: "", style: .bold ) ).cardView() exampleView( initialState: false, titleBodyModel: .init( title: Example.Text.longIpsum, body: "", style: .bold ) ).cardView() exampleView( initialState: true, titleBodyModel: .init( title: Example.Text.longIpsum, body: Example.Text.longestIpsum, style: .bold ) ).cardView() } ) } private static func exampleView(initialState: Bool, titleBodyModel: Components.Molecules.TitleBodyView.Model) -> Components.Molecules.SwitchRowView { var isOnVar = initialState let isOnBinding = Binding<Bool> { isOnVar } set: { isOn in isOnVar = isOn print("SwitchRow Value did change: \(isOnVar)") } return Components.Molecules.SwitchRowView( isOn: isOnBinding, titleBodyModel: titleBodyModel ) } } extension Components.Molecules.TextInputView: Examplable { static var title: String { "TextInputView" } static var exampleBackgroundColor: Color { Color.Semantic.pageBackground } struct ViewWrapper: View { @State var text: String let model: Components.Molecules.TextInputView.Model let error: String? init(initialText: String = "", model: Components.Molecules.TextInputView.Model, error: String? = nil) { self.text = initialText self.model = model self.error = error } var body: some View { Components.Molecules.TextInputView( text: $text, model: model, validationError: error ) } } static func withPlaceholders() -> AnyView { AnyView( ViewWrapper( model: .init( title: "Title", placeholder: "Placeholder", leftViewText: "@leftText", maxLength: 20 ), error: "Validation Error" ) ) } static func examples() -> AnyView { AnyView( VStack(spacing: .spacer16) { ViewWrapper( initialText: "Enter text", model: .init( title: "Enter text", placeholder: "Enter text here please", maxLength: 0 ) ).cardView() ViewWrapper( initialText: "Some text", model: .init( title: "Enter text", placeholder: "Enter text here please", maxLength: 0 ) ).cardView() ViewWrapper( initialText: "Some text", model: .init( title: "Enter text", placeholder: "Enter text here please", maxLength: 10 ) ).cardView() ViewWrapper( initialText: "Some text with limit not enforced", model: .init( title: "Enter text", placeholder: "Enter text here please", maxLength: 10, enforceMaxLength: false ) ).cardView() ViewWrapper( initialText: "Some text", model: .init( title: "Enter text", placeholder: "Enter text here please", maxLength: 100 ), error: "Validation Error" ).cardView() ViewWrapper( initialText: "Multi line\nMultiPass", model: .init( title: "Multi Line", maxLength: 100, multiLine: true ) ).cardView() } ) } } extension Components.Molecules.CurrencyInputView: Examplable { static var title: String { "CurrencyInputView" } static var exampleBackgroundColor: Color { Color.Semantic.pageBackground } struct ViewWrapper: View { @State var text: String let model: Components.Molecules.CurrencyInputView.Model let error: String? init(initialText: String = "", model: Components.Molecules.CurrencyInputView.Model, error: String? = nil) { self.text = initialText self.model = model self.error = error } var body: some View { Components.Molecules.CurrencyInputView( text: $text, model: model, validationError: error ) } } static func withPlaceholders() -> AnyView { AnyView( ViewWrapper( initialText: "InitialText", model: .init(title: "Title", maxLength: 0), error: "Validation Error" ) ) } static func examples() -> AnyView { AnyView( VStack(spacing: .spacer16) { ViewWrapper( initialText: "49.99", model: .init( title: "Pay amount", maxLength: 0 ), error: nil ).cardView() } ) } } extension Components.Molecules.InsetView: Examplable { static var title: String { "InsetView" } static var exampleBackgroundColor: Color { Color.Semantic.pageBackground } static func withPlaceholders() -> AnyView { AnyView( Components.Molecules.InsetView( model: .init( body: "Inset text" ) ) ) } static func examples() -> AnyView { AnyView( VStack(spacing: .spacer16) { Components.Molecules.InsetView( model: .init( body: "Your employer or pension provider takes off Income Tax before they pay you. This is called Pay As You Earn (PAYE). The amount of tax you pay depends on your income, how much of it is tax-free, and your tax code." // swiftlint:disable:this line_length ) ).cardView() Components.Molecules.InsetView( model: .init(content: { VStack(alignment: .leading, spacing: .spacer16) { Text("Child Tax Credit") Text("Working Tax Credit") Text("Another Tax Credit") } }) ).cardView() } ) } }
33.917051
282
0.465965
f54a78074f5651a294b5fca64ab5fd88bc3b4ad6
842
rs
Rust
rust/src/day01/part01.rs
goksgie/advent-of-code-2021
e0df17bac95daf221ab97dbcf3f6bfc36aacf04a
[ "MIT" ]
null
null
null
rust/src/day01/part01.rs
goksgie/advent-of-code-2021
e0df17bac95daf221ab97dbcf3f6bfc36aacf04a
[ "MIT" ]
null
null
null
rust/src/day01/part01.rs
goksgie/advent-of-code-2021
e0df17bac95daf221ab97dbcf3f6bfc36aacf04a
[ "MIT" ]
null
null
null
/// Compute the consequtive increase in the input and output the result /// as u64. pub fn compute_consequtive_increase<'a, T: IntoIterator<Item = &'a u64>>(numbers: T) -> u64 { let mut prev_elem = None; let mut result = 0; for elem in numbers { if let Some(prev) = prev_elem { if elem > prev { result += 1; } } prev_elem = Some(elem); } result } #[test] fn test_compute_increase() { let test_data: Vec<(Vec<u64>, u64)> = vec![ (vec![199, 200, 208, 210, 200, 207, 240, 269, 260, 263], 7), (vec![1, 1, 1, 2, 1, 1, 1], 1) ]; // the following iteration will consume the test data vector. for (test_inp, result) in test_data.iter() { assert_eq!(compute_consequtive_increase(test_inp), *result); } }
27.16129
93
0.557007
81dcfe23900de442446cc0cadde6fffd64db7fc4
1,826
swift
Swift
Example/PTVRPlayer/PTVR/Common/TimeLabel.swift
tienpx-x/PTVRPlayer
b8e3941edaaafac67f3569ccb809dd7b1a1e0a1a
[ "MIT" ]
null
null
null
Example/PTVRPlayer/PTVR/Common/TimeLabel.swift
tienpx-x/PTVRPlayer
b8e3941edaaafac67f3569ccb809dd7b1a1e0a1a
[ "MIT" ]
null
null
null
Example/PTVRPlayer/PTVR/Common/TimeLabel.swift
tienpx-x/PTVRPlayer
b8e3941edaaafac67f3569ccb809dd7b1a1e0a1a
[ "MIT" ]
2
2021-07-12T08:17:45.000Z
2022-02-16T03:05:50.000Z
// // TimeLabel.swift // PTVRPlayer // // Created by Phạm Xuân Tiến on 11/6/20. // Copyright © 2020 CocoaPods. All rights reserved. // class TimeLabel: UILabel { var second: TimeInterval = 0 { didSet { guard !second.isInfinite, !second.isNaN else { self.text = "00:00" return } if second >= 0 { self.text = second.toString() } else { self.text = "- \((-second).toString())" if self.text == "- 00:00" { self.text = "00:00" } } } } override init(frame: CGRect) { super.init(frame: frame) setupView() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupView() } fileprivate func setupView() { textColor = UIColor.white text = "00:00" } } extension TimeInterval { func toHourMinutesSeconds() -> (Int, Int, Int) { guard self > 0 else { return (0, 0, 0) } let hours = floor(self / (60 * 60)) let minutes = floor((self - hours * (60 * 60)) / 60) let seconds = trunc(self - hours * (60 * 60) - minutes * 60) return (Int(hours), Int(minutes), Int(seconds)) } func toString() -> String { let hms = toHourMinutesSeconds() let hour = hms.0 let minute = hms.1 let second = hms.2 let hourStr = String(format: "%02d", hour) let minuteStr = String(format: "%02d", minute) let secondStr = String(format: "%02d", second) if hour == 0 { return "\(minuteStr):\(secondStr)" } else { return "\(hourStr):\(minuteStr):\(secondStr)" } } }
26.085714
68
0.484666
83a7a128dbfc52d480556e124e5c3c03ec04e023
4,348
rs
Rust
src/main.rs
laptou/reactions-telegram-bot
7b044b1e8d9b313836dd99dcf4797f2346b76323
[ "MIT" ]
5
2021-03-21T17:04:52.000Z
2021-12-30T21:18:45.000Z
src/main.rs
laptou/reactions-telegram-bot
7b044b1e8d9b313836dd99dcf4797f2346b76323
[ "MIT" ]
2
2020-10-01T22:11:58.000Z
2020-10-04T17:01:16.000Z
src/main.rs
laptou/reactions-telegram-bot
7b044b1e8d9b313836dd99dcf4797f2346b76323
[ "MIT" ]
1
2021-04-15T13:57:01.000Z
2021-04-15T13:57:01.000Z
use std::{convert::Infallible, env, net::SocketAddr}; use log::{info, warn}; use pretty_env_logger; use teloxide::{dispatching::update_listeners::UpdateListener, utils::command::BotCommand}; use teloxide::{prelude::*, types::*}; use tokio; mod handler; mod reaction; use handler::{handle_callback_query, handle_command}; use warp::{hyper::StatusCode, Filter}; #[derive(BotCommand, PartialEq, Eq, Debug, Clone, Copy)] #[command(rename = "lowercase", description = "These commands are supported:")] pub enum Command { #[command(description = "display this text.")] Help, #[command(description = "react to a message", rename = "r")] React, #[command(description = "react to a message with a ❤")] Heart, #[command(description = "react to a message with a 👍")] Up, #[command(description = "react to a message with a 👎")] Down, #[command(description = "show who reacted to a message", rename = "s")] Show, } #[tokio::main] async fn main() { info!("starting reactions bot"); teloxide::enable_logging!(); info!("token: {:?}", env::var("TELOXIDE_TOKEN").unwrap()); let bot = Bot::from_env(); let listener = webhook(bot.clone()).await; Dispatcher::new(bot) .messages_handler(move |rx: DispatcherHandlerRx<Message>| { rx.for_each_concurrent(None, move |update| async move { if let Some(text) = update.update.text() { if let Ok(cmd) = Command::parse(text, "reaxnbot") { if let Err(err) = handle_command(update, cmd).await { warn!("message response failed: {:?}", err); } } } }) }) .callback_queries_handler(move |rx: DispatcherHandlerRx<CallbackQuery>| { rx.for_each_concurrent(None, move |update| async move { if let Err(err) = handle_callback_query(update).await { warn!("callback query response failed: {:?}", err); } }) }) .dispatch_with_listener(listener, LoggingErrorHandler::new()) .await; } pub async fn webhook<'a>(bot: Bot) -> impl UpdateListener<Infallible> { // Heroku defines auto defines a port value let teloxide_token = env::var("TELOXIDE_TOKEN").expect("TELOXIDE_TOKEN env variable missing"); let port: u16 = env::var("PORT") .expect("PORT env variable missing") .parse() .expect("PORT value to be integer"); let endpoint = format!("bot{}", teloxide_token); let prefix = "reactions"; let url = format!("https://reaxnbot.dev/{}/{}", prefix, endpoint); bot.set_webhook(url) .send() .await .expect("Cannot setup a webhook"); let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); let server = warp::post() .and(warp::path(prefix)) .and(warp::path(endpoint)) .and(warp::body::json()) .map(move |json: serde_json::Value| { let try_parse = match serde_json::from_str(&json.to_string()) { Ok(update) => Ok(update), Err(error) => { log::error!( "Cannot parse an update.\nError: {:?}\nValue: {}\n\ This is a bug in teloxide, please open an issue here: \ https://github.com/teloxide/teloxide/issues.", error, json ); Err(error) } }; if let Ok(update) = try_parse { tx.send(Ok(update)) .expect("Cannot send an incoming update from the webhook") } StatusCode::OK }); let test_route = warp::get() .and(warp::path::tail()) .map(|tail| format!("hello world {:?}", tail)); let server = server.or(test_route).recover(handle_rejection); let serve = warp::serve(server); let address = format!("0.0.0.0:{}", port); tokio::spawn(serve.run(address.parse::<SocketAddr>().unwrap())); rx } async fn handle_rejection(error: warp::Rejection) -> Result<impl warp::Reply, Infallible> { log::error!("Cannot process the request due to: {:?}", error); Ok(StatusCode::INTERNAL_SERVER_ERROR) }
33.705426
98
0.560948
817540ac01c1d32c151242221c98ba5ca0856fee
62,935
rs
Rust
sdk/pi/src/model.rs
ymwjbxxq/aws-sdk-rust
f2b4361b004ee822960ea9791f566fd4eb6d1aba
[ "Apache-2.0" ]
1,415
2021-05-07T20:15:53.000Z
2022-03-31T20:47:15.000Z
sdk/pi/src/model.rs
ymwjbxxq/aws-sdk-rust
f2b4361b004ee822960ea9791f566fd4eb6d1aba
[ "Apache-2.0" ]
253
2021-05-07T21:53:56.000Z
2022-03-29T20:52:47.000Z
sdk/pi/src/model.rs
ymwjbxxq/aws-sdk-rust
f2b4361b004ee822960ea9791f566fd4eb6d1aba
[ "Apache-2.0" ]
108
2021-05-07T20:42:02.000Z
2022-03-28T18:16:53.000Z
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. /// <p>A time-ordered series of data points, corresponding to a dimension of a Performance Insights metric.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct MetricKeyDataPoints { /// <p>The dimension(s) to which the data points apply.</p> pub key: std::option::Option<crate::model::ResponseResourceMetricKey>, /// <p>An array of timestamp-value pairs, representing measurements over a period of time.</p> pub data_points: std::option::Option<std::vec::Vec<crate::model::DataPoint>>, } impl MetricKeyDataPoints { /// <p>The dimension(s) to which the data points apply.</p> pub fn key(&self) -> std::option::Option<&crate::model::ResponseResourceMetricKey> { self.key.as_ref() } /// <p>An array of timestamp-value pairs, representing measurements over a period of time.</p> pub fn data_points(&self) -> std::option::Option<&[crate::model::DataPoint]> { self.data_points.as_deref() } } impl std::fmt::Debug for MetricKeyDataPoints { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("MetricKeyDataPoints"); formatter.field("key", &self.key); formatter.field("data_points", &self.data_points); formatter.finish() } } /// See [`MetricKeyDataPoints`](crate::model::MetricKeyDataPoints) pub mod metric_key_data_points { /// A builder for [`MetricKeyDataPoints`](crate::model::MetricKeyDataPoints) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) key: std::option::Option<crate::model::ResponseResourceMetricKey>, pub(crate) data_points: std::option::Option<std::vec::Vec<crate::model::DataPoint>>, } impl Builder { /// <p>The dimension(s) to which the data points apply.</p> pub fn key(mut self, input: crate::model::ResponseResourceMetricKey) -> Self { self.key = Some(input); self } /// <p>The dimension(s) to which the data points apply.</p> pub fn set_key( mut self, input: std::option::Option<crate::model::ResponseResourceMetricKey>, ) -> Self { self.key = input; self } /// Appends an item to `data_points`. /// /// To override the contents of this collection use [`set_data_points`](Self::set_data_points). /// /// <p>An array of timestamp-value pairs, representing measurements over a period of time.</p> pub fn data_points(mut self, input: crate::model::DataPoint) -> Self { let mut v = self.data_points.unwrap_or_default(); v.push(input); self.data_points = Some(v); self } /// <p>An array of timestamp-value pairs, representing measurements over a period of time.</p> pub fn set_data_points( mut self, input: std::option::Option<std::vec::Vec<crate::model::DataPoint>>, ) -> Self { self.data_points = input; self } /// Consumes the builder and constructs a [`MetricKeyDataPoints`](crate::model::MetricKeyDataPoints) pub fn build(self) -> crate::model::MetricKeyDataPoints { crate::model::MetricKeyDataPoints { key: self.key, data_points: self.data_points, } } } } impl MetricKeyDataPoints { /// Creates a new builder-style object to manufacture [`MetricKeyDataPoints`](crate::model::MetricKeyDataPoints) pub fn builder() -> crate::model::metric_key_data_points::Builder { crate::model::metric_key_data_points::Builder::default() } } /// <p>A timestamp, and a single numerical value, which together represent a measurement at a particular point in time.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DataPoint { /// <p>The time, in epoch format, associated with a particular <code>Value</code>.</p> pub timestamp: std::option::Option<aws_smithy_types::DateTime>, /// <p>The actual value associated with a particular <code>Timestamp</code>.</p> pub value: std::option::Option<f64>, } impl DataPoint { /// <p>The time, in epoch format, associated with a particular <code>Value</code>.</p> pub fn timestamp(&self) -> std::option::Option<&aws_smithy_types::DateTime> { self.timestamp.as_ref() } /// <p>The actual value associated with a particular <code>Timestamp</code>.</p> pub fn value(&self) -> std::option::Option<f64> { self.value } } impl std::fmt::Debug for DataPoint { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DataPoint"); formatter.field("timestamp", &self.timestamp); formatter.field("value", &self.value); formatter.finish() } } /// See [`DataPoint`](crate::model::DataPoint) pub mod data_point { /// A builder for [`DataPoint`](crate::model::DataPoint) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) timestamp: std::option::Option<aws_smithy_types::DateTime>, pub(crate) value: std::option::Option<f64>, } impl Builder { /// <p>The time, in epoch format, associated with a particular <code>Value</code>.</p> pub fn timestamp(mut self, input: aws_smithy_types::DateTime) -> Self { self.timestamp = Some(input); self } /// <p>The time, in epoch format, associated with a particular <code>Value</code>.</p> pub fn set_timestamp( mut self, input: std::option::Option<aws_smithy_types::DateTime>, ) -> Self { self.timestamp = input; self } /// <p>The actual value associated with a particular <code>Timestamp</code>.</p> pub fn value(mut self, input: f64) -> Self { self.value = Some(input); self } /// <p>The actual value associated with a particular <code>Timestamp</code>.</p> pub fn set_value(mut self, input: std::option::Option<f64>) -> Self { self.value = input; self } /// Consumes the builder and constructs a [`DataPoint`](crate::model::DataPoint) pub fn build(self) -> crate::model::DataPoint { crate::model::DataPoint { timestamp: self.timestamp, value: self.value, } } } } impl DataPoint { /// Creates a new builder-style object to manufacture [`DataPoint`](crate::model::DataPoint) pub fn builder() -> crate::model::data_point::Builder { crate::model::data_point::Builder::default() } } /// <p>An object describing a Performance Insights metric and one or more dimensions for that metric.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ResponseResourceMetricKey { /// <p>The name of a Performance Insights metric to be measured.</p> /// <p>Valid values for <code>Metric</code> are:</p> /// <ul> /// <li> <p> <code>db.load.avg</code> - a scaled representation of the number of active sessions for the database engine.</p> </li> /// <li> <p> <code>db.sampledload.avg</code> - the raw number of active sessions for the database engine.</p> </li> /// </ul> /// <p>If the number of active sessions is less than an internal Performance Insights threshold, <code>db.load.avg</code> and <code>db.sampledload.avg</code> are the same value. If the number of active sessions is greater than the internal threshold, Performance Insights samples the active sessions, with <code>db.load.avg</code> showing the scaled values, <code>db.sampledload.avg</code> showing the raw values, and <code>db.sampledload.avg</code> less than <code>db.load.avg</code>. For most use cases, you can query <code>db.load.avg</code> only. </p> pub metric: std::option::Option<std::string::String>, /// <p>The valid dimensions for the metric.</p> pub dimensions: std::option::Option<std::collections::HashMap<std::string::String, std::string::String>>, } impl ResponseResourceMetricKey { /// <p>The name of a Performance Insights metric to be measured.</p> /// <p>Valid values for <code>Metric</code> are:</p> /// <ul> /// <li> <p> <code>db.load.avg</code> - a scaled representation of the number of active sessions for the database engine.</p> </li> /// <li> <p> <code>db.sampledload.avg</code> - the raw number of active sessions for the database engine.</p> </li> /// </ul> /// <p>If the number of active sessions is less than an internal Performance Insights threshold, <code>db.load.avg</code> and <code>db.sampledload.avg</code> are the same value. If the number of active sessions is greater than the internal threshold, Performance Insights samples the active sessions, with <code>db.load.avg</code> showing the scaled values, <code>db.sampledload.avg</code> showing the raw values, and <code>db.sampledload.avg</code> less than <code>db.load.avg</code>. For most use cases, you can query <code>db.load.avg</code> only. </p> pub fn metric(&self) -> std::option::Option<&str> { self.metric.as_deref() } /// <p>The valid dimensions for the metric.</p> pub fn dimensions( &self, ) -> std::option::Option<&std::collections::HashMap<std::string::String, std::string::String>> { self.dimensions.as_ref() } } impl std::fmt::Debug for ResponseResourceMetricKey { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ResponseResourceMetricKey"); formatter.field("metric", &self.metric); formatter.field("dimensions", &self.dimensions); formatter.finish() } } /// See [`ResponseResourceMetricKey`](crate::model::ResponseResourceMetricKey) pub mod response_resource_metric_key { /// A builder for [`ResponseResourceMetricKey`](crate::model::ResponseResourceMetricKey) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) metric: std::option::Option<std::string::String>, pub(crate) dimensions: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, } impl Builder { /// <p>The name of a Performance Insights metric to be measured.</p> /// <p>Valid values for <code>Metric</code> are:</p> /// <ul> /// <li> <p> <code>db.load.avg</code> - a scaled representation of the number of active sessions for the database engine.</p> </li> /// <li> <p> <code>db.sampledload.avg</code> - the raw number of active sessions for the database engine.</p> </li> /// </ul> /// <p>If the number of active sessions is less than an internal Performance Insights threshold, <code>db.load.avg</code> and <code>db.sampledload.avg</code> are the same value. If the number of active sessions is greater than the internal threshold, Performance Insights samples the active sessions, with <code>db.load.avg</code> showing the scaled values, <code>db.sampledload.avg</code> showing the raw values, and <code>db.sampledload.avg</code> less than <code>db.load.avg</code>. For most use cases, you can query <code>db.load.avg</code> only. </p> pub fn metric(mut self, input: impl Into<std::string::String>) -> Self { self.metric = Some(input.into()); self } /// <p>The name of a Performance Insights metric to be measured.</p> /// <p>Valid values for <code>Metric</code> are:</p> /// <ul> /// <li> <p> <code>db.load.avg</code> - a scaled representation of the number of active sessions for the database engine.</p> </li> /// <li> <p> <code>db.sampledload.avg</code> - the raw number of active sessions for the database engine.</p> </li> /// </ul> /// <p>If the number of active sessions is less than an internal Performance Insights threshold, <code>db.load.avg</code> and <code>db.sampledload.avg</code> are the same value. If the number of active sessions is greater than the internal threshold, Performance Insights samples the active sessions, with <code>db.load.avg</code> showing the scaled values, <code>db.sampledload.avg</code> showing the raw values, and <code>db.sampledload.avg</code> less than <code>db.load.avg</code>. For most use cases, you can query <code>db.load.avg</code> only. </p> pub fn set_metric(mut self, input: std::option::Option<std::string::String>) -> Self { self.metric = input; self } /// Adds a key-value pair to `dimensions`. /// /// To override the contents of this collection use [`set_dimensions`](Self::set_dimensions). /// /// <p>The valid dimensions for the metric.</p> pub fn dimensions( mut self, k: impl Into<std::string::String>, v: impl Into<std::string::String>, ) -> Self { let mut hash_map = self.dimensions.unwrap_or_default(); hash_map.insert(k.into(), v.into()); self.dimensions = Some(hash_map); self } /// <p>The valid dimensions for the metric.</p> pub fn set_dimensions( mut self, input: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, ) -> Self { self.dimensions = input; self } /// Consumes the builder and constructs a [`ResponseResourceMetricKey`](crate::model::ResponseResourceMetricKey) pub fn build(self) -> crate::model::ResponseResourceMetricKey { crate::model::ResponseResourceMetricKey { metric: self.metric, dimensions: self.dimensions, } } } } impl ResponseResourceMetricKey { /// Creates a new builder-style object to manufacture [`ResponseResourceMetricKey`](crate::model::ResponseResourceMetricKey) pub fn builder() -> crate::model::response_resource_metric_key::Builder { crate::model::response_resource_metric_key::Builder::default() } } /// <p>A single query to be processed. You must provide the metric to query. If no other parameters are specified, Performance Insights returns all of the data points for that metric. You can optionally request that the data points be aggregated by dimension group ( <code>GroupBy</code>), and return only those data points that match your criteria (<code>Filter</code>).</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct MetricQuery { /// <p>The name of a Performance Insights metric to be measured.</p> /// <p>Valid values for <code>Metric</code> are:</p> /// <ul> /// <li> <p> <code>db.load.avg</code> - a scaled representation of the number of active sessions for the database engine.</p> </li> /// <li> <p> <code>db.sampledload.avg</code> - the raw number of active sessions for the database engine.</p> </li> /// </ul> /// <p>If the number of active sessions is less than an internal Performance Insights threshold, <code>db.load.avg</code> and <code>db.sampledload.avg</code> are the same value. If the number of active sessions is greater than the internal threshold, Performance Insights samples the active sessions, with <code>db.load.avg</code> showing the scaled values, <code>db.sampledload.avg</code> showing the raw values, and <code>db.sampledload.avg</code> less than <code>db.load.avg</code>. For most use cases, you can query <code>db.load.avg</code> only. </p> pub metric: std::option::Option<std::string::String>, /// <p>A specification for how to aggregate the data points from a query result. You must specify a valid dimension group. Performance Insights will return all of the dimensions within that group, unless you provide the names of specific dimensions within that group. You can also request that Performance Insights return a limited number of values for a dimension.</p> pub group_by: std::option::Option<crate::model::DimensionGroup>, /// <p>One or more filters to apply in the request. Restrictions:</p> /// <ul> /// <li> <p>Any number of filters by the same dimension, as specified in the <code>GroupBy</code> parameter.</p> </li> /// <li> <p>A single filter for any other dimension in this dimension group.</p> </li> /// </ul> pub filter: std::option::Option<std::collections::HashMap<std::string::String, std::string::String>>, } impl MetricQuery { /// <p>The name of a Performance Insights metric to be measured.</p> /// <p>Valid values for <code>Metric</code> are:</p> /// <ul> /// <li> <p> <code>db.load.avg</code> - a scaled representation of the number of active sessions for the database engine.</p> </li> /// <li> <p> <code>db.sampledload.avg</code> - the raw number of active sessions for the database engine.</p> </li> /// </ul> /// <p>If the number of active sessions is less than an internal Performance Insights threshold, <code>db.load.avg</code> and <code>db.sampledload.avg</code> are the same value. If the number of active sessions is greater than the internal threshold, Performance Insights samples the active sessions, with <code>db.load.avg</code> showing the scaled values, <code>db.sampledload.avg</code> showing the raw values, and <code>db.sampledload.avg</code> less than <code>db.load.avg</code>. For most use cases, you can query <code>db.load.avg</code> only. </p> pub fn metric(&self) -> std::option::Option<&str> { self.metric.as_deref() } /// <p>A specification for how to aggregate the data points from a query result. You must specify a valid dimension group. Performance Insights will return all of the dimensions within that group, unless you provide the names of specific dimensions within that group. You can also request that Performance Insights return a limited number of values for a dimension.</p> pub fn group_by(&self) -> std::option::Option<&crate::model::DimensionGroup> { self.group_by.as_ref() } /// <p>One or more filters to apply in the request. Restrictions:</p> /// <ul> /// <li> <p>Any number of filters by the same dimension, as specified in the <code>GroupBy</code> parameter.</p> </li> /// <li> <p>A single filter for any other dimension in this dimension group.</p> </li> /// </ul> pub fn filter( &self, ) -> std::option::Option<&std::collections::HashMap<std::string::String, std::string::String>> { self.filter.as_ref() } } impl std::fmt::Debug for MetricQuery { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("MetricQuery"); formatter.field("metric", &self.metric); formatter.field("group_by", &self.group_by); formatter.field("filter", &self.filter); formatter.finish() } } /// See [`MetricQuery`](crate::model::MetricQuery) pub mod metric_query { /// A builder for [`MetricQuery`](crate::model::MetricQuery) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) metric: std::option::Option<std::string::String>, pub(crate) group_by: std::option::Option<crate::model::DimensionGroup>, pub(crate) filter: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, } impl Builder { /// <p>The name of a Performance Insights metric to be measured.</p> /// <p>Valid values for <code>Metric</code> are:</p> /// <ul> /// <li> <p> <code>db.load.avg</code> - a scaled representation of the number of active sessions for the database engine.</p> </li> /// <li> <p> <code>db.sampledload.avg</code> - the raw number of active sessions for the database engine.</p> </li> /// </ul> /// <p>If the number of active sessions is less than an internal Performance Insights threshold, <code>db.load.avg</code> and <code>db.sampledload.avg</code> are the same value. If the number of active sessions is greater than the internal threshold, Performance Insights samples the active sessions, with <code>db.load.avg</code> showing the scaled values, <code>db.sampledload.avg</code> showing the raw values, and <code>db.sampledload.avg</code> less than <code>db.load.avg</code>. For most use cases, you can query <code>db.load.avg</code> only. </p> pub fn metric(mut self, input: impl Into<std::string::String>) -> Self { self.metric = Some(input.into()); self } /// <p>The name of a Performance Insights metric to be measured.</p> /// <p>Valid values for <code>Metric</code> are:</p> /// <ul> /// <li> <p> <code>db.load.avg</code> - a scaled representation of the number of active sessions for the database engine.</p> </li> /// <li> <p> <code>db.sampledload.avg</code> - the raw number of active sessions for the database engine.</p> </li> /// </ul> /// <p>If the number of active sessions is less than an internal Performance Insights threshold, <code>db.load.avg</code> and <code>db.sampledload.avg</code> are the same value. If the number of active sessions is greater than the internal threshold, Performance Insights samples the active sessions, with <code>db.load.avg</code> showing the scaled values, <code>db.sampledload.avg</code> showing the raw values, and <code>db.sampledload.avg</code> less than <code>db.load.avg</code>. For most use cases, you can query <code>db.load.avg</code> only. </p> pub fn set_metric(mut self, input: std::option::Option<std::string::String>) -> Self { self.metric = input; self } /// <p>A specification for how to aggregate the data points from a query result. You must specify a valid dimension group. Performance Insights will return all of the dimensions within that group, unless you provide the names of specific dimensions within that group. You can also request that Performance Insights return a limited number of values for a dimension.</p> pub fn group_by(mut self, input: crate::model::DimensionGroup) -> Self { self.group_by = Some(input); self } /// <p>A specification for how to aggregate the data points from a query result. You must specify a valid dimension group. Performance Insights will return all of the dimensions within that group, unless you provide the names of specific dimensions within that group. You can also request that Performance Insights return a limited number of values for a dimension.</p> pub fn set_group_by( mut self, input: std::option::Option<crate::model::DimensionGroup>, ) -> Self { self.group_by = input; self } /// Adds a key-value pair to `filter`. /// /// To override the contents of this collection use [`set_filter`](Self::set_filter). /// /// <p>One or more filters to apply in the request. Restrictions:</p> /// <ul> /// <li> <p>Any number of filters by the same dimension, as specified in the <code>GroupBy</code> parameter.</p> </li> /// <li> <p>A single filter for any other dimension in this dimension group.</p> </li> /// </ul> pub fn filter( mut self, k: impl Into<std::string::String>, v: impl Into<std::string::String>, ) -> Self { let mut hash_map = self.filter.unwrap_or_default(); hash_map.insert(k.into(), v.into()); self.filter = Some(hash_map); self } /// <p>One or more filters to apply in the request. Restrictions:</p> /// <ul> /// <li> <p>Any number of filters by the same dimension, as specified in the <code>GroupBy</code> parameter.</p> </li> /// <li> <p>A single filter for any other dimension in this dimension group.</p> </li> /// </ul> pub fn set_filter( mut self, input: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, ) -> Self { self.filter = input; self } /// Consumes the builder and constructs a [`MetricQuery`](crate::model::MetricQuery) pub fn build(self) -> crate::model::MetricQuery { crate::model::MetricQuery { metric: self.metric, group_by: self.group_by, filter: self.filter, } } } } impl MetricQuery { /// Creates a new builder-style object to manufacture [`MetricQuery`](crate::model::MetricQuery) pub fn builder() -> crate::model::metric_query::Builder { crate::model::metric_query::Builder::default() } } /// <p>A logical grouping of Performance Insights metrics for a related subject area. For example, the <code>db.sql</code> dimension group consists of the following dimensions: <code>db.sql.id</code>, <code>db.sql.db_id</code>, <code>db.sql.statement</code>, and <code>db.sql.tokenized_id</code>.</p> <note> /// <p>Each response element returns a maximum of 500 bytes. For larger elements, such as SQL statements, only the first 500 bytes are returned.</p> /// </note> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DimensionGroup { /// <p>The name of the dimension group. Valid values are:</p> /// <ul> /// <li> <p> <code>db</code> - The name of the database to which the client is connected (only Aurora PostgreSQL, RDS PostgreSQL, Aurora MySQL, RDS MySQL, and MariaDB)</p> </li> /// <li> <p> <code>db.application</code> - The name of the application that is connected to the database (only Aurora PostgreSQL and RDS PostgreSQL)</p> </li> /// <li> <p> <code>db.host</code> - The host name of the connected client (all engines)</p> </li> /// <li> <p> <code>db.session_type</code> - The type of the current session (only Aurora PostgreSQL and RDS PostgreSQL)</p> </li> /// <li> <p> <code>db.sql</code> - The SQL that is currently executing (all engines)</p> </li> /// <li> <p> <code>db.sql_tokenized</code> - The SQL digest (all engines)</p> </li> /// <li> <p> <code>db.wait_event</code> - The event for which the database backend is waiting (all engines)</p> </li> /// <li> <p> <code>db.wait_event_type</code> - The type of event for which the database backend is waiting (all engines)</p> </li> /// <li> <p> <code>db.user</code> - The user logged in to the database (all engines)</p> </li> /// </ul> pub group: std::option::Option<std::string::String>, /// <p>A list of specific dimensions from a dimension group. If this parameter is not present, then it signifies that all of the dimensions in the group were requested, or are present in the response.</p> /// <p>Valid values for elements in the <code>Dimensions</code> array are:</p> /// <ul> /// <li> <p> <code>db.application.name</code> - The name of the application that is connected to the database (only Aurora PostgreSQL and RDS PostgreSQL)</p> </li> /// <li> <p> <code>db.host.id</code> - The host ID of the connected client (all engines)</p> </li> /// <li> <p> <code>db.host.name</code> - The host name of the connected client (all engines)</p> </li> /// <li> <p> <code>db.name</code> - The name of the database to which the client is connected (only Aurora PostgreSQL, RDS PostgreSQL, Aurora MySQL, RDS MySQL, and MariaDB)</p> </li> /// <li> <p> <code>db.session_type.name</code> - The type of the current session (only Aurora PostgreSQL and RDS PostgreSQL)</p> </li> /// <li> <p> <code>db.sql.id</code> - The SQL ID generated by Performance Insights (all engines)</p> </li> /// <li> <p> <code>db.sql.db_id</code> - The SQL ID generated by the database (all engines)</p> </li> /// <li> <p> <code>db.sql.statement</code> - The SQL text that is being executed (all engines)</p> </li> /// <li> <p> <code>db.sql.tokenized_id</code> </p> </li> /// <li> <p> <code>db.sql_tokenized.id</code> - The SQL digest ID generated by Performance Insights (all engines)</p> </li> /// <li> <p> <code>db.sql_tokenized.db_id</code> - SQL digest ID generated by the database (all engines)</p> </li> /// <li> <p> <code>db.sql_tokenized.statement</code> - The SQL digest text (all engines)</p> </li> /// <li> <p> <code>db.user.id</code> - The ID of the user logged in to the database (all engines)</p> </li> /// <li> <p> <code>db.user.name</code> - The name of the user logged in to the database (all engines)</p> </li> /// <li> <p> <code>db.wait_event.name</code> - The event for which the backend is waiting (all engines)</p> </li> /// <li> <p> <code>db.wait_event.type</code> - The type of event for which the backend is waiting (all engines)</p> </li> /// <li> <p> <code>db.wait_event_type.name</code> - The name of the event type for which the backend is waiting (all engines)</p> </li> /// </ul> pub dimensions: std::option::Option<std::vec::Vec<std::string::String>>, /// <p>The maximum number of items to fetch for this dimension group.</p> pub limit: std::option::Option<i32>, } impl DimensionGroup { /// <p>The name of the dimension group. Valid values are:</p> /// <ul> /// <li> <p> <code>db</code> - The name of the database to which the client is connected (only Aurora PostgreSQL, RDS PostgreSQL, Aurora MySQL, RDS MySQL, and MariaDB)</p> </li> /// <li> <p> <code>db.application</code> - The name of the application that is connected to the database (only Aurora PostgreSQL and RDS PostgreSQL)</p> </li> /// <li> <p> <code>db.host</code> - The host name of the connected client (all engines)</p> </li> /// <li> <p> <code>db.session_type</code> - The type of the current session (only Aurora PostgreSQL and RDS PostgreSQL)</p> </li> /// <li> <p> <code>db.sql</code> - The SQL that is currently executing (all engines)</p> </li> /// <li> <p> <code>db.sql_tokenized</code> - The SQL digest (all engines)</p> </li> /// <li> <p> <code>db.wait_event</code> - The event for which the database backend is waiting (all engines)</p> </li> /// <li> <p> <code>db.wait_event_type</code> - The type of event for which the database backend is waiting (all engines)</p> </li> /// <li> <p> <code>db.user</code> - The user logged in to the database (all engines)</p> </li> /// </ul> pub fn group(&self) -> std::option::Option<&str> { self.group.as_deref() } /// <p>A list of specific dimensions from a dimension group. If this parameter is not present, then it signifies that all of the dimensions in the group were requested, or are present in the response.</p> /// <p>Valid values for elements in the <code>Dimensions</code> array are:</p> /// <ul> /// <li> <p> <code>db.application.name</code> - The name of the application that is connected to the database (only Aurora PostgreSQL and RDS PostgreSQL)</p> </li> /// <li> <p> <code>db.host.id</code> - The host ID of the connected client (all engines)</p> </li> /// <li> <p> <code>db.host.name</code> - The host name of the connected client (all engines)</p> </li> /// <li> <p> <code>db.name</code> - The name of the database to which the client is connected (only Aurora PostgreSQL, RDS PostgreSQL, Aurora MySQL, RDS MySQL, and MariaDB)</p> </li> /// <li> <p> <code>db.session_type.name</code> - The type of the current session (only Aurora PostgreSQL and RDS PostgreSQL)</p> </li> /// <li> <p> <code>db.sql.id</code> - The SQL ID generated by Performance Insights (all engines)</p> </li> /// <li> <p> <code>db.sql.db_id</code> - The SQL ID generated by the database (all engines)</p> </li> /// <li> <p> <code>db.sql.statement</code> - The SQL text that is being executed (all engines)</p> </li> /// <li> <p> <code>db.sql.tokenized_id</code> </p> </li> /// <li> <p> <code>db.sql_tokenized.id</code> - The SQL digest ID generated by Performance Insights (all engines)</p> </li> /// <li> <p> <code>db.sql_tokenized.db_id</code> - SQL digest ID generated by the database (all engines)</p> </li> /// <li> <p> <code>db.sql_tokenized.statement</code> - The SQL digest text (all engines)</p> </li> /// <li> <p> <code>db.user.id</code> - The ID of the user logged in to the database (all engines)</p> </li> /// <li> <p> <code>db.user.name</code> - The name of the user logged in to the database (all engines)</p> </li> /// <li> <p> <code>db.wait_event.name</code> - The event for which the backend is waiting (all engines)</p> </li> /// <li> <p> <code>db.wait_event.type</code> - The type of event for which the backend is waiting (all engines)</p> </li> /// <li> <p> <code>db.wait_event_type.name</code> - The name of the event type for which the backend is waiting (all engines)</p> </li> /// </ul> pub fn dimensions(&self) -> std::option::Option<&[std::string::String]> { self.dimensions.as_deref() } /// <p>The maximum number of items to fetch for this dimension group.</p> pub fn limit(&self) -> std::option::Option<i32> { self.limit } } impl std::fmt::Debug for DimensionGroup { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DimensionGroup"); formatter.field("group", &self.group); formatter.field("dimensions", &self.dimensions); formatter.field("limit", &self.limit); formatter.finish() } } /// See [`DimensionGroup`](crate::model::DimensionGroup) pub mod dimension_group { /// A builder for [`DimensionGroup`](crate::model::DimensionGroup) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) group: std::option::Option<std::string::String>, pub(crate) dimensions: std::option::Option<std::vec::Vec<std::string::String>>, pub(crate) limit: std::option::Option<i32>, } impl Builder { /// <p>The name of the dimension group. Valid values are:</p> /// <ul> /// <li> <p> <code>db</code> - The name of the database to which the client is connected (only Aurora PostgreSQL, RDS PostgreSQL, Aurora MySQL, RDS MySQL, and MariaDB)</p> </li> /// <li> <p> <code>db.application</code> - The name of the application that is connected to the database (only Aurora PostgreSQL and RDS PostgreSQL)</p> </li> /// <li> <p> <code>db.host</code> - The host name of the connected client (all engines)</p> </li> /// <li> <p> <code>db.session_type</code> - The type of the current session (only Aurora PostgreSQL and RDS PostgreSQL)</p> </li> /// <li> <p> <code>db.sql</code> - The SQL that is currently executing (all engines)</p> </li> /// <li> <p> <code>db.sql_tokenized</code> - The SQL digest (all engines)</p> </li> /// <li> <p> <code>db.wait_event</code> - The event for which the database backend is waiting (all engines)</p> </li> /// <li> <p> <code>db.wait_event_type</code> - The type of event for which the database backend is waiting (all engines)</p> </li> /// <li> <p> <code>db.user</code> - The user logged in to the database (all engines)</p> </li> /// </ul> pub fn group(mut self, input: impl Into<std::string::String>) -> Self { self.group = Some(input.into()); self } /// <p>The name of the dimension group. Valid values are:</p> /// <ul> /// <li> <p> <code>db</code> - The name of the database to which the client is connected (only Aurora PostgreSQL, RDS PostgreSQL, Aurora MySQL, RDS MySQL, and MariaDB)</p> </li> /// <li> <p> <code>db.application</code> - The name of the application that is connected to the database (only Aurora PostgreSQL and RDS PostgreSQL)</p> </li> /// <li> <p> <code>db.host</code> - The host name of the connected client (all engines)</p> </li> /// <li> <p> <code>db.session_type</code> - The type of the current session (only Aurora PostgreSQL and RDS PostgreSQL)</p> </li> /// <li> <p> <code>db.sql</code> - The SQL that is currently executing (all engines)</p> </li> /// <li> <p> <code>db.sql_tokenized</code> - The SQL digest (all engines)</p> </li> /// <li> <p> <code>db.wait_event</code> - The event for which the database backend is waiting (all engines)</p> </li> /// <li> <p> <code>db.wait_event_type</code> - The type of event for which the database backend is waiting (all engines)</p> </li> /// <li> <p> <code>db.user</code> - The user logged in to the database (all engines)</p> </li> /// </ul> pub fn set_group(mut self, input: std::option::Option<std::string::String>) -> Self { self.group = input; self } /// Appends an item to `dimensions`. /// /// To override the contents of this collection use [`set_dimensions`](Self::set_dimensions). /// /// <p>A list of specific dimensions from a dimension group. If this parameter is not present, then it signifies that all of the dimensions in the group were requested, or are present in the response.</p> /// <p>Valid values for elements in the <code>Dimensions</code> array are:</p> /// <ul> /// <li> <p> <code>db.application.name</code> - The name of the application that is connected to the database (only Aurora PostgreSQL and RDS PostgreSQL)</p> </li> /// <li> <p> <code>db.host.id</code> - The host ID of the connected client (all engines)</p> </li> /// <li> <p> <code>db.host.name</code> - The host name of the connected client (all engines)</p> </li> /// <li> <p> <code>db.name</code> - The name of the database to which the client is connected (only Aurora PostgreSQL, RDS PostgreSQL, Aurora MySQL, RDS MySQL, and MariaDB)</p> </li> /// <li> <p> <code>db.session_type.name</code> - The type of the current session (only Aurora PostgreSQL and RDS PostgreSQL)</p> </li> /// <li> <p> <code>db.sql.id</code> - The SQL ID generated by Performance Insights (all engines)</p> </li> /// <li> <p> <code>db.sql.db_id</code> - The SQL ID generated by the database (all engines)</p> </li> /// <li> <p> <code>db.sql.statement</code> - The SQL text that is being executed (all engines)</p> </li> /// <li> <p> <code>db.sql.tokenized_id</code> </p> </li> /// <li> <p> <code>db.sql_tokenized.id</code> - The SQL digest ID generated by Performance Insights (all engines)</p> </li> /// <li> <p> <code>db.sql_tokenized.db_id</code> - SQL digest ID generated by the database (all engines)</p> </li> /// <li> <p> <code>db.sql_tokenized.statement</code> - The SQL digest text (all engines)</p> </li> /// <li> <p> <code>db.user.id</code> - The ID of the user logged in to the database (all engines)</p> </li> /// <li> <p> <code>db.user.name</code> - The name of the user logged in to the database (all engines)</p> </li> /// <li> <p> <code>db.wait_event.name</code> - The event for which the backend is waiting (all engines)</p> </li> /// <li> <p> <code>db.wait_event.type</code> - The type of event for which the backend is waiting (all engines)</p> </li> /// <li> <p> <code>db.wait_event_type.name</code> - The name of the event type for which the backend is waiting (all engines)</p> </li> /// </ul> pub fn dimensions(mut self, input: impl Into<std::string::String>) -> Self { let mut v = self.dimensions.unwrap_or_default(); v.push(input.into()); self.dimensions = Some(v); self } /// <p>A list of specific dimensions from a dimension group. If this parameter is not present, then it signifies that all of the dimensions in the group were requested, or are present in the response.</p> /// <p>Valid values for elements in the <code>Dimensions</code> array are:</p> /// <ul> /// <li> <p> <code>db.application.name</code> - The name of the application that is connected to the database (only Aurora PostgreSQL and RDS PostgreSQL)</p> </li> /// <li> <p> <code>db.host.id</code> - The host ID of the connected client (all engines)</p> </li> /// <li> <p> <code>db.host.name</code> - The host name of the connected client (all engines)</p> </li> /// <li> <p> <code>db.name</code> - The name of the database to which the client is connected (only Aurora PostgreSQL, RDS PostgreSQL, Aurora MySQL, RDS MySQL, and MariaDB)</p> </li> /// <li> <p> <code>db.session_type.name</code> - The type of the current session (only Aurora PostgreSQL and RDS PostgreSQL)</p> </li> /// <li> <p> <code>db.sql.id</code> - The SQL ID generated by Performance Insights (all engines)</p> </li> /// <li> <p> <code>db.sql.db_id</code> - The SQL ID generated by the database (all engines)</p> </li> /// <li> <p> <code>db.sql.statement</code> - The SQL text that is being executed (all engines)</p> </li> /// <li> <p> <code>db.sql.tokenized_id</code> </p> </li> /// <li> <p> <code>db.sql_tokenized.id</code> - The SQL digest ID generated by Performance Insights (all engines)</p> </li> /// <li> <p> <code>db.sql_tokenized.db_id</code> - SQL digest ID generated by the database (all engines)</p> </li> /// <li> <p> <code>db.sql_tokenized.statement</code> - The SQL digest text (all engines)</p> </li> /// <li> <p> <code>db.user.id</code> - The ID of the user logged in to the database (all engines)</p> </li> /// <li> <p> <code>db.user.name</code> - The name of the user logged in to the database (all engines)</p> </li> /// <li> <p> <code>db.wait_event.name</code> - The event for which the backend is waiting (all engines)</p> </li> /// <li> <p> <code>db.wait_event.type</code> - The type of event for which the backend is waiting (all engines)</p> </li> /// <li> <p> <code>db.wait_event_type.name</code> - The name of the event type for which the backend is waiting (all engines)</p> </li> /// </ul> pub fn set_dimensions( mut self, input: std::option::Option<std::vec::Vec<std::string::String>>, ) -> Self { self.dimensions = input; self } /// <p>The maximum number of items to fetch for this dimension group.</p> pub fn limit(mut self, input: i32) -> Self { self.limit = Some(input); self } /// <p>The maximum number of items to fetch for this dimension group.</p> pub fn set_limit(mut self, input: std::option::Option<i32>) -> Self { self.limit = input; self } /// Consumes the builder and constructs a [`DimensionGroup`](crate::model::DimensionGroup) pub fn build(self) -> crate::model::DimensionGroup { crate::model::DimensionGroup { group: self.group, dimensions: self.dimensions, limit: self.limit, } } } } impl DimensionGroup { /// Creates a new builder-style object to manufacture [`DimensionGroup`](crate::model::DimensionGroup) pub fn builder() -> crate::model::dimension_group::Builder { crate::model::dimension_group::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum ServiceType { #[allow(missing_docs)] // documentation missing in model Rds, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for ServiceType { fn from(s: &str) -> Self { match s { "RDS" => ServiceType::Rds, other => ServiceType::Unknown(other.to_owned()), } } } impl std::str::FromStr for ServiceType { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(ServiceType::from(s)) } } impl ServiceType { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { ServiceType::Rds => "RDS", ServiceType::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &["RDS"] } } impl AsRef<str> for ServiceType { fn as_ref(&self) -> &str { self.as_str() } } /// <p>An object that describes the details for a specified dimension.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DimensionKeyDetail { /// <p>The value of the dimension detail data. For the <code>db.sql.statement</code> dimension, this value is either the full or truncated SQL query, depending on the return status.</p> pub value: std::option::Option<std::string::String>, /// <p>The full name of the dimension. The full name includes the group name and key name. The only valid value is <code>db.sql.statement</code>. </p> pub dimension: std::option::Option<std::string::String>, /// <p>The status of the dimension detail data. Possible values include the following:</p> /// <ul> /// <li> <p> <code>AVAILABLE</code> - The dimension detail data is ready to be retrieved.</p> </li> /// <li> <p> <code>PROCESSING</code> - The dimension detail data isn't ready to be retrieved because more processing time is required. If the requested detail data for <code>db.sql.statement</code> has the status <code>PROCESSING</code>, Performance Insights returns the truncated query.</p> </li> /// <li> <p> <code>UNAVAILABLE</code> - The dimension detail data could not be collected successfully.</p> </li> /// </ul> pub status: std::option::Option<crate::model::DetailStatus>, } impl DimensionKeyDetail { /// <p>The value of the dimension detail data. For the <code>db.sql.statement</code> dimension, this value is either the full or truncated SQL query, depending on the return status.</p> pub fn value(&self) -> std::option::Option<&str> { self.value.as_deref() } /// <p>The full name of the dimension. The full name includes the group name and key name. The only valid value is <code>db.sql.statement</code>. </p> pub fn dimension(&self) -> std::option::Option<&str> { self.dimension.as_deref() } /// <p>The status of the dimension detail data. Possible values include the following:</p> /// <ul> /// <li> <p> <code>AVAILABLE</code> - The dimension detail data is ready to be retrieved.</p> </li> /// <li> <p> <code>PROCESSING</code> - The dimension detail data isn't ready to be retrieved because more processing time is required. If the requested detail data for <code>db.sql.statement</code> has the status <code>PROCESSING</code>, Performance Insights returns the truncated query.</p> </li> /// <li> <p> <code>UNAVAILABLE</code> - The dimension detail data could not be collected successfully.</p> </li> /// </ul> pub fn status(&self) -> std::option::Option<&crate::model::DetailStatus> { self.status.as_ref() } } impl std::fmt::Debug for DimensionKeyDetail { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DimensionKeyDetail"); formatter.field("value", &self.value); formatter.field("dimension", &self.dimension); formatter.field("status", &self.status); formatter.finish() } } /// See [`DimensionKeyDetail`](crate::model::DimensionKeyDetail) pub mod dimension_key_detail { /// A builder for [`DimensionKeyDetail`](crate::model::DimensionKeyDetail) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) value: std::option::Option<std::string::String>, pub(crate) dimension: std::option::Option<std::string::String>, pub(crate) status: std::option::Option<crate::model::DetailStatus>, } impl Builder { /// <p>The value of the dimension detail data. For the <code>db.sql.statement</code> dimension, this value is either the full or truncated SQL query, depending on the return status.</p> pub fn value(mut self, input: impl Into<std::string::String>) -> Self { self.value = Some(input.into()); self } /// <p>The value of the dimension detail data. For the <code>db.sql.statement</code> dimension, this value is either the full or truncated SQL query, depending on the return status.</p> pub fn set_value(mut self, input: std::option::Option<std::string::String>) -> Self { self.value = input; self } /// <p>The full name of the dimension. The full name includes the group name and key name. The only valid value is <code>db.sql.statement</code>. </p> pub fn dimension(mut self, input: impl Into<std::string::String>) -> Self { self.dimension = Some(input.into()); self } /// <p>The full name of the dimension. The full name includes the group name and key name. The only valid value is <code>db.sql.statement</code>. </p> pub fn set_dimension(mut self, input: std::option::Option<std::string::String>) -> Self { self.dimension = input; self } /// <p>The status of the dimension detail data. Possible values include the following:</p> /// <ul> /// <li> <p> <code>AVAILABLE</code> - The dimension detail data is ready to be retrieved.</p> </li> /// <li> <p> <code>PROCESSING</code> - The dimension detail data isn't ready to be retrieved because more processing time is required. If the requested detail data for <code>db.sql.statement</code> has the status <code>PROCESSING</code>, Performance Insights returns the truncated query.</p> </li> /// <li> <p> <code>UNAVAILABLE</code> - The dimension detail data could not be collected successfully.</p> </li> /// </ul> pub fn status(mut self, input: crate::model::DetailStatus) -> Self { self.status = Some(input); self } /// <p>The status of the dimension detail data. Possible values include the following:</p> /// <ul> /// <li> <p> <code>AVAILABLE</code> - The dimension detail data is ready to be retrieved.</p> </li> /// <li> <p> <code>PROCESSING</code> - The dimension detail data isn't ready to be retrieved because more processing time is required. If the requested detail data for <code>db.sql.statement</code> has the status <code>PROCESSING</code>, Performance Insights returns the truncated query.</p> </li> /// <li> <p> <code>UNAVAILABLE</code> - The dimension detail data could not be collected successfully.</p> </li> /// </ul> pub fn set_status( mut self, input: std::option::Option<crate::model::DetailStatus>, ) -> Self { self.status = input; self } /// Consumes the builder and constructs a [`DimensionKeyDetail`](crate::model::DimensionKeyDetail) pub fn build(self) -> crate::model::DimensionKeyDetail { crate::model::DimensionKeyDetail { value: self.value, dimension: self.dimension, status: self.status, } } } } impl DimensionKeyDetail { /// Creates a new builder-style object to manufacture [`DimensionKeyDetail`](crate::model::DimensionKeyDetail) pub fn builder() -> crate::model::dimension_key_detail::Builder { crate::model::dimension_key_detail::Builder::default() } } #[allow(missing_docs)] // documentation missing in model #[non_exhaustive] #[derive( std::clone::Clone, std::cmp::Eq, std::cmp::Ord, std::cmp::PartialEq, std::cmp::PartialOrd, std::fmt::Debug, std::hash::Hash, )] pub enum DetailStatus { #[allow(missing_docs)] // documentation missing in model Available, #[allow(missing_docs)] // documentation missing in model Processing, #[allow(missing_docs)] // documentation missing in model Unavailable, /// Unknown contains new variants that have been added since this code was generated. Unknown(String), } impl std::convert::From<&str> for DetailStatus { fn from(s: &str) -> Self { match s { "AVAILABLE" => DetailStatus::Available, "PROCESSING" => DetailStatus::Processing, "UNAVAILABLE" => DetailStatus::Unavailable, other => DetailStatus::Unknown(other.to_owned()), } } } impl std::str::FromStr for DetailStatus { type Err = std::convert::Infallible; fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { Ok(DetailStatus::from(s)) } } impl DetailStatus { /// Returns the `&str` value of the enum member. pub fn as_str(&self) -> &str { match self { DetailStatus::Available => "AVAILABLE", DetailStatus::Processing => "PROCESSING", DetailStatus::Unavailable => "UNAVAILABLE", DetailStatus::Unknown(s) => s.as_ref(), } } /// Returns all the `&str` values of the enum members. pub fn values() -> &'static [&'static str] { &["AVAILABLE", "PROCESSING", "UNAVAILABLE"] } } impl AsRef<str> for DetailStatus { fn as_ref(&self) -> &str { self.as_str() } } /// <p>An array of descriptions and aggregated values for each dimension within a dimension group.</p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct DimensionKeyDescription { /// <p>A map of name-value pairs for the dimensions in the group.</p> pub dimensions: std::option::Option<std::collections::HashMap<std::string::String, std::string::String>>, /// <p>The aggregated metric value for the dimension(s), over the requested time range.</p> pub total: std::option::Option<f64>, /// <p>If <code>PartitionBy</code> was specified, <code>PartitionKeys</code> contains the dimensions that were.</p> pub partitions: std::option::Option<std::vec::Vec<f64>>, } impl DimensionKeyDescription { /// <p>A map of name-value pairs for the dimensions in the group.</p> pub fn dimensions( &self, ) -> std::option::Option<&std::collections::HashMap<std::string::String, std::string::String>> { self.dimensions.as_ref() } /// <p>The aggregated metric value for the dimension(s), over the requested time range.</p> pub fn total(&self) -> std::option::Option<f64> { self.total } /// <p>If <code>PartitionBy</code> was specified, <code>PartitionKeys</code> contains the dimensions that were.</p> pub fn partitions(&self) -> std::option::Option<&[f64]> { self.partitions.as_deref() } } impl std::fmt::Debug for DimensionKeyDescription { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("DimensionKeyDescription"); formatter.field("dimensions", &self.dimensions); formatter.field("total", &self.total); formatter.field("partitions", &self.partitions); formatter.finish() } } /// See [`DimensionKeyDescription`](crate::model::DimensionKeyDescription) pub mod dimension_key_description { /// A builder for [`DimensionKeyDescription`](crate::model::DimensionKeyDescription) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) dimensions: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, pub(crate) total: std::option::Option<f64>, pub(crate) partitions: std::option::Option<std::vec::Vec<f64>>, } impl Builder { /// Adds a key-value pair to `dimensions`. /// /// To override the contents of this collection use [`set_dimensions`](Self::set_dimensions). /// /// <p>A map of name-value pairs for the dimensions in the group.</p> pub fn dimensions( mut self, k: impl Into<std::string::String>, v: impl Into<std::string::String>, ) -> Self { let mut hash_map = self.dimensions.unwrap_or_default(); hash_map.insert(k.into(), v.into()); self.dimensions = Some(hash_map); self } /// <p>A map of name-value pairs for the dimensions in the group.</p> pub fn set_dimensions( mut self, input: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, ) -> Self { self.dimensions = input; self } /// <p>The aggregated metric value for the dimension(s), over the requested time range.</p> pub fn total(mut self, input: f64) -> Self { self.total = Some(input); self } /// <p>The aggregated metric value for the dimension(s), over the requested time range.</p> pub fn set_total(mut self, input: std::option::Option<f64>) -> Self { self.total = input; self } /// Appends an item to `partitions`. /// /// To override the contents of this collection use [`set_partitions`](Self::set_partitions). /// /// <p>If <code>PartitionBy</code> was specified, <code>PartitionKeys</code> contains the dimensions that were.</p> pub fn partitions(mut self, input: f64) -> Self { let mut v = self.partitions.unwrap_or_default(); v.push(input); self.partitions = Some(v); self } /// <p>If <code>PartitionBy</code> was specified, <code>PartitionKeys</code> contains the dimensions that were.</p> pub fn set_partitions(mut self, input: std::option::Option<std::vec::Vec<f64>>) -> Self { self.partitions = input; self } /// Consumes the builder and constructs a [`DimensionKeyDescription`](crate::model::DimensionKeyDescription) pub fn build(self) -> crate::model::DimensionKeyDescription { crate::model::DimensionKeyDescription { dimensions: self.dimensions, total: self.total, partitions: self.partitions, } } } } impl DimensionKeyDescription { /// Creates a new builder-style object to manufacture [`DimensionKeyDescription`](crate::model::DimensionKeyDescription) pub fn builder() -> crate::model::dimension_key_description::Builder { crate::model::dimension_key_description::Builder::default() } } /// <p>If <code>PartitionBy</code> was specified in a <code>DescribeDimensionKeys</code> request, the dimensions are returned in an array. Each element in the array specifies one dimension. </p> #[non_exhaustive] #[derive(std::clone::Clone, std::cmp::PartialEq)] pub struct ResponsePartitionKey { /// <p>A dimension map that contains the dimension(s) for this partition.</p> pub dimensions: std::option::Option<std::collections::HashMap<std::string::String, std::string::String>>, } impl ResponsePartitionKey { /// <p>A dimension map that contains the dimension(s) for this partition.</p> pub fn dimensions( &self, ) -> std::option::Option<&std::collections::HashMap<std::string::String, std::string::String>> { self.dimensions.as_ref() } } impl std::fmt::Debug for ResponsePartitionKey { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut formatter = f.debug_struct("ResponsePartitionKey"); formatter.field("dimensions", &self.dimensions); formatter.finish() } } /// See [`ResponsePartitionKey`](crate::model::ResponsePartitionKey) pub mod response_partition_key { /// A builder for [`ResponsePartitionKey`](crate::model::ResponsePartitionKey) #[non_exhaustive] #[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)] pub struct Builder { pub(crate) dimensions: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, } impl Builder { /// Adds a key-value pair to `dimensions`. /// /// To override the contents of this collection use [`set_dimensions`](Self::set_dimensions). /// /// <p>A dimension map that contains the dimension(s) for this partition.</p> pub fn dimensions( mut self, k: impl Into<std::string::String>, v: impl Into<std::string::String>, ) -> Self { let mut hash_map = self.dimensions.unwrap_or_default(); hash_map.insert(k.into(), v.into()); self.dimensions = Some(hash_map); self } /// <p>A dimension map that contains the dimension(s) for this partition.</p> pub fn set_dimensions( mut self, input: std::option::Option< std::collections::HashMap<std::string::String, std::string::String>, >, ) -> Self { self.dimensions = input; self } /// Consumes the builder and constructs a [`ResponsePartitionKey`](crate::model::ResponsePartitionKey) pub fn build(self) -> crate::model::ResponsePartitionKey { crate::model::ResponsePartitionKey { dimensions: self.dimensions, } } } } impl ResponsePartitionKey { /// Creates a new builder-style object to manufacture [`ResponsePartitionKey`](crate::model::ResponsePartitionKey) pub fn builder() -> crate::model::response_partition_key::Builder { crate::model::response_partition_key::Builder::default() } }
58.165434
563
0.631159
3fab18ec2a1b8cf81411832e2f1c05c3aef8d8f4
228
asm
Assembly
target/asm/empty-testTemplate.asm
chriscamacho/emu68k
5fc9e79e42b2023277dfa49e7faa7898d0d8ed96
[ "MIT" ]
8
2020-08-29T21:17:23.000Z
2021-12-28T19:35:59.000Z
target/asm/empty-testTemplate.asm
chriscamacho/emu68k
5fc9e79e42b2023277dfa49e7faa7898d0d8ed96
[ "MIT" ]
null
null
null
target/asm/empty-testTemplate.asm
chriscamacho/emu68k
5fc9e79e42b2023277dfa49e7faa7898d0d8ed96
[ "MIT" ]
1
2021-11-02T20:46:48.000Z
2021-11-02T20:46:48.000Z
dc.l $00100000 * SP and PC dc.l $00000400 rorg $400 start: subi.b #1,d0 move.b d0,($A0000) # output to latch move.b ($A0000),d0 # check it reads back. bra.s start # main loop
16.285714
48
0.52193
1e2b6274ab28a1d9151f9a9f25168b8ca932e62e
338
css
CSS
use-css-animation-to-change-the-hover-state-of-a-button.css
ParthKalkar/learning-html-css
5f5169477c57f897180ca77f727fd5137395a974
[ "MIT" ]
null
null
null
use-css-animation-to-change-the-hover-state-of-a-button.css
ParthKalkar/learning-html-css
5f5169477c57f897180ca77f727fd5137395a974
[ "MIT" ]
null
null
null
use-css-animation-to-change-the-hover-state-of-a-button.css
ParthKalkar/learning-html-css
5f5169477c57f897180ca77f727fd5137395a974
[ "MIT" ]
null
null
null
<style> button { border-radius: 5px; color: white; background-color: #0F5897; padding: 5px 10px 8px 10px; } button:hover { animation-name: background-color; animation-duration: 500ms; } @keyframes background-color{ 100% { background-color: #4791d0; } </style> <button>Register</button>
15.363636
37
0.627219
85b09f781bff657bfa1b539e3984457a9d1a791a
7,043
js
JavaScript
js/tree_vis.js
UnofficialJuliaMirrorSnapshots/D3Trees.jl-e3df1716-f71e-5df9-9e2d-98e193103c45
c97f3175a258528c66d7b16f36627c903c9e3a03
[ "MIT" ]
22
2017-09-29T18:22:25.000Z
2021-09-29T19:54:20.000Z
js/tree_vis.js
UnofficialJuliaMirrorSnapshots/D3Trees.jl-e3df1716-f71e-5df9-9e2d-98e193103c45
c97f3175a258528c66d7b16f36627c903c9e3a03
[ "MIT" ]
20
2017-09-27T02:13:55.000Z
2020-07-15T16:01:18.000Z
js/tree_vis.js
UnofficialJuliaMirrorSnapshots/D3Trees.jl-e3df1716-f71e-5df9-9e2d-98e193103c45
c97f3175a258528c66d7b16f36627c903c9e3a03
[ "MIT" ]
6
2018-02-26T18:33:41.000Z
2021-08-03T12:23:42.000Z
if (typeof $ === 'undefined') { loadScript("https://code.jquery.com/jquery-3.1.1.min.js", run); } else { run(); } function run() { if (typeof d3 === 'undefined') { loadScript("https://d3js.org/d3.v3.js", showTree); } else { showTree(); } } function loadScript(url, callback) { console.log("starting script load...") // Adding the script tag to the head as suggested before var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = url; // Then bind the event to the callback function. // There are several events for cross browser compatibility. script.onreadystatechange = callback; script.onload = callback; // Fire the loading head.appendChild(script); } function showTree() { // var margin = {top: 20, right: 120, bottom: 20, left: 120}, var margin = {top: 20, right: 120, bottom: 80, left: 120}, width = $("#"+div).width() - margin.right - margin.left, height = svgHeight - margin.top - margin.bottom; // TODO make height a parameter of TreeVisualizer var i = 0, root; var tree = d3.layout.tree() .size([width, height]); var diagonal = d3.svg.diagonal(); //.projection(function(d) { return [d.y, d.x]; }); // uncomment above to make the tree go horizontally // see http://stackoverflow.com/questions/16265123/resize-svg-when-window-is-resized-in-d3-js if (d3.select("#"+div+"_svg").empty()) { $(".d3twarn").remove(); d3.select("#"+div).append("svg") .attr("id", div+"_svg") .attr("width", width + margin.right + margin.left) .attr("height", height + margin.top + margin.bottom); } d3.select("#"+div+"_svg").selectAll("*").remove(); var svg = d3.select("#"+div+"_svg") .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // console.log("tree data:"); // console.log(treeData[rootID]); root = createDisplayNode(rootID, initExpand); root.x0 = width / 2; root.y0 = 0; update(root, initDuration); console.log("tree should appear"); function createDisplayNode(id, expandLevel) { var dnode = {"dataID":id, "children": null, "_children":null}; if (expandLevel > 0) { initializeChildren(dnode, expandLevel); } return dnode; } function initializeChildren(d, expandLevel) { // create children var children = treeData.children[d.dataID]; d.children = []; if (children) { for (var i = 0; i < children.length; i++) { var cid = children[i]-1; d.children.push(createDisplayNode(cid, expandLevel-1)); } } } /** * Recursively called to update each node in the tree. * * source is a d3 node that has position, etc. */ function update(source, duration) { width = $("#"+div).width() - margin.right - margin.left, height = $("#"+div).height() - margin.top - margin.bottom; tree.size([width,height]); d3.select("#"+div).attr("width", width + margin.right + margin.left) .attr("height", height + margin.top + margin.bottom); d3.select("#"+div+"_svg").attr("width", width + margin.right + margin.left) .attr("height", height + margin.top + margin.bottom); // Compute the new tree layout. var nodes = tree.nodes(root).reverse(), links = tree.links(nodes); // Update the nodes… var node = svg.selectAll("g.node") .data(nodes, function(d) { return d.id || (d.id = ++i); }); // Enter any new nodes at the parent's previous position. var nodeEnter = node.enter().append("g") .attr("class", "node") .attr("transform", function(d) { return "translate(" + source.x0 + "," + source.y0 + ")"; }) .on("click", click) nodeEnter.append("circle") .attr("r", "10px") .attr("style", function(d) { return treeData.style[d.dataID]; } ) var tbox = nodeEnter.append("text") .attr("y", 25) .attr("text-anchor", "middle") //.text( function(d) { return treeData.text[d.dataID]; } ) .style("fill-opacity", 1e-6); tbox.each( function(d) { var el = d3.select(this) var text = treeData.text[d.dataID]; var lines = text.split('\n'); for (var i = 0; i < lines.length; i++) { var tspan = el.append("tspan").text(lines[i]); if (i > 0) { tspan.attr("x", 0).attr("dy", "1.2em"); } } }); //tooltip nodeEnter.append("title").text( function(d) { return treeData.tooltip[d.dataID];} ); // Transition nodes to their new position. var nodeUpdate = node.transition() .duration(duration) .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); nodeUpdate.select("text") .style("fill-opacity", 1); // Transition exiting nodes to the parent's new position. var nodeExit = node.exit().transition() .duration(duration) .attr("transform", function(d) { return "translate(" + source.x + "," + source.y + ")"; }) .remove(); nodeExit.select("text") .style("fill-opacity", 1e-6); // Update the links… var link = svg.selectAll("path.link") .data(links, function(d) { return d.target.id; }); // Enter any new links at the parent's previous position. // XXX link width should be based on transition data, not node data link.enter().insert("path", "g") .attr("class", "link") .attr("style", function(d) { var ls = treeData.link_style[d.target.dataID]; return ls; } ) .attr("d", function(d) { var o = {x: source.x0, y: source.y0}; return diagonal({source: o, target: o}); }); // Transition links to their new position. link.transition() .duration(duration) .attr("d", diagonal); // Transition exiting nodes to the parent's new position. link.exit().transition() .duration(duration) .attr("d", function(d) { var o = {x: source.x, y: source.y}; return diagonal({source: o, target: o}); }) .remove(); // Stash the old positions for transition. nodes.forEach(function(d) { d.x0 = d.x; d.y0 = d.y; }); } // Toggle children on click. function click(d) { if (d.children) { d._children = d.children; d.children = null; } else if (d._children) { d.children = d._children; d._children = null; } else { initializeChildren(d, 1); } update(d, 750); } }
31.441964
102
0.543802
5adc45dcf20cc0bceef7b69f755461f0ee107f2f
2,215
rs
Rust
2017/src/day01.rs
shrugalic/advent_of_code
8d18a3dbdcf847a667ab553f5441676003b9362a
[ "MIT" ]
1
2021-12-17T18:26:17.000Z
2021-12-17T18:26:17.000Z
2017/src/day01.rs
shrugalic/advent_of_code
8d18a3dbdcf847a667ab553f5441676003b9362a
[ "MIT" ]
null
null
null
2017/src/day01.rs
shrugalic/advent_of_code
8d18a3dbdcf847a667ab553f5441676003b9362a
[ "MIT" ]
null
null
null
use line_reader::read_file_to_lines; pub(crate) fn day1_part1() -> u32 { let line = read_file_to_lines("input/day01.txt").remove(0); solve_part1_captcha(line) } pub(crate) fn day1_part2() -> u32 { let line = read_file_to_lines("input/day01.txt").remove(0); solve_part2_captcha(line) } fn solve_part1_captcha<T: AsRef<str>>(line: T) -> u32 { solve_captcha(parse_input(line), 1) } fn solve_part2_captcha<T: AsRef<str>>(line: T) -> u32 { let numbers = parse_input(line); let offset = numbers.len() / 2; solve_captcha(numbers, offset) } fn solve_captcha(mut numbers: Vec<u32>, offset: usize) -> u32 { numbers.extend_from_within(0..offset); numbers .iter() .zip(numbers.iter().skip(offset)) .filter_map(|(a, b)| { // println!("{} <> {}", a, b); if a == b { Some(a) } else { None } }) .sum::<u32>() } fn parse_input<T: AsRef<str>>(line: T) -> Vec<u32> { line.as_ref() .chars() .filter_map(|c| c.to_digit(10)) .collect() } #[cfg(test)] mod tests { use super::*; #[test] fn part1_example1() { assert_eq!(3, solve_part1_captcha("1122")); } #[test] fn part1_example2() { assert_eq!(4, solve_part1_captcha("1111")); } #[test] fn part1_example3() { assert_eq!(0, solve_part1_captcha("1234")); } #[test] fn part1_example4() { assert_eq!(9, solve_part1_captcha("91212129")); } #[test] fn test_day1_part1() { assert_eq!(1144, day1_part1()); } #[test] fn part2_example1() { assert_eq!(6, solve_part2_captcha("1212")); } #[test] fn part2_example2() { assert_eq!(0, solve_part2_captcha("1221")); } #[test] fn part2_example3() { assert_eq!(4, solve_part2_captcha("123425")); } #[test] fn part2_example4() { assert_eq!(12, solve_part2_captcha("123123")); } #[test] fn part2_example5() { assert_eq!(4, solve_part2_captcha("12131415")); } #[test] fn test_day1_part2() { assert_eq!(1194, day1_part2()); } }
20.896226
63
0.552596
cdb0f962583359bba7a9633ca1799ecc5a134853
10,405
rs
Rust
src/solver/strategy/specific/killer.rs
florian1345/sudoku-variants
dd493c8e0745de10f3697c7cc3657c30136018b2
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
3
2020-10-17T20:36:53.000Z
2021-07-09T21:02:22.000Z
src/solver/strategy/specific/killer.rs
florian1345/sudoku-variants
dd493c8e0745de10f3697c7cc3657c30136018b2
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
21
2021-03-26T01:25:36.000Z
2022-02-15T19:21:20.000Z
src/solver/strategy/specific/killer.rs
florian1345/sudoku-variants
dd493c8e0745de10f3697c7cc3657c30136018b2
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
1
2021-07-09T21:02:57.000Z
2021-07-09T21:02:57.000Z
//! This module contains [Strategy] implementations specific to the //! [KillerConstraint]. They are re-exported in the //! [specific](crate::solver::strategy::specific) module, so they do not have //! to be referenced from this module directly. use crate::constraint::{ Constraint, KillerCage, KillerConstraint, Subconstraint }; use crate::solver::strategy::{Strategy, SudokuInfo}; use crate::solver::strategy::specific::sum; use crate::util::USizeSet; /// A [Strategy] specifically for the [KillerConstraint], which, for each cage, /// enumerates the possibilities and eliminates all options which are not used /// in at least one possibility. /// /// As an example, consider the following Killer cage (in a Sudoku with the /// [DefaultConstraint](crate::constraint::DefaultConstraint) as well as the /// [KillerConstraint]): /// /// ```text /// ╔═══════╤═══════╦═══════╤═══════╗ /// ║╭8─────┼───────╫──────╮│ ║ /// ║│ X │ Y ║ Y ││ ║ /// ║╰──────┼───────╫──────╯│ ║ /// ╟───────┼───────╫───────┼───────╢ /// ║ │ ║ │ ║ /// ║ │ ║ │ ║ /// ║ │ ║ │ ║ /// ╠═══════╪═══════╬═══════╪═══════╣ /// ║ │ ║ │ ║ /// ║ │ 4 ║ │ ║ /// ║ │ ║ │ ║ /// ╟───────┼───────╫───────┼───────╢ /// ║ │ ║ │ ║ /// ║ │ ║ 4 │ ║ /// ║ │ ║ │ ║ /// ╚═══════╧═══════╩═══════╧═══════╝ /// ``` /// /// This strategy would be able to deduce that the cell marked with `X` cannot /// be a 1. This is because that would require a 4 in either of the cells /// marked with Y, which is not possible due to the 4s in the lower two rows. #[derive(Clone)] pub struct KillerCagePossibilitiesStrategy; fn process_cage<C>(cage: &KillerCage, sudoku_info: &mut SudokuInfo<C>) -> bool where C: Constraint + Clone + 'static { let size = sudoku_info.size(); let mut numbers = USizeSet::new(1, size).unwrap(); let mut sum = 0; let mut missing_options = Vec::new(); let mut missing_cells = Vec::new(); for &(column, row) in cage.group() { if let Some(n) = sudoku_info.get_cell(column, row).unwrap() { numbers.insert(n).unwrap(); sum += n; } else { missing_options.push( sudoku_info.get_options(column, row).unwrap()); missing_cells.push((column, row)); } } if missing_cells.is_empty() { return false; } let new_options = sum::find_options_unique(missing_options.into_iter(), sum, cage.sum()); let mut changed = false; for (new_options, &(column, row)) in new_options.iter().zip(missing_cells.iter()) { let options = sudoku_info.get_options_mut(column, row).unwrap(); changed |= options.intersect_assign(new_options).unwrap(); } changed } impl Strategy for KillerCagePossibilitiesStrategy { fn apply<C>(&self, sudoku_info: &mut SudokuInfo<C>) -> bool where C: Constraint + Clone + 'static { let c = sudoku_info.sudoku().constraint(); if let Some(killer) = c.get_subconstraint::<KillerConstraint>() { let mut changed = false; let cages = killer.cages().clone(); for cage in cages { changed |= process_cage(&cage, sudoku_info); } changed } else { panic!("KillerCageSumStrategy deployed on non-killer Sudoku.") } } } #[cfg(test)] mod tests { use super::*; use crate::{Sudoku, SudokuGrid}; use crate::constraint::{ CompositeConstraint, DefaultConstraint, KillerCage, KillerConstraint }; use crate::solver::{Solution, Solver}; use crate::solver::strategy::{ CompositeStrategy, NakedSingleStrategy, OnlyCellStrategy, StrategicBacktrackingSolver, SudokuInfo, TupleStrategy }; type DefaultKillerConstraint = CompositeConstraint<DefaultConstraint, KillerConstraint>; fn killer_example() -> Sudoku<DefaultKillerConstraint> { let grid = SudokuGrid::parse("2x2; , , , ,\ , , , ,\ ,4, , ,\ , ,4, ").unwrap(); let mut killer_constraint = KillerConstraint::new(); let cage = KillerCage::new(vec![(0, 0), (1, 0), (2, 0)], 8).unwrap(); killer_constraint.add_cage(cage).unwrap(); let constraint = CompositeConstraint::new(DefaultConstraint, killer_constraint); Sudoku::new_with_grid(grid, constraint) } fn applied_killer_example() -> SudokuInfo<DefaultKillerConstraint> { let mut sudoku_info = SudokuInfo::from_sudoku(killer_example()); assert!(KillerCagePossibilitiesStrategy.apply(&mut sudoku_info)); sudoku_info } #[test] fn killer_cage_possibilities_strategy_excludes_due_to_sum() { let sudoku_info = applied_killer_example(); assert!(!sudoku_info.get_options(0, 0).unwrap().contains(1)); } #[test] fn killer_cage_possibilities_strategy_excludes_due_to_repeat() { let sudoku_info = applied_killer_example(); assert!(!sudoku_info.get_options(0, 0).unwrap().contains(3)); } fn big_killer_example() -> Sudoku<DefaultKillerConstraint> { // This Sudoku is taken from the World Puzzle Federation Sudoku GP 2020 // Round 8 Puzzle 10 // Puzzle: https://gp.worldpuzzle.org/sites/default/files/Puzzles/2020/2020_SudokuRound8.pdf // Solution: https://gp.worldpuzzle.org/sites/default/files/Puzzles/2020/2020_SudokuRound8_SB.pdf let grid = SudokuGrid::parse("3x3; , , , ,4, , , , ,\ , , , , , , , , ,\ , , , , , , , , ,\ , , , , , , , , ,\ 5, , , , , , , ,7,\ , , , , , , , , ,\ , , , , , , , , ,\ , , , , , , , , ,\ , , , ,1, , , , ").unwrap(); let mut killer_constraint = KillerConstraint::new(); killer_constraint.add_cage( KillerCage::new( vec![(0, 0), (1, 0), (2, 0), (3, 0), (0, 1), (0, 2), (0, 3)], 35).unwrap() ).unwrap(); killer_constraint.add_cage( KillerCage::new( vec![(5, 0), (6, 0), (7, 0), (8, 0), (8, 1), (8, 2), (8, 3)], 33).unwrap() ).unwrap(); killer_constraint.add_cage( KillerCage::new(vec![(1, 1), (1, 2)], 9).unwrap() ).unwrap(); killer_constraint.add_cage( KillerCage::new(vec![(2, 1), (2, 2)], 15).unwrap() ).unwrap(); killer_constraint.add_cage( KillerCage::new(vec![(3, 1), (3, 2), (4, 2)], 14).unwrap() ).unwrap(); killer_constraint.add_cage( KillerCage::new(vec![(4, 1), (5, 1), (5, 2)], 13).unwrap() ).unwrap(); killer_constraint.add_cage( KillerCage::new(vec![(6, 1), (7, 1)], 12).unwrap() ).unwrap(); killer_constraint.add_cage( KillerCage::new(vec![(6, 2), (7, 2)], 14).unwrap() ).unwrap(); killer_constraint.add_cage( KillerCage::new(vec![(1, 3), (2, 3), (1, 4)], 13).unwrap() ).unwrap(); killer_constraint.add_cage( KillerCage::new(vec![(6, 3), (7, 3), (6, 4)], 14).unwrap() ).unwrap(); killer_constraint.add_cage( KillerCage::new(vec![(2, 4), (1, 5), (2, 5)], 12).unwrap() ).unwrap(); killer_constraint.add_cage( KillerCage::new(vec![(7, 4), (6, 5), (7, 5)], 11).unwrap() ).unwrap(); killer_constraint.add_cage( KillerCage::new( vec![(0, 5), (0, 6), (0, 7), (0, 8), (1, 8), (2, 8), (3, 8)], 35).unwrap() ).unwrap(); killer_constraint.add_cage( KillerCage::new( vec![(8, 5), (8, 6), (8, 7), (5, 8), (6, 8), (7, 8), (8, 8)], 30).unwrap() ).unwrap(); killer_constraint.add_cage( KillerCage::new(vec![(1, 6), (2, 6)], 13).unwrap() ).unwrap(); killer_constraint.add_cage( KillerCage::new(vec![(3, 6), (3, 7), (4, 7)], 13).unwrap() ).unwrap(); killer_constraint.add_cage( KillerCage::new(vec![(4, 6), (5, 6), (5, 7)], 17).unwrap() ).unwrap(); killer_constraint.add_cage( KillerCage::new(vec![(6, 6), (6, 7)], 13).unwrap() ).unwrap(); killer_constraint.add_cage( KillerCage::new(vec![(7, 6), (7, 7)], 16).unwrap() ).unwrap(); killer_constraint.add_cage( KillerCage::new(vec![(1, 7), (2, 7)], 11).unwrap() ).unwrap(); let constraint = CompositeConstraint::new(DefaultConstraint, killer_constraint); Sudoku::new_with_grid(grid, constraint) } fn big_killer_example_solution() -> SudokuGrid { SudokuGrid::parse("3x3; 7,5,3,8,4,6,1,2,9,\ 4,8,6,2,9,1,7,5,3,\ 2,1,9,7,5,3,6,8,4,\ 6,4,7,3,2,5,9,1,8,\ 5,2,1,9,6,8,4,3,7,\ 9,3,8,1,7,4,2,6,5,\ 3,9,4,6,8,2,5,7,1,\ 1,6,5,4,3,7,8,9,2,\ 8,7,2,5,1,9,3,4,6").unwrap() } fn test_big_killer_solver<S: Solver>(solver: S) { let solution = solver.solve(&big_killer_example()); let expected = big_killer_example_solution(); assert_eq!(Solution::Unique(expected), solution); } #[test] fn killer_cage_possibilities_strategic_backtracking_is_sound() { let solver = StrategicBacktrackingSolver::new(KillerCagePossibilitiesStrategy); test_big_killer_solver(solver); } #[test] fn complex_killer_strategic_backtracking_is_sound() { let solver = StrategicBacktrackingSolver::new(CompositeStrategy::new( CompositeStrategy::new( OnlyCellStrategy, NakedSingleStrategy ), CompositeStrategy::new( KillerCagePossibilitiesStrategy, TupleStrategy::new(|_| 3) ) )); test_big_killer_solver(solver); } }
34.453642
105
0.51802
fb628cfd5872f8ee00cb34decf048e7ec09267be
3,752
kt
Kotlin
psolib/src/commonMain/kotlin/world/phantasmal/psolib/asm/dataFlowAnalysis/GetStackValue.kt
DaanVandenBosch/phantasmal-world
89ea739c65fda32cda1caaf159cad022469e2663
[ "MIT" ]
16
2019-06-14T03:20:51.000Z
2022-02-04T08:01:56.000Z
psolib/src/commonMain/kotlin/world/phantasmal/psolib/asm/dataFlowAnalysis/GetStackValue.kt
DaanVandenBosch/phantasmal-world
89ea739c65fda32cda1caaf159cad022469e2663
[ "MIT" ]
12
2019-09-15T20:37:05.000Z
2022-02-06T03:24:22.000Z
psolib/src/commonMain/kotlin/world/phantasmal/psolib/asm/dataFlowAnalysis/GetStackValue.kt
DaanVandenBosch/phantasmal-world
89ea739c65fda32cda1caaf159cad022469e2663
[ "MIT" ]
5
2019-07-20T05:16:20.000Z
2021-11-15T09:19:54.000Z
package world.phantasmal.psolib.asm.dataFlowAnalysis import mu.KotlinLogging import world.phantasmal.psolib.asm.* private val logger = KotlinLogging.logger {} /** * Computes the possible values of a stack element at the nth position from the top, right before a * specific instruction. If the stack element's value can be traced back to a single push * instruction, that instruction is also returned. */ fun getStackValue( cfg: ControlFlowGraph, instruction: Instruction, position: Int, ): Pair<ValueSet, Instruction?> { val block = cfg.getBlockForInstruction(instruction) return StackValueFinder().find( mutableSetOf(), cfg, block, block.indexOfInstruction(instruction), position, ) } private class StackValueFinder { private var iterations = 0 fun find( path: MutableSet<BasicBlock>, cfg: ControlFlowGraph, block: BasicBlock, end: Int, position: Int, ): Pair<ValueSet, Instruction?> { if (++iterations > 100) { logger.warn { "Too many iterations." } return Pair(ValueSet.all(), null) } var pos = position for (i in end - 1 downTo block.start) { val instruction = block.segment.instructions[i] if (instruction.opcode.stack == StackInteraction.Pop) { pos += instruction.opcode.params.size continue } val args = instruction.args when (instruction.opcode.code) { OP_ARG_PUSHR.code -> { if (pos == 0) { val arg = args[0] return if (arg is IntArg) { Pair(getRegisterValue(cfg, instruction, arg.value), instruction) } else { Pair(ValueSet.all(), instruction) } } else { pos-- } } OP_ARG_PUSHL.code, OP_ARG_PUSHB.code, OP_ARG_PUSHW.code, -> { if (pos == 0) { val arg = args[0] return if (arg is IntArg) { Pair(ValueSet.of(arg.value), instruction) } else { Pair(ValueSet.all(), instruction) } } else { pos-- } } OP_ARG_PUSHA.code, OP_ARG_PUSHO.code, OP_ARG_PUSHS.code, -> { if (pos == 0) { return Pair(ValueSet.all(), instruction) } else { pos-- } } } } val values = ValueSet.empty() var instruction: Instruction? = null var multipleInstructions = false path.add(block) for (from in block.from) { // Bail out from loops. if (from in path) { return Pair(ValueSet.all(), null) } val (fromValues, fromInstruction) = find(LinkedHashSet(path), cfg, from, from.end, pos) values.union(fromValues) if (!multipleInstructions) { if (instruction == null) { instruction = fromInstruction } else if (instruction != fromInstruction) { instruction = null multipleInstructions = true } } } return Pair(values, instruction) } }
29.3125
99
0.472548
cde6f8270ae6b2a9436f8352d7d7783572fbdc6a
7,125
asm
Assembly
Transynther/x86/_processed/NONE/_xt_/i3-7100_9_0xca_notsx.log_21829_925.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/NONE/_xt_/i3-7100_9_0xca_notsx.log_21829_925.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/NONE/_xt_/i3-7100_9_0xca_notsx.log_21829_925.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r14 push %r8 push %r9 push %rax push %rbx push %rcx push %rdi push %rsi lea addresses_UC_ht+0x508a, %r11 nop nop nop and %rax, %rax mov $0x6162636465666768, %rcx movq %rcx, %xmm2 and $0xffffffffffffffc0, %r11 vmovntdq %ymm2, (%r11) nop nop nop nop add $42615, %r8 lea addresses_WC_ht+0x1230a, %r14 nop nop add %rbx, %rbx mov (%r14), %ax cmp $20796, %rax lea addresses_D_ht+0xaf5a, %r14 nop xor %r9, %r9 movw $0x6162, (%r14) nop nop inc %r9 lea addresses_UC_ht+0x804b, %rsi lea addresses_WT_ht+0x1dd0a, %rdi nop nop nop nop cmp %r11, %r11 mov $125, %rcx rep movsb nop nop nop nop nop add $17238, %rbx lea addresses_WT_ht+0x1af8a, %rbx nop nop nop add %rdi, %rdi mov $0x6162636465666768, %rsi movq %rsi, (%rbx) nop cmp %r9, %r9 lea addresses_normal_ht+0x12e8a, %rbx cmp $20786, %rax mov (%rbx), %rcx add %rax, %rax lea addresses_WC_ht+0xe8a, %rbx inc %rax movb $0x61, (%rbx) xor %rcx, %rcx lea addresses_WT_ht+0x1048a, %rax nop nop nop xor $47399, %rbx mov $0x6162636465666768, %r14 movq %r14, %xmm7 vmovups %ymm7, (%rax) nop nop nop and $22354, %r9 lea addresses_D_ht+0x12c0a, %r9 nop nop nop sub $17911, %rdi mov $0x6162636465666768, %r14 movq %r14, %xmm4 vmovups %ymm4, (%r9) inc %r11 lea addresses_WT_ht+0x19a8a, %rbx nop nop nop cmp %r11, %r11 movb (%rbx), %al nop nop nop and $33968, %r9 lea addresses_WT_ht+0x368a, %r9 nop nop nop xor $45035, %r14 mov $0x6162636465666768, %r11 movq %r11, (%r9) nop nop nop nop nop xor %r11, %r11 lea addresses_UC_ht+0x16e8a, %rsi lea addresses_WC_ht+0x6162, %rdi nop nop dec %r8 mov $58, %rcx rep movsq nop nop nop nop inc %rbx pop %rsi pop %rdi pop %rcx pop %rbx pop %rax pop %r9 pop %r8 pop %r14 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r9 push %rax push %rbp push %rcx push %rdx // Store lea addresses_PSE+0xad4a, %r10 add %rbp, %rbp movb $0x51, (%r10) nop nop nop nop mfence // Faulty Load lea addresses_PSE+0xe8a, %r10 nop nop cmp %rax, %rax mov (%r10), %bp lea oracles, %r9 and $0xff, %rbp shlq $12, %rbp mov (%r9,%rbp,1), %rbp pop %rdx pop %rcx pop %rbp pop %rax pop %r9 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'same': False, 'congruent': 0, 'NT': False, 'type': 'addresses_PSE', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_PSE', 'size': 1, 'AVXalign': False}} [Faulty Load] {'src': {'same': True, 'congruent': 0, 'NT': False, 'type': 'addresses_PSE', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'same': False, 'congruent': 9, 'NT': True, 'type': 'addresses_UC_ht', 'size': 32, 'AVXalign': False}} {'src': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_WC_ht', 'size': 2, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 4, 'NT': False, 'type': 'addresses_D_ht', 'size': 2, 'AVXalign': False}} {'src': {'type': 'addresses_UC_ht', 'congruent': 0, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WT_ht', 'congruent': 6, 'same': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 7, 'NT': False, 'type': 'addresses_WT_ht', 'size': 8, 'AVXalign': False}} {'src': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_normal_ht', 'size': 8, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 9, 'NT': False, 'type': 'addresses_WC_ht', 'size': 1, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': True, 'congruent': 8, 'NT': False, 'type': 'addresses_WT_ht', 'size': 32, 'AVXalign': False}} {'OP': 'STOR', 'dst': {'same': False, 'congruent': 6, 'NT': False, 'type': 'addresses_D_ht', 'size': 32, 'AVXalign': False}} {'src': {'same': False, 'congruent': 10, 'NT': False, 'type': 'addresses_WT_ht', 'size': 1, 'AVXalign': False}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'same': True, 'congruent': 10, 'NT': False, 'type': 'addresses_WT_ht', 'size': 8, 'AVXalign': False}} {'src': {'type': 'addresses_UC_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 3, 'same': False}} {'33': 21829} 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 */
35.984848
2,999
0.656421
9fd6a5bd733cde42a2408a514c0e9b3502f44813
3,545
rs
Rust
src/pattern.rs
zfzackfrost/string_studio
c7e4fd3a7d8fd1252f250959b130bfa2cc958838
[ "MIT" ]
null
null
null
src/pattern.rs
zfzackfrost/string_studio
c7e4fd3a7d8fd1252f250959b130bfa2cc958838
[ "MIT" ]
null
null
null
src/pattern.rs
zfzackfrost/string_studio
c7e4fd3a7d8fd1252f250959b130bfa2cc958838
[ "MIT" ]
null
null
null
use crate::config::Fragment; use serde::de::Deserializer; use serde::de::{SeqAccess, Visitor}; use serde::ser::{SerializeSeq, Serializer}; use serde::{Deserialize, Serialize}; use std::fmt; use std::iter::FromIterator; #[derive(Debug, Clone)] pub struct CompositePattern { pub parts: Vec<String>, } impl CompositePattern { pub fn assemble_pattern(&self, fragments: &Vec<Fragment>) -> Result<String, String> { let mut pat = String::new(); for p in &self.parts { if p.starts_with("@") && p.ends_with("@") { let p_name = p.strip_suffix("@").unwrap().strip_prefix("@").unwrap(); pat += &{ let mut s: String = Default::default(); for i in fragments { if i.name == p_name { let tmp_pat = i.pattern.assemble_pattern(fragments)?; s = tmp_pat; break; } } s.clone() }; } else { pat += &p; } } Ok(pat) } } impl Serialize for CompositePattern { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { if self.parts.len() < 1 { serializer.serialize_none() } else if self.parts.len() == 1 { serializer.serialize_str(&self.parts[0]) } else { let mut seq = serializer.serialize_seq(Some(self.parts.len()))?; for p in &self.parts { seq.serialize_element(&p)?; } seq.end() } } } impl<'de> Deserialize<'de> for CompositePattern { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct CompositePatternVisitor; impl<'de> Visitor<'de> for CompositePatternVisitor { type Value = CompositePattern; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("struct CompositePattern") } fn visit_str<E>(self, value: &str) -> Result<CompositePattern, E> { Ok(CompositePattern::from(value)) } fn visit_seq<V>(self, mut seq: V) -> Result<CompositePattern, V::Error> where V: SeqAccess<'de>, { let mut strs: Vec<String> = Vec::new(); loop { if let Ok(Some(s)) = seq.next_element::<&str>() { strs.push(String::from(s)); } else { break; } } Ok(CompositePattern::from(strs.as_slice())) } } deserializer.deserialize_any(CompositePatternVisitor) } } impl Default for CompositePattern { fn default() -> Self { Self { parts: Vec::new() } } } impl From<&str> for CompositePattern { fn from(value: &str) -> Self { Self { parts: vec![String::from(value)], } } } impl From<&[String]> for CompositePattern { fn from(value: &[String]) -> Self { Self { parts: Vec::from(value), } } } impl From<&[&str]> for CompositePattern { fn from(value: &[&str]) -> Self { Self { parts: Vec::from_iter(value.iter().map(|x| String::from(*x))), } } }
27.913386
89
0.482934
e73edfde7f67f674b761d7588194ef86d54d8b46
2,258
js
JavaScript
src/game/models/tile.js
aldhsu/minesweeper
adaa9bc74b53dbe4697e2bf228faabf973eb093d
[ "CC0-1.0" ]
null
null
null
src/game/models/tile.js
aldhsu/minesweeper
adaa9bc74b53dbe4697e2bf228faabf973eb093d
[ "CC0-1.0" ]
null
null
null
src/game/models/tile.js
aldhsu/minesweeper
adaa9bc74b53dbe4697e2bf228faabf973eb093d
[ "CC0-1.0" ]
null
null
null
import _ from 'underscore'; export default class Tile { constructor(y, x, board, channel) { this.x = x; this.y = y; this.board = board; this.revealed = false; this.isBomb = false; this.channel = channel; this.isFlagged = false; } get isRevealed() { return this.revealed; } get hasBomb() { return this.isBomb; } becomeBomb() { this.isBomb = true; return this; } get bombCount() { const value = this.neighbours.reduce((acc, tile) => { return acc + tile.hasBomb; }, 0); return value; } reveal() { this.revealed = true; if (this.bombCount === 0) { this.neighbours .filter((tile) => { return !tile.revealed && !tile.isBomb }).forEach((tile) => { tile.reveal(); }); } this.channel.emit('reveal'); return true; } flag() { this.isFlagged = true; this.channel.emit('reveal'); } // related positions get topLeft() { return this.safePositionCheck([this.y - 1, this.x - 1]) } get topMiddle() { return this.safePositionCheck([this.y - 1, this.x]) } get topRight() { return this.safePositionCheck([this.y - 1, this.x + 1]) } get left() { return this.safePositionCheck([this.y, this.x - 1]) } get right() { return this.safePositionCheck([this.y, this.x + 1]) } get bottomLeft() { return this.safePositionCheck([this.y + 1, this.x - 1]) } get bottomMiddle() { return this.safePositionCheck([this.y + 1, this.x]) } get bottomRight() { return this.safePositionCheck([this.y + 1, this.x + 1]) } safePositionCheck(offsets) { const [yOffset, xOffset] = offsets; const offGrid = ((xOffset) < 0 || (yOffset) < 0) || (xOffset > this.board.length - 1 || yOffset > this.board.length - 1) if(offGrid) { return; } else { return this.board[yOffset][xOffset] } } get neighbours() { const neighbours = []; for (var y = -1; y <= 1; y++) { for (var x = -1; x <= 1; x++) { if (y === 0 && x === 0) { continue; } else { neighbours.push(this.safePositionCheck([this.y + y, this.x + x])); } } } return _.compact(neighbours); } }
19.807018
124
0.550487
ad44640a5702e5628a875fa2bd0cf737563647a8
2,336
lua
Lua
src/mod/tools/api/MapViewer.lua
Ruin0x11/OpenNefia
548f1a1442eca704bb1c16b1a1591d982a34919f
[ "MIT" ]
109
2020-04-07T16:56:38.000Z
2022-02-17T04:05:40.000Z
src/mod/tools/api/MapViewer.lua
Ruin0x11/OpenNefia
548f1a1442eca704bb1c16b1a1591d982a34919f
[ "MIT" ]
243
2020-04-07T08:25:15.000Z
2021-10-30T07:22:10.000Z
src/mod/tools/api/MapViewer.lua
Ruin0x11/OpenNefia
548f1a1442eca704bb1c16b1a1591d982a34919f
[ "MIT" ]
15
2020-04-25T12:28:55.000Z
2022-02-23T03:20:43.000Z
local Draw = require("api.Draw") local Gui = require("api.Gui") local InstancedMap = require("api.InstancedMap") local MapRenderer = require("api.gui.MapRenderer") local IUiLayer = require("api.gui.IUiLayer") local IInput = require("api.gui.IInput") local InputHandler = require("api.gui.InputHandler") local MapViewer = class.class("MapViewer", IUiLayer) MapViewer:delegate("input", IInput) function MapViewer:init(map) class.assert_is_an(InstancedMap, map) self.map = map map:iter_tiles():each(function(x, y) map:memorize_tile(x, y) end) map:redraw_all_tiles() self.renderer = MapRenderer:new(map) local tw, th = Draw.get_coords():get_size() local mw = self.map:width() * tw local mh = self.map:height() * th self.offset_x = math.floor((Draw.get_width() - mw) / 2) self.offset_y = math.floor((Draw.get_height() - mh) / 2) self.delta = math.floor(tw / 2) self.input = InputHandler:new() self.input:bind_keys(self:make_keymap()) end function MapViewer:default_z_order() return 100000000 end function MapViewer:make_keymap() return { north = function() self:pan(0, -self.delta) end, south = function() self:pan(0, self.delta) end, east = function() self:pan(self.delta, 0) end, west = function() self:pan(-self.delta, 0) end, cancel = function() self.canceled = true end, escape = function() self.canceled = true end, enter = function() self.canceled = true end, } end function MapViewer:on_query() Gui.play_sound("base.pop2") end function MapViewer:pan(dx, dy) self.offset_x = math.floor(self.offset_x + dx) self.offset_y = math.floor(self.offset_y + dy) end function MapViewer:relayout(x, y, width, height) self.x = x self.y = y self.width = width self.height = height self.renderer:relayout(self.x, self.y, self.width, self.height) end function MapViewer:draw() local x = self.x + self.offset_x local y = self.y + self.offset_y self.renderer.x = x self.renderer.y = y Draw.set_color(255, 255, 255) self.renderer:draw() end function MapViewer:update(dt) self.renderer:update(dt) local canceled = self.canceled self.canceled = nil if canceled then return nil, "canceled" end end function MapViewer.start(map) MapViewer:new(map):query() end return MapViewer
24.333333
68
0.686644
4cc36869fa4d0777ae134f50406e7f08b65c8455
309
sql
SQL
Tables/dbo.SQLServerKeywords.sql
SQLauto/DBA-database-1
7647724573993aa1a88c7144617dc5cce2034028
[ "MIT" ]
2
2018-10-02T11:14:56.000Z
2021-06-20T12:29:07.000Z
Tables/dbo.SQLServerKeywords.sql
SQLauto/DBA-database-1
7647724573993aa1a88c7144617dc5cce2034028
[ "MIT" ]
6
2018-10-05T07:18:44.000Z
2019-12-08T11:05:07.000Z
Tables/dbo.SQLServerKeywords.sql
SQLDoubleG/DBA-database
e6029aef8d4efdf4b5a2b51e6960245077f3ab6b
[ "MIT" ]
2
2018-10-04T07:57:18.000Z
2019-03-09T21:07:22.000Z
CREATE TABLE [dbo].[SQLServerKeywords] ( [SQLServerProduct] [sys].[sysname] NOT NULL, [keyword] [sys].[sysname] NOT NULL ) ON [PRIMARY] GO ALTER TABLE [dbo].[SQLServerKeywords] ADD CONSTRAINT [UQ_SQLServerKeywords_SQLServerProduct_keyword] UNIQUE NONCLUSTERED ([SQLServerProduct], [keyword]) ON [PRIMARY] GO
34.333333
166
0.773463
5f8f53c929dde8ebd249488f9f4207bccf96c9ce
265
h
C
EventTracing/EventNameFilter.h
euphrat1ca/ProcMonXv2
8ea0e45e90629c00b489b6d6476515bb9cb48deb
[ "MIT" ]
302
2020-08-29T20:02:09.000Z
2022-03-30T02:43:42.000Z
EventTracing/EventNameFilter.h
euphrat1ca/ProcMonXv2
8ea0e45e90629c00b489b6d6476515bb9cb48deb
[ "MIT" ]
5
2020-11-23T05:55:54.000Z
2022-02-20T12:38:59.000Z
EventTracing/EventNameFilter.h
euphrat1ca/ProcMonXv2
8ea0e45e90629c00b489b6d6476515bb9cb48deb
[ "MIT" ]
65
2020-08-29T20:57:06.000Z
2022-03-28T07:12:52.000Z
#pragma once #include "StringCompareFilterBase.h" class EventNameFilter : public StringCompareFilterBase { public: EventNameFilter(std::wstring name, CompareType type, FilterAction action); virtual FilterAction Eval(FilterContext& context) const override; };
22.083333
75
0.807547
b8f3b0bab3dcb776b07d4e5be3f4ecf1abe7e91c
145
lua
Lua
src/clientcore.com.main.ccs.component.slider.CcsSliderViewItem.lua
lvqier/fishingjoy
a5569e7074664a9ca72f88d6bd0dcff9282db627
[ "Unlicense" ]
null
null
null
src/clientcore.com.main.ccs.component.slider.CcsSliderViewItem.lua
lvqier/fishingjoy
a5569e7074664a9ca72f88d6bd0dcff9282db627
[ "Unlicense" ]
null
null
null
src/clientcore.com.main.ccs.component.slider.CcsSliderViewItem.lua
lvqier/fishingjoy
a5569e7074664a9ca72f88d6bd0dcff9282db627
[ "Unlicense" ]
1
2022-01-18T03:26:33.000Z
2022-01-18T03:26:33.000Z
CcsSliderViewItem = class("CcsSliderViewItem") CcsSliderViewItem.ctor = function (slot0) ClassUtil.extends(slot0, CcsListViewItem) end return
18.125
46
0.813793
7fc22fa331739d3ea4e473a988dc1e1f35f58701
136
sql
SQL
cosmic-core/cosmic-flyway/src/main/resources/db/migration/V2_23__disk-offering-custom-only.sql
sanderv32/cosmic
9a9d86500b67255a1c743a9438a05c0d969fd210
[ "Apache-2.0" ]
64
2016-01-30T13:31:00.000Z
2022-02-21T02:13:25.000Z
cosmic-core/cosmic-flyway/src/main/resources/db/migration/V2_23__disk-offering-custom-only.sql
sanderv32/cosmic
9a9d86500b67255a1c743a9438a05c0d969fd210
[ "Apache-2.0" ]
525
2016-01-22T10:46:31.000Z
2022-02-23T11:08:01.000Z
cosmic-core/cosmic-flyway/src/main/resources/db/migration/V2_23__disk-offering-custom-only.sql
sanderv32/cosmic
9a9d86500b67255a1c743a9438a05c0d969fd210
[ "Apache-2.0" ]
25
2016-01-13T16:46:46.000Z
2021-07-23T15:22:27.000Z
UPDATE `disk_offering` SET `disk_size`=0, `customized`=1, `state`="Inactive", `removed`=NOW() WHERE `type`="disk" AND `customized` = 0;
68
135
0.683824
6536be01b7eb4b8a845b975aa35e3be000f854f3
1,182
py
Python
lib/googlecloudsdk/command_lib/filestore/operations/flags.py
bshaffer/google-cloud-sdk
f587382fd112f238c0d6d5ca3dab8f52d2b5c5f9
[ "Apache-2.0" ]
null
null
null
lib/googlecloudsdk/command_lib/filestore/operations/flags.py
bshaffer/google-cloud-sdk
f587382fd112f238c0d6d5ca3dab8f52d2b5c5f9
[ "Apache-2.0" ]
null
null
null
lib/googlecloudsdk/command_lib/filestore/operations/flags.py
bshaffer/google-cloud-sdk
f587382fd112f238c0d6d5ca3dab8f52d2b5c5f9
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- # # Copyright 2017 Google Inc. All Rights Reserved. # # 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. """Flags and helpers for the Cloud Filestore operations commands.""" from __future__ import unicode_literals OPERATIONS_LIST_FORMAT = """\ table( name.basename():label=OPERATION_NAME, name.segment(3):label=LOCATION, metadata.verb:label=TYPE, metadata.target.basename(), done.yesno(yes='DONE', no='RUNNING'):label=STATUS, metadata.createTime.date():sort=1, duration(start=metadata.createTime,end=metadata.endTime,precision=0,calendar=false).slice(2:).join("").yesno(no="<1S"):label=DURATION )"""
40.758621
141
0.716582
1a3d1b5fd919cdd7a98086c28edb15f3f6db36d0
8,455
rs
Rust
hadron-operator/src/server/http.rs
hadron-project/hadron
ea260d06dff9309af8a36803715c8268535a023c
[ "Apache-2.0" ]
19
2021-03-14T11:57:33.000Z
2022-01-10T02:33:43.000Z
hadron-operator/src/server/http.rs
hadron-project/hadron
ea260d06dff9309af8a36803715c8268535a023c
[ "Apache-2.0" ]
60
2021-05-18T13:22:31.000Z
2021-12-07T16:18:45.000Z
hadron-operator/src/server/http.rs
hadron-project/hadron
ea260d06dff9309af8a36803715c8268535a023c
[ "Apache-2.0" ]
2
2021-05-13T09:45:30.000Z
2021-05-20T17:52:06.000Z
use std::convert::Infallible; use std::sync::Arc; use anyhow::{Context, Result}; use axum::http::{header::HeaderName, HeaderMap, HeaderValue, StatusCode}; use axum::routing::{get, post, Router}; use axum::{extract, handler::Handler, AddExtensionLayer}; use hyper::server::conn::Http; use kube::api::DynamicObject; use kube::core::admission::{AdmissionResponse, AdmissionReview, Operation}; use metrics_exporter_prometheus::PrometheusHandle; use tokio::net::TcpListener; use tokio::sync::broadcast; use tokio::task::JoinHandle; use tokio_rustls::rustls::{Certificate, NoClientAuth, PrivateKey, ServerConfig}; use tokio_rustls::TlsAcceptor; use tower_http::trace::TraceLayer; use crate::config::Config; use crate::get_metrics_recorder; use hadron_core::crd::{Pipeline, Stream, Token}; /// The HTTP server. pub(super) struct HttpServer { /// The application's runtime config. #[allow(dead_code)] config: Arc<Config>, /// A channel used for triggering graceful shutdown. shutdown_tx: broadcast::Sender<()>, /// A channel used for triggering graceful shutdown. shutdown_rx: broadcast::Receiver<()>, listener: TcpListener, acceptor: TlsAcceptor, } impl HttpServer { /// Construct a new instance. pub async fn new(config: Arc<Config>, shutdown: broadcast::Sender<()>) -> Result<Self> { let rustls_config = rustls_server_config(config.webhook_key.0.clone(), config.webhook_cert.0.clone()).context("error building webhook TLS config")?; let acceptor = TlsAcceptor::from(rustls_config); let listener = TcpListener::bind(("0.0.0.0", config.webhooks_port)).await.context("error binding socket address for webhook server")?; Ok(Self { config, shutdown_rx: shutdown.subscribe(), shutdown_tx: shutdown, listener, acceptor, }) } pub fn spawn(self) -> JoinHandle<Result<()>> { tokio::spawn(self.run()) } async fn run(mut self) -> Result<()> { let state = get_metrics_recorder(&self.config).handle(); let mut http_shutdown = self.shutdown_tx.subscribe(); let http_router = Router::new() .route("/health", get(|| async { StatusCode::OK })) .route("/metrics", get(prom_metrics.layer(AddExtensionLayer::new(state)))); let http_server = axum::Server::bind(&([0, 0, 0, 0], self.config.metrics_port).into()) .serve(http_router.into_make_service()) .with_graceful_shutdown(async move { let _res = http_shutdown.recv().await; }); let http_server_handle = tokio::spawn(http_server); tracing::info!("metrics server is listening at 0.0.0.0:{}", self.config.metrics_port); let webhook_router = Router::new() .route("/k8s/admissions/vaw/pipelines", post(vaw_pipelines.layer(TraceLayer::new_for_http()))) .route("/k8s/admissions/vaw/streams", post(vaw_streams.layer(TraceLayer::new_for_http()))) .route("/k8s/admissions/vaw/tokens", post(vaw_tokens.layer(TraceLayer::new_for_http()))); tracing::info!("webhook server is listening at 0.0.0.0:{}", self.config.webhooks_port); loop { tokio::select! { sock_res = self.listener.accept() => { let (stream, _addr) = match sock_res { Ok((stream, addr)) => (stream, addr), Err(err) => { tracing::error!(error = ?err, "error accepting webhook socket connection"); let _res = self.shutdown_tx.send(()); break; } }; let (acceptor, webhook_router) = (self.acceptor.clone(), webhook_router.clone()); tokio::spawn(async move { if let Ok(stream) = acceptor.accept(stream).await { let _res = Http::new().serve_connection(stream, webhook_router).await; } }); }, _ = self.shutdown_rx.recv() => break, } } if let Err(err) = http_server_handle.await { tracing::error!(error = ?err, "error shutting down http server"); } Ok(()) } } /// Build RusTLS server config. fn rustls_server_config(key: PrivateKey, certs: Vec<Certificate>) -> Result<Arc<ServerConfig>> { let mut config = ServerConfig::new(NoClientAuth::new()); config.set_single_cert(certs, key).context("error configuring webhook certificate")?; config.set_protocols(&[b"h2".to_vec(), b"http/1.1".to_vec()]); Ok(Arc::new(config)) } /// VAW handler for pipelines. #[tracing::instrument(level = "debug", skip(payload))] pub(super) async fn vaw_pipelines(mut payload: extract::Json<AdmissionReview<Pipeline>>) -> std::result::Result<axum::Json<AdmissionReview<DynamicObject>>, Infallible> { tracing::debug!(?payload, "received pipeline VAW request"); let req = match payload.0.request.take() { Some(req) => req, None => { let res = AdmissionResponse::invalid("malformed webhook request received, no `request` field"); return Ok(axum::Json::from(res.into_review())); } }; // Unpack request components based on operation. let new_pipeline = match &req.operation { // Nothing to do for these, so just accept. Operation::Delete | Operation::Connect => { return Ok(axum::Json::from(AdmissionResponse::from(&req).into_review())); } // These operations require at least the new object to be present. Operation::Create | Operation::Update => match &req.object { Some(new_pipeline) => new_pipeline, None => { let res = AdmissionResponse::invalid("no pipeline object found in the `object` field, can not validate"); return Ok(axum::Json::from(res.into_review())); } }, }; // Perform a full validation of the new object. if let Err(err) = new_pipeline.validate() { let rejection = err.join("; "); return Ok(axum::Json::from(AdmissionResponse::invalid(rejection).into_review())); } // If this is an update request, than validate the compatibility between the new and the old objects. if let Some(old_pipeline) = &req.old_object { // Should only be populated for Operation::Update. if let Err(err) = new_pipeline.validate_compatibility(old_pipeline) { let rejection = err.join("; "); return Ok(axum::Json::from(AdmissionResponse::invalid(rejection).into_review())); } } Ok(axum::Json::from(AdmissionResponse::from(&req).into_review())) } /// VAW handler for streams. #[tracing::instrument(level = "debug", skip(payload))] pub(super) async fn vaw_streams(mut payload: extract::Json<AdmissionReview<Stream>>) -> std::result::Result<axum::Json<AdmissionReview<DynamicObject>>, Infallible> { tracing::debug!(?payload, "received streams VAW request"); match payload.0.request.take() { Some(req) => Ok(axum::Json::from(AdmissionResponse::from(&req).into_review())), None => { let res = AdmissionResponse::invalid("malformed webhook request received, no `request` field"); Ok(axum::Json::from(res.into_review())) } } } /// VAW handler for tokens. #[tracing::instrument(level = "debug", skip(payload))] pub(super) async fn vaw_tokens(mut payload: extract::Json<AdmissionReview<Token>>) -> std::result::Result<axum::Json<AdmissionReview<DynamicObject>>, Infallible> { tracing::debug!(?payload, "received token VAW request"); match payload.0.request.take() { Some(req) => Ok(axum::Json::from(AdmissionResponse::from(&req).into_review())), None => { let res = AdmissionResponse::invalid("malformed webhook request received, no `request` field"); Ok(axum::Json::from(res.into_review())) } } } /// Handler for serving Prometheus metrics. pub(super) async fn prom_metrics(extract::Extension(state): extract::Extension<PrometheusHandle>) -> (StatusCode, HeaderMap, String) { let mut headers = HeaderMap::new(); headers.insert(HeaderName::from_static("content-type"), HeaderValue::from_static("text/plain; version=0.0.4")); (StatusCode::OK, headers, state.render()) }
43.80829
169
0.625429