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
53b69dc852d76e416dcc42d5a51b374859da6222
643
java
Java
application-server/src/main/java/de/msg/iot/anki/application/entity/Track.java
Aspern/anki-overdrive
9937a8b084af2ddac42951d0a8177cbced625a20
[ "Apache-2.0" ]
null
null
null
application-server/src/main/java/de/msg/iot/anki/application/entity/Track.java
Aspern/anki-overdrive
9937a8b084af2ddac42951d0a8177cbced625a20
[ "Apache-2.0" ]
null
null
null
application-server/src/main/java/de/msg/iot/anki/application/entity/Track.java
Aspern/anki-overdrive
9937a8b084af2ddac42951d0a8177cbced625a20
[ "Apache-2.0" ]
null
null
null
package de.msg.iot.anki.application.entity; import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; @XmlRootElement @Entity public class Track { @Id @GeneratedValue(strategy = GenerationType.TABLE) private long id; @OneToMany(cascade = CascadeType.PERSIST, orphanRemoval = true) private List<Piece> pieces; public long getId() { return id; } public void setId(long id) { this.id = id; } public List<Piece> getPieces() { return pieces; } public void setPieces(List<Piece> pieces) { this.pieces = pieces; } }
18.911765
67
0.654743
cb85450a831d89dfb631cd5521a6035e08dc11cd
1,028
go
Go
example/for.go
edwingeng/go2lua
94ba18c468b457456779e817ba33615836259c21
[ "BSD-3-Clause" ]
3
2019-11-05T06:07:32.000Z
2021-07-22T10:19:00.000Z
example/for.go
edwingeng/go2lua
94ba18c468b457456779e817ba33615836259c21
[ "BSD-3-Clause" ]
null
null
null
example/for.go
edwingeng/go2lua
94ba18c468b457456779e817ba33615836259c21
[ "BSD-3-Clause" ]
null
null
null
package example func forLoop1() { for { break } } func forLoop2() { for i := 0; i < 3; i++ { // Empty } } func forLoop3() { i := 0 for i < 1 { break } } func forLoop4() { for i := 0; ; { println(i) break } } func forLoop5() { i := 0 for ; ; i++ { if i >= 1 { break } } } func forLoop6() { for i := 0; i < 3; i++ { if i >= 1 { continue } println(i) } for i := 0; i < 3; i++ { if i >= 1 { continue } println(i) } } func forLoop7() { pos1: for i := 0; i < 3; i++ { for { break pos1 } } } func forLoop8() { pos1: for i := 0; i < 3; i++ { for { continue pos1 } } } func forLoop9(n int) { if n > 0 { goto pos1 } println(100) pos1: for i := 0; i < 3; i++ { for { continue pos1 } } } func forLoop10() { for i := 0; i < 3; i++ { i := i * 10 println(i) } } func forLoop11() { outer: for i := 0; i < 4; i++ { switch i { case 0: continue case 1: case 2: println("a", i) default: break outer } println("b", i) } }
9.518519
25
0.459144
39640d4e5214aedf779bcb4bebd392a27fc71801
267
html
HTML
app/views/includes/phase.html
htmlandbacon/register-your-balloon
6d2e40b59f32ac8eb23c69895bcd08bbbcfff7f0
[ "MIT" ]
null
null
null
app/views/includes/phase.html
htmlandbacon/register-your-balloon
6d2e40b59f32ac8eb23c69895bcd08bbbcfff7f0
[ "MIT" ]
null
null
null
app/views/includes/phase.html
htmlandbacon/register-your-balloon
6d2e40b59f32ac8eb23c69895bcd08bbbcfff7f0
[ "MIT" ]
null
null
null
<div class="govuk-width-container"> {{ govukPhaseBanner({ tag: { text: "DEMO" }, html: 'This is a new service – your <a class="govuk-link" href="/steps/feedbac">feedback</a> will help us to improve it.' }) }} </div>
33.375
129
0.535581
fc539acbcb6cdea0c78c746dc712eca00d48163e
749
sql
SQL
bitrix/modules/intranet/install/db/oracle/uninstall.sql
BuildingBridge/biznet
0e9e864be99e01bd35f4321a04736866937897b0
[ "Unlicense" ]
1
2020-10-05T04:28:40.000Z
2020-10-05T04:28:40.000Z
bitrix/modules/intranet/install/db/oracle/uninstall.sql
shuchitamathur28/bitrix24
fafc179382f028989a4ee4a5f97422e49b1526b4
[ "Unlicense" ]
null
null
null
bitrix/modules/intranet/install/db/oracle/uninstall.sql
shuchitamathur28/bitrix24
fafc179382f028989a4ee4a5f97422e49b1526b4
[ "Unlicense" ]
null
null
null
DROP TABLE b_intranet_sharepoint CASCADE CONSTRAINTS / DROP TABLE b_intranet_sharepoint_field CASCADE CONSTRAINTS / DROP TABLE b_intranet_sharepoint_queue CASCADE CONSTRAINTS / DROP SEQUENCE sq_b_intranet_sharepoint_queue / DROP TABLE b_intranet_sharepoint_log CASCADE CONSTRAINTS / DROP SEQUENCE sq_b_intranet_sharepoint_log / DROP TABLE b_rating_subordinate CASCADE CONSTRAINTS / DROP SEQUENCE sq_b_rating_subordinate / DROP TABLE b_intranet_ustat_hour CASCADE CONSTRAINTS / DROP TABLE b_intranet_ustat_day CASCADE CONSTRAINTS / DROP TABLE b_intranet_dstat_hour CASCADE CONSTRAINTS / DROP TABLE b_intranet_dstat_day CASCADE CONSTRAINTS / DROP TABLE B_INTRANET_USERSUBORD CASCADE CONSTRAINTS / DROP TABLE B_INTRANET_USER2DEP CASCADE CONSTRAINTS /
26.75
59
0.875834
df4994f6b585a8502e4155c0b673f97c39d2b95a
4,653
dart
Dart
test/features/application_preferences/presentation/bloc/preferences/app_preferences_bloc_test.dart
anCRONIK/bloc-preferences
746634b8367d637b6aef524593a2d6c78fecccae
[ "MIT" ]
null
null
null
test/features/application_preferences/presentation/bloc/preferences/app_preferences_bloc_test.dart
anCRONIK/bloc-preferences
746634b8367d637b6aef524593a2d6c78fecccae
[ "MIT" ]
null
null
null
test/features/application_preferences/presentation/bloc/preferences/app_preferences_bloc_test.dart
anCRONIK/bloc-preferences
746634b8367d637b6aef524593a2d6c78fecccae
[ "MIT" ]
null
null
null
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; import 'package:blocpreferences/core/error/failures.dart'; import 'package:blocpreferences/features/application_preferences/domain/entities/app_preferences.dart'; import 'package:blocpreferences/features/application_preferences/domain/usecases/get_and_store_app_preferences.dart'; import 'package:blocpreferences/features/application_preferences/presentation/bloc/bloc.dart'; import 'package:blocpreferences/features/application_preferences/presentation/util/app_preferences_input_validator.dart'; class MockGetAndStoreAppPreferences extends Mock implements GetAndStoreAppPreferences {} class MockAppPreferencesInputValidator extends Mock implements AppPreferencesInputValidator {} void main() { MockGetAndStoreAppPreferences mockGetAndStoreAppPreferences; AppPreferencesBloc preferenceBloc; MockAppPreferencesInputValidator mockInputValidator; setUp(() { mockGetAndStoreAppPreferences = MockGetAndStoreAppPreferences(); mockInputValidator = MockAppPreferencesInputValidator(); //arrange initial values when(mockGetAndStoreAppPreferences.getValues()).thenReturn(AppPreferences.initial()); preferenceBloc = AppPreferencesBloc(mockGetAndStoreAppPreferences, mockInputValidator); }); tearDown(() { preferenceBloc?.close(); }); test('initialState should be loaded', () { // assert expect(preferenceBloc.initialState, equals(AppPreferencesBlocState.loaded(AppPreferences.initial()))); }); group('update preference', () { const tPreference = AppPreferences.keyUnitSystem; final tValue = unitSystems[1]; final tRetVal = AppPreferences.initial(); tRetVal.unitSystem = tValue; test( 'should call the validator when update is requested', () async { // arrange when(mockInputValidator.validate(preference: anyNamed("preference"), value: anyNamed("value"))).thenReturn(Failure()); when(mockGetAndStoreAppPreferences.updateValue(preference: tPreference, value: tValue)).thenAnswer((_) => Future.value(null)); // act preferenceBloc.add(AppPreferenceBlocEvent.update(preference: tPreference, value: tValue)); await untilCalled(mockInputValidator.validate(preference: anyNamed("preference"), value: anyNamed("value"))); // assert verify(mockInputValidator.validate(preference: tPreference, value: tValue)); }, ); blocTest( 'get validator failure on store event', build: () async { when(mockGetAndStoreAppPreferences.getValues()).thenReturn(AppPreferences.initial()); when(mockInputValidator.validate(preference: anyNamed("preference"), value: anyNamed("value"))).thenReturn(UnsupportedValueFailure()); return preferenceBloc; }, act: (bloc) => bloc.add(AppPreferenceBlocEvent.update(preference: tPreference, value: tValue)) as Future, expect: [AppPreferencesBlocState.error(UnsupportedValueFailure()), AppPreferencesBlocState.loaded(AppPreferences.initial())], ); blocTest( 'validator success, but update fails', build: () async { when(mockGetAndStoreAppPreferences.getValues()).thenReturn(AppPreferences.initial()); when(mockInputValidator.validate(preference: anyNamed("preference"), value: anyNamed("value"))).thenReturn(null); when(mockGetAndStoreAppPreferences.updateValue(preference: anyNamed("preference"), value: anyNamed("value"))).thenAnswer((_) => Future.value(WriteFailure())); return preferenceBloc; }, act: (bloc) => bloc.add(AppPreferenceBlocEvent.update(preference: tPreference, value: tValue)) as Future, expect: [AppPreferencesBlocState.error(WriteFailure()), AppPreferencesBlocState.loaded(AppPreferences.initial())], ); blocTest( 'validator success, update success', build: () async { when(mockInputValidator.validate(preference: anyNamed("preference"), value: anyNamed("value"))).thenReturn(null); when(mockGetAndStoreAppPreferences.updateValue(preference: anyNamed("preference"), value: anyNamed("value"))).thenAnswer((_) => Future.value(null)); when(mockGetAndStoreAppPreferences.getValues()).thenReturn(tRetVal); return AppPreferencesBloc(mockGetAndStoreAppPreferences, mockInputValidator); }, act: (bloc) => bloc.add(AppPreferenceBlocEvent.update(preference: tPreference, value: tValue)) as Future, expect: [], //we would need to get loaded event, but we can't mock to get two different values from [mockGetAndStoreAppPreferences] ); }); }
50.032258
166
0.746185
715942deb27b250257c39805c78594aabe82068d
336
ps1
PowerShell
Public/New-FreshServiceRequest.ps1
tslight/TSFresh
fa7fb5f1350ff7617546e777547d8f7b9f773873
[ "0BSD" ]
null
null
null
Public/New-FreshServiceRequest.ps1
tslight/TSFresh
fa7fb5f1350ff7617546e777547d8f7b9f773873
[ "0BSD" ]
null
null
null
Public/New-FreshServiceRequest.ps1
tslight/TSFresh
fa7fb5f1350ff7617546e777547d8f7b9f773873
[ "0BSD" ]
null
null
null
function New-FreshServiceRequest { param ( [Parameter(Mandatory = $true)] [object]$Body, [Parameter(Mandatory = $true)] [string]$ItemDisplayId ) $Uri = "/catalog/request_items/$ItemDisplayId/service_request.json" $json = ConvertTo-Json $Body -Depth 3 New-FreshRequest -Method Post -Resource $Uri -data $json }
24
71
0.696429
604ffe543df37c0ab53ce30f6a614a642fe8c59e
53
html
HTML
google90c52bb465f13384.html
jennysoon/jennysoon.github.io
7eefac3e070a2ac871ecbebcb3a799cb4480b327
[ "CC-BY-3.0" ]
null
null
null
google90c52bb465f13384.html
jennysoon/jennysoon.github.io
7eefac3e070a2ac871ecbebcb3a799cb4480b327
[ "CC-BY-3.0" ]
null
null
null
google90c52bb465f13384.html
jennysoon/jennysoon.github.io
7eefac3e070a2ac871ecbebcb3a799cb4480b327
[ "CC-BY-3.0" ]
null
null
null
google-site-verification: google90c52bb465f13384.html
53
53
0.90566
a77bbc00258afa5854256fb30c8442c078c4737b
1,416
dart
Dart
lib/games/hnb/hnb_engine.dart
z7workbench/minigames
6d99b7e061f0bfc091591f4b454afda07b483528
[ "MIT" ]
8
2022-01-03T13:21:56.000Z
2022-03-21T14:59:29.000Z
lib/games/hnb/hnb_engine.dart
z7workbench/minigames
6d99b7e061f0bfc091591f4b454afda07b483528
[ "MIT" ]
null
null
null
lib/games/hnb/hnb_engine.dart
z7workbench/minigames
6d99b7e061f0bfc091591f4b454afda07b483528
[ "MIT" ]
1
2022-01-04T12:48:06.000Z
2022-01-04T12:48:06.000Z
import 'dart:collection'; import 'dart:math'; class HitAndBlowEngine { bool allowDuplicate; int balls; List<int> answer = []; int numberRange = 6; HashMap<int, int> stats = HashMap(); HitAndBlowEngine(this.balls, this.allowDuplicate) { var random = Random(); var index = -1; for (var i = 0; i < balls; i++) { do { index = random.nextInt(numberRange) + 1; } while (!allowDuplicate && answer.contains(index)); answer.add(index); if (stats.containsKey(index)) { stats[index] = stats[index]! + 1; } else { stats[index] = 1; } } numberRange = balls + 2; } HitAndBlowResult check(List<int> candidate) { var allRight = []; var halfRight = []; var map = Map.of(stats); for (var i = 0; i < balls; i++) { if (map.containsKey(candidate[i]) && map[candidate[i]]! > 0 && candidate[i] == answer[i]) { map[candidate[i]] = map[candidate[i]]! - 1; allRight.add(i); } } for (var i = 0; i < balls; i++) { if (!allRight.contains(i)) { if (map.containsKey(candidate[i]) && map[candidate[i]]! > 0) { halfRight.add(i); } } } return HitAndBlowResult(allRight.length, halfRight.length); } } class HitAndBlowResult { int allCorrect = 0; int halfCorrect = 0; HitAndBlowResult(this.allCorrect, this.halfCorrect); }
24
70
0.562147
cdb497ee1869b8d4d1e497ff9de5c6399dee9b13
366
kt
Kotlin
app/src/main/java/com/kylix/submissionbajp3/model/remote/response/MovieModelResponse.kt
KylixEza/Submission-BAJP3-Dicoding
81841574ec752bf40946592ad333b790c5abb933
[ "MIT" ]
3
2020-12-22T08:05:48.000Z
2021-12-20T07:41:23.000Z
app/src/main/java/com/kylix/submissionbajp3/model/remote/response/MovieModelResponse.kt
KylixEza/Submission-BAJP3-Dicoding
81841574ec752bf40946592ad333b790c5abb933
[ "MIT" ]
null
null
null
app/src/main/java/com/kylix/submissionbajp3/model/remote/response/MovieModelResponse.kt
KylixEza/Submission-BAJP3-Dicoding
81841574ec752bf40946592ad333b790c5abb933
[ "MIT" ]
null
null
null
package com.kylix.submissionbajp3.model.remote.response data class MovieModelResponse ( val movieId: Int? = 0, val movieTitle: String? = "", val movieDescription: String? = "", val movieRelease: String?= "", val movieGenre: String? = "", val movieDuration: String? = "", val movieRating : String?= "", val moviePoster : String?= "" )
30.5
55
0.644809
fb76164997ba0e3527dc90b6fe31b1cc339ee9cf
2,756
java
Java
src/main/java/nl/dtls/fairdatapoint/service/metadata/generic/GenericMetadataService.java
EOSC-synergy/FAIRDataPoint
4d5e6eb8722b9ae6cd73f7e9f565f84568b5ef18
[ "MIT" ]
1
2021-10-17T03:04:39.000Z
2021-10-17T03:04:39.000Z
src/main/java/nl/dtls/fairdatapoint/service/metadata/generic/GenericMetadataService.java
EOSC-synergy/FAIRDataPoint
4d5e6eb8722b9ae6cd73f7e9f565f84568b5ef18
[ "MIT" ]
11
2021-12-27T02:23:32.000Z
2022-03-25T02:26:40.000Z
src/main/java/nl/dtls/fairdatapoint/service/metadata/generic/GenericMetadataService.java
EOSC-synergy/FAIRDataPoint
4d5e6eb8722b9ae6cd73f7e9f565f84568b5ef18
[ "MIT" ]
null
null
null
/** * The MIT License * Copyright © 2017 DTL * * 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. */ package nl.dtls.fairdatapoint.service.metadata.generic; import nl.dtls.fairdatapoint.entity.exception.ForbiddenException; import nl.dtls.fairdatapoint.entity.exception.ValidationException; import nl.dtls.fairdatapoint.entity.metadata.Metadata; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; import nl.dtls.fairdatapoint.entity.user.UserRole; import nl.dtls.fairdatapoint.service.metadata.common.AbstractMetadataService; import nl.dtls.fairdatapoint.service.metadata.exception.MetadataServiceException; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; import org.springframework.security.acls.domain.BasePermission; import org.springframework.stereotype.Service; import java.util.Optional; import static nl.dtls.fairdatapoint.entity.metadata.MetadataGetter.getParent; @Service("genericMetadataService") public class GenericMetadataService extends AbstractMetadataService { @Override public Model store(Model metadata, IRI uri, ResourceDefinition rd) throws MetadataServiceException { if (!rd.getName().equals("Repository")) { // 1. Check permissions String parentId = Optional.ofNullable(getParent(metadata)) .orElseThrow(() -> new ValidationException("Metadata has no parent")).stringValue(); if (!(memberService.checkPermission(parentId, Metadata.class, BasePermission.CREATE) || memberService.checkRole(UserRole.ADMIN))) { throw new ForbiddenException("You are not allow to add new entry"); } } // 2. Store return super.store(metadata, uri, rd); } }
45.933333
143
0.758708
6a1114d524a98f0def2be1971d0f477cb5c91412
1,167
dart
Dart
test/staff_data_test.dart
wondenge/fineract.dart
472f5d60d345365b6c362c20bc3f6fbcf4aad622
[ "Apache-2.0" ]
1
2022-03-19T12:23:23.000Z
2022-03-19T12:23:23.000Z
test/staff_data_test.dart
wondenge/fineract.dart
472f5d60d345365b6c362c20bc3f6fbcf4aad622
[ "Apache-2.0" ]
null
null
null
test/staff_data_test.dart
wondenge/fineract.dart
472f5d60d345365b6c362c20bc3f6fbcf4aad622
[ "Apache-2.0" ]
null
null
null
import 'package:openapi/api.dart'; import 'package:test/test.dart'; // tests for StaffData void main() { var instance = new StaffData(); group('test StaffData', () { // int id (default value: null) test('to test the property `id`', () async { // TODO }); // String firstname (default value: null) test('to test the property `firstname`', () async { // TODO }); // String lastname (default value: null) test('to test the property `lastname`', () async { // TODO }); // String displayName (default value: null) test('to test the property `displayName`', () async { // TODO }); // int officeId (default value: null) test('to test the property `officeId`', () async { // TODO }); // String officeName (default value: null) test('to test the property `officeName`', () async { // TODO }); // DateTime joiningDate (default value: null) test('to test the property `joiningDate`', () async { // TODO }); // int rowIndex (default value: null) test('to test the property `rowIndex`', () async { // TODO }); }); }
22.018868
57
0.56641
fb5c5e2b1407a3b1aa4e8e57ee92c7417c9ac518
142
h
C
src/globalinclude/common/basecommon.h
tangtgithub/common_robotframe
f098d688bde1d2b2d5d6fac430c98b952621b7c1
[ "MIT" ]
5
2021-07-21T11:38:09.000Z
2021-11-26T03:16:09.000Z
src/globalinclude/common/basecommon.h
tangtgithub/common_robotframe
f098d688bde1d2b2d5d6fac430c98b952621b7c1
[ "MIT" ]
null
null
null
src/globalinclude/common/basecommon.h
tangtgithub/common_robotframe
f098d688bde1d2b2d5d6fac430c98b952621b7c1
[ "MIT" ]
null
null
null
#ifndef __BASECOMMON_H #define __BASECOMMON_H #ifndef SUCCESS #define SUCCESS 0 #endif #ifndef FAILURE #define FAILURE -1 #endif #endif
8.875
22
0.767606
e54d0ad14a5df6b1c1cb3567da7dcacccd6a8170
1,330
tsx
TypeScript
src/components/SkjemaFeiloppsummering.tsx
navikt/syfomodiaperson
5d99a9a618779284f813c66fb1a479be02305c15
[ "MIT" ]
null
null
null
src/components/SkjemaFeiloppsummering.tsx
navikt/syfomodiaperson
5d99a9a618779284f813c66fb1a479be02305c15
[ "MIT" ]
111
2020-02-26T15:17:37.000Z
2022-03-30T11:34:02.000Z
src/components/SkjemaFeiloppsummering.tsx
navikt/syfomodiaperson
5d99a9a618779284f813c66fb1a479be02305c15
[ "MIT" ]
null
null
null
import { Feiloppsummering, FeiloppsummeringFeil } from "nav-frontend-skjema"; import React, { ReactElement, useEffect, useRef } from "react"; import { harFeilmeldinger, SkjemaFeil } from "@/utils/valideringUtils"; import { FlexColumn, FlexRow, PaddingSize } from "./Layout"; interface SkjemaFeiloppsummeringProps { errors?: SkjemaFeil; } export const texts = { title: "For å gå videre må du rette opp følgende:", }; const getFeiloppsummeringFeil = (errors: SkjemaFeil): FeiloppsummeringFeil[] => Object.entries(errors) .filter(([, value]) => value !== undefined) .map(([key, value]) => ({ skjemaelementId: key, feilmelding: value || "", })); export const SkjemaFeiloppsummering = ({ errors, }: SkjemaFeiloppsummeringProps): ReactElement => { const feiloppsummeringRef = useRef<HTMLDivElement>(null); useEffect(() => { const { current } = feiloppsummeringRef; if (current !== null) { current.focus(); } }, [feiloppsummeringRef]); return errors && harFeilmeldinger(errors) ? ( <FlexRow bottomPadding={PaddingSize.MD}> <FlexColumn flex={1}> <Feiloppsummering innerRef={feiloppsummeringRef} tittel={texts.title} feil={getFeiloppsummeringFeil(errors)} /> </FlexColumn> </FlexRow> ) : ( <></> ); };
28.297872
79
0.653383
548ad716956c5e82e455a5098252dc7664d726e5
3,653
sql
SQL
script/package/pkg_log_i.body.sql
lourencomcviana/log-schema
926fc3f63896d4f5a7a39f05beb87691f0967f81
[ "MIT" ]
2
2019-05-31T05:37:22.000Z
2019-11-05T17:03:55.000Z
script/package/pkg_log_i.body.sql
lourencomcviana/log-schema
926fc3f63896d4f5a7a39f05beb87691f0967f81
[ "MIT" ]
null
null
null
script/package/pkg_log_i.body.sql
lourencomcviana/log-schema
926fc3f63896d4f5a7a39f05beb87691f0967f81
[ "MIT" ]
1
2019-05-31T05:37:27.000Z
2019-05-31T05:37:27.000Z
create or replace PACKAGE BODY log_audit.PKG_LOG_I AS FUNCTION TO_XML(p_resource IN CLOB) RETURN XMLTYPE IS T_ENTRADA XMLTYPE; BEGIN IF (p_resource IS NOT NULL) THEN T_ENTRADA := XMLTYPE(p_resource); END IF; RETURN T_ENTRADA; END; procedure P_LOG(P_Mensagem IN VARCHAR2) AS BEGIN LOG_AUDIT.pkg_log.P_LOG(p_Mensagem); END P_LOG; procedure P_LOG(P_Mensagem IN VARCHAR2, LOG_REFERENCE IN OUT CLOB) AS t_reference xmltype := to_xml(LOG_REFERENCE); BEGIN LOG_AUDIT.pkg_log.P_LOG(p_Mensagem, t_reference); if (t_reference is not null) then LOG_REFERENCE := t_reference.getClobVal(); end if; END P_LOG; procedure P_LOG(P_Mensagem IN VARCHAR2, P_priority IN NUMBER) AS BEGIN LOG_AUDIT.pkg_log.P_LOG(p_Mensagem, P_priority); END P_LOG; procedure P_LOG(P_Mensagem IN VARCHAR2, P_priority IN NUMBER, LOG_REFERENCE IN OUT CLOB) AS t_reference xmltype := to_xml(LOG_REFERENCE); BEGIN LOG_AUDIT.pkg_log.P_LOG(p_Mensagem, P_priority, t_reference); if (t_reference is not null) then LOG_REFERENCE := t_reference.getClobVal(); end if; END P_LOG; procedure P_LOG(P_Mensagem IN VARCHAR2, P_CONTEXT IN Varchar2) AS BEGIN LOG_AUDIT.pkg_log.P_LOG(p_Mensagem, P_CONTEXT); END P_LOG; procedure P_LOG(P_Mensagem IN VARCHAR2, P_CONTEXT IN Varchar2, LOG_REFERENCE IN OUT CLOB) AS t_reference xmltype := to_xml(LOG_REFERENCE); BEGIN LOG_AUDIT.pkg_log.P_LOG(p_Mensagem, P_CONTEXT, t_reference); if (t_reference is not null) then LOG_REFERENCE := t_reference.getClobVal(); end if; END P_LOG; procedure P_LOG(P_Mensagem IN VARCHAR2, P_priority IN NUMBER, P_CONTEXT IN Varchar2) AS BEGIN LOG_AUDIT.pkg_log.P_LOG(p_Mensagem, P_priority, P_CONTEXT); END P_LOG; procedure P_LOG(P_Mensagem IN VARCHAR2, P_priority IN NUMBER, P_CONTEXT IN Varchar2, LOG_REFERENCE IN OUT CLOB) AS t_reference xmltype := to_xml(LOG_REFERENCE); BEGIN LOG_AUDIT.pkg_log.P_LOG(p_Mensagem, P_priority, P_CONTEXT, t_reference); if (t_reference is not null) then LOG_REFERENCE := t_reference.getClobVal(); end if; END P_LOG; procedure P_ADD_clob(p_Name IN VARCHAR2, p_Value IN CLOB, LOG_REFERENCE in OUT clob) as t_reference xmltype := to_xml(LOG_REFERENCE); BEGIN LOG_AUDIT.pkg_log.P_add(p_Name, p_Value, t_reference); if (t_reference is not null) then LOG_REFERENCE := t_reference.getClobVal(); end if; END; procedure P_ADD_xml(p_Name IN VARCHAR2, p_Value IN clob, LOG_REFERENCE in OUT clob) as t_reference xmltype := to_xml(LOG_REFERENCE); t_value xmltype := to_xml(p_Value); BEGIN LOG_AUDIT.pkg_log.P_add(p_Name, t_value, t_reference); if (t_reference is not null) then LOG_REFERENCE := t_reference.getClobVal(); end if; END; procedure P_ADD_date(p_Name IN VARCHAR2, p_Value IN DATE, LOG_REFERENCE in OUT clob) as t_reference xmltype := to_xml(LOG_REFERENCE); BEGIN LOG_AUDIT.pkg_log.P_add(p_Name, p_Value, t_reference); if (t_reference is not null) then LOG_REFERENCE := t_reference.getClobVal(); end if; END; procedure P_ADD_number(p_Name IN VARCHAR2, p_Value IN NUMBER, LOG_REFERENCE in OUT clob) as t_reference xmltype := to_xml(LOG_REFERENCE); BEGIN LOG_AUDIT.pkg_log.P_add(p_Name, p_Value, t_reference); if (t_reference is not null) then LOG_REFERENCE := t_reference.getClobVal(); end if; END; END;
30.957627
116
0.692855
04d230f61a7275d50b5448662f7dd8f56b679de3
703
java
Java
app/src/main/java/org/andresoviedo/app/model3D/Atlas/CustomRelativeLayout.java
jolyDev/muse
a80e6a01ed29d9da508eda7b3bd05dbb2f8450e2
[ "MIT" ]
1
2021-01-09T18:16:51.000Z
2021-01-09T18:16:51.000Z
app/src/main/java/org/andresoviedo/app/model3D/Atlas/CustomRelativeLayout.java
jolyDev/muse
a80e6a01ed29d9da508eda7b3bd05dbb2f8450e2
[ "MIT" ]
null
null
null
app/src/main/java/org/andresoviedo/app/model3D/Atlas/CustomRelativeLayout.java
jolyDev/muse
a80e6a01ed29d9da508eda7b3bd05dbb2f8450e2
[ "MIT" ]
null
null
null
package org.andresoviedo.app.model3D.Atlas; import android.content.Context; import android.util.AttributeSet; import android.widget.RelativeLayout; public abstract class CustomRelativeLayout extends RelativeLayout { public CustomRelativeLayout(Context context) { super(context); } public CustomRelativeLayout(Context context, AttributeSet attrs) { super(context, attrs); } protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); try { getPageContent(); } catch (Exception e) { e.printStackTrace(); } } abstract protected void getPageContent(); }
26.037037
74
0.668563
fbe6b5aa264cdce2b2ac6a9dc55c3e6d7cf28b1f
19,313
java
Java
src/main/java/org/mmarini/genesis/model3/DDRMWrapper.java
m-marini/genesis
c8e94c3f11e1ff3a2b97e624a4d19c16eb288762
[ "MIT" ]
null
null
null
src/main/java/org/mmarini/genesis/model3/DDRMWrapper.java
m-marini/genesis
c8e94c3f11e1ff3a2b97e624a4d19c16eb288762
[ "MIT" ]
4
2021-07-13T12:55:20.000Z
2022-01-10T23:32:32.000Z
src/main/java/org/mmarini/genesis/model3/DDRMWrapper.java
m-marini/genesis
c8e94c3f11e1ff3a2b97e624a4d19c16eb288762
[ "MIT" ]
null
null
null
/* * * Copyright (c) 2021 Marco Marini, marco.marini@mmarini.org * * 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. * * END OF TERMS AND CONDITIONS * */ package org.mmarini.genesis.model3; import io.reactivex.rxjava3.functions.Function3; import io.reactivex.rxjava3.functions.Function4; import org.ejml.data.DMatrixRMaj; import org.ejml.dense.row.CommonOps_DDRM; import java.util.function.BiFunction; import java.util.function.DoublePredicate; import java.util.function.DoubleUnaryOperator; import java.util.stream.IntStream; import static org.ejml.dense.row.CommonOps_DDRM.elementLog; /** * */ public class DDRMWrapper implements Matrix { private final DMatrixRMaj matrix; /** * @param matrix the matrix */ public DDRMWrapper(DMatrixRMaj matrix) { this.matrix = matrix; } @Override public Matrix add(Matrix other) { assert matrix.getNumRows() == other.getNumRows() && matrix.getNumCols() == other.getNumCols() : String.format("Matrix %dx%d != Matrix %dx%d", matrix.getNumRows(), matrix.getNumCols(), other.getNumRows(), other.getNumCols()); return new DDRMWrapper(CommonOps_DDRM.add(matrix, ((DDRMWrapper) other).get(), null)); } @Override public Matrix addi(double other) { return mapi(v -> v + other); } @Override public Matrix addi(Matrix other) { if (other.getNumRows() == 1) { if (other.getNumCols() == 1) { return addi(other.get(0, 0)); } else { assert other.getNumCols() == matrix.getNumCols() : String.format("Invalid operation %dx%d + %dx%d", matrix.getNumRows(), matrix.getNumCols(), other.getNumRows(), other.getNumCols()); return mapi((v, i, j) -> v + other.get(0, j)); } } else if (other.getNumCols() == 1) { assert other.getNumRows() == matrix.getNumRows() : String.format("Invalid operation %dx%d + %dx%d", matrix.getNumRows(), matrix.getNumCols(), other.getNumRows(), other.getNumCols()); return mapi((v, i, j) -> v + other.get(i, 0)); } else { CommonOps_DDRM.addEquals(matrix, ((DDRMWrapper) other).get()); return this; } } @Override public Matrix assign(Matrix other, int row, int col) { CommonOps_DDRM.extract(((DDRMWrapper) other).matrix, 0, other.getNumRows(), 0, other.getNumCols(), matrix, row, col); return this; } /** * @param col the column * @param f the mapper */ public Matrix assignCol(int col, BiFunction<Double, Integer, Double> f) { return mapiCols((v, i, j, k) -> f.apply(v, i), col); } @Override public Matrix assignCols(Matrix other, int... cols) { assert other.getNumRows() == matrix.getNumRows() : String.format("cannot insert columns %dx%d into %dx%d", other.getNumRows(), other.getNumCols(), matrix.getNumRows(), matrix.getNumCols()); assert other.getNumCols() == cols.length : String.format("Mismatched indexing %d columns of %dx%d map", cols.length, other.getNumRows(), other.getNumCols()); int[] rows = IntStream.range(0, matrix.getNumRows()).toArray(); CommonOps_DDRM.insert(((DDRMWrapper) other).get(), matrix, rows, matrix.getNumRows(), cols, cols.length); return this; } /** * @param row the row * @param f the mapper */ public Matrix assignRow(int row, BiFunction<Double, Integer, Double> f) { return mapiRows((v, i, j, k) -> f.apply(v, j), row); } /** * @param other other matrix * @param rows the destination columns */ public Matrix assignRows(Matrix other, int... rows) { assert other.getNumCols() == matrix.getNumCols() : String.format("cannot insert columns %dx%d into %dx%d", other.getNumRows(), other.getNumCols(), matrix.getNumRows(), matrix.getNumCols()); assert other.getNumRows() == rows.length : String.format("Mismatched indexing %d columns of %dx%d map", rows.length, other.getNumRows(), other.getNumCols()); int[] cols = IntStream.range(0, matrix.getNumCols()).toArray(); CommonOps_DDRM.insert(((DDRMWrapper) other).get(), matrix, rows, rows.length, cols, matrix.getNumCols()); return this; } @Override public Matrix cdfiRows() { int n = matrix.getNumRows(); int m = matrix.getNumCols(); Matrix sum = sumCols(); for (int i = 1; i < n; i++) { for (int j = 0; j < m; j++) { matrix.set(i, j, matrix.get(i, j) + matrix.get(i - 1, j)); } } return divi(sum); } @Override public int[] cellsOf(DoublePredicate p) { return IntStream.range(0, matrix.getData().length) .filter(i -> p.test(matrix.get(i))) .toArray(); } @Override public int[] choose(Matrix selector) { assert selector.getNumRows() == 1 : String.format("selector %dx%d is not a row matrix ", selector.getNumRows(), selector.getNumCols()); assert matrix.getNumCols() == selector.getNumCols() : String.format("selector %dx%d has different # columns than %dx%d", selector.getNumRows(), selector.getNumCols(), getNumRows(), getNumCols()); final int n = getNumRows(); final int m = getNumCols(); final int[] result = new int[m]; for (int j = 0; j < m; j++) { result[j] = n - 1; final double v = selector.get(0, j); for (int i = 0; i < n - 1; i++) { if (v < matrix.get(i, j)) { result[j] = i; break; } } } return result; } @Override public Matrix copy() { return new DDRMWrapper(matrix.copy()); } @Override public Matrix createLike() { return new DDRMWrapper(matrix.createLike()); } @Override public Matrix divi(double value) { CommonOps_DDRM.divide(matrix, value, matrix); return this; } @Override public Matrix divi(Matrix other) { if (other.getNumRows() == 1) { if (other.getNumCols() == 1) { return divi(other.get(0, 0)); } else { assert other.getNumCols() == matrix.getNumCols() : String.format("Invalid operation %dx%d * %dx%d", matrix.getNumRows(), matrix.getNumCols(), other.getNumRows(), other.getNumCols()); return mapi((v, i, j) -> v / other.get(0, j)); } } else if (other.getNumCols() == 1) { assert other.getNumRows() == matrix.getNumRows() : String.format("Invalid operation %dx%d * %dx%d", matrix.getNumRows(), matrix.getNumCols(), other.getNumRows(), other.getNumCols()); return mapi((v, i, j) -> v / other.get(i, 0)); } else { CommonOps_DDRM.elementDiv(matrix, ((DDRMWrapper) other).get()); return this; } } @Override public Matrix expi() { CommonOps_DDRM.elementExp(matrix, matrix); return this; } @Override public Matrix expm1i() { return mapi(Math::expm1); } @Override public Matrix extractCols(int... cols) { int n = matrix.getNumRows(); int[] rows = IntStream.range(0, n).toArray(); DMatrixRMaj result = CommonOps_DDRM.extract(matrix, rows, rows.length, cols, cols.length, null); return new DDRMWrapper(result); } @Override public Matrix extractColumn(int col) { return new DDRMWrapper(CommonOps_DDRM.extractColumn(matrix, col, null)); } @Override public Matrix extractRow(int row) { return new DDRMWrapper(CommonOps_DDRM.extractRow(matrix, row, null)); } /** * @param rows the rows */ @Override public Matrix extractRows(int... rows) { int m = matrix.getNumCols(); int[] cols = IntStream.range(0, m).toArray(); DMatrixRMaj result = CommonOps_DDRM.extract(matrix, rows, rows.length, cols, cols.length, null); return new DDRMWrapper(result); } @Override public double get(final int i, final int j) { return matrix.get(i, j); } public DMatrixRMaj get() { return matrix; } /** * */ DMatrixRMaj getMatrix() { return matrix; } @Override public int getNumCols() { return matrix.getNumCols(); } @Override public int getNumRows() { return matrix.getNumRows(); } @Override public Matrix insert(Matrix other, int row, int col) { CommonOps_DDRM.insert(((DDRMWrapper) other).get(), matrix, row, col); return this; } public Matrix logi() { elementLog(matrix, matrix); return this; } @Override public Matrix lti() { return mapi(v -> v < 0.0 ? 1.0 : 0.0); } @Override public Matrix mapi(DoubleUnaryOperator mapper) { CommonOps_DDRM.apply(matrix, mapper::applyAsDouble, matrix); return this; } /** * @param f the mapper */ public Matrix mapi(Function3<Double, Integer, Integer, Double> f) { return mapi(0, matrix.getNumRows() - 1, 0, matrix.getNumCols() - 1, f); } @Override public Matrix mapi(int startRow, int endRow, int startCol, int endCol, Function3<Double, Integer, Integer, Double> mapper) { for (int i = startRow; i <= endRow; i++) { for (int j = startCol; j <= endCol; j++) { try { double v = mapper.apply(matrix.get(i, j), i, j); matrix.set(i, j, v); } catch (Throwable e) { throw new IllegalArgumentException(e); } } } return this; } @Override public Matrix mapi(int startRow, int endRow, int startCol, int endCol, DoubleUnaryOperator mapper) { for (int i = startRow; i <= endRow; i++) { for (int j = startCol; j <= endCol; j++) { try { double v = mapper.applyAsDouble(matrix.get(i, j)); matrix.set(i, j, v); } catch (Throwable e) { throw new IllegalArgumentException(e); } } } return this; } /** * @param mapper the mapper * @param cols the columns */ public Matrix mapiCols(Function4<Double, Integer, Integer, Integer, Double> mapper, int... cols) { int n = matrix.getNumRows(); int m = cols.length; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { try { int k = cols[j]; double v = mapper.apply(matrix.get(i, k), i, j, k); matrix.set(i, k, v); } catch (Throwable e) { throw new IllegalArgumentException(e); } } } return this; } /** * @param mapper the mapper * @param rows the rows */ public Matrix mapiRows(Function4<Double, Integer, Integer, Integer, Double> mapper, int... rows) { int n = rows.length; int m = matrix.getNumCols(); for (int i = 0; i < n; i++) { int k = rows[i]; for (int j = 0; j < m; j++) { try { double v = mapper.apply(matrix.get(k, j), i, j, k); matrix.set(k, j, v); } catch (Throwable e) { throw new IllegalArgumentException(e); } } } return this; } @Override public double max() { return CommonOps_DDRM.elementMax(matrix); } /** * Returns matrix[i][j] = max(matrix[i][j], value) * * @param value the value */ public Matrix maxi(double value) { return mapi(v -> Math.max(v, value)); } @Override public double min() { return CommonOps_DDRM.elementMin(matrix); } /** * */ public Matrix minCols() { return new DDRMWrapper(CommonOps_DDRM.minCols(matrix, null)); } @Override public Matrix mini(double value) { return mapi(v -> Math.min(v, value)); } /** * @param other the other matrix */ public Matrix mini(Matrix other) { assert matrix.getNumRows() == other.getNumRows() && matrix.getNumCols() == other.getNumCols() : String.format("mini between different martrices %dx%d, %dx%d ", matrix.getNumRows(), matrix.getNumCols(), other.getNumRows(), other.getNumCols()); return mapi((x, i, j) -> Math.min(x, other.get(i, j))); } /** * @param other the other matrix */ public Matrix muli(double other) { CommonOps_DDRM.scale(other, matrix); return this; } /** * @param other the other matrix */ public Matrix muli(Matrix other) { if (other.getNumRows() == 1) { if (other.getNumCols() == 1) { return muli(other.get(0, 0)); } else { assert other.getNumCols() == matrix.getNumCols() : String.format("Invalid operation %dx%d * %dx%d", matrix.getNumRows(), matrix.getNumCols(), other.getNumRows(), other.getNumCols()); return mapi((v, i, j) -> v * other.get(0, j)); } } else if (other.getNumCols() == 1) { assert other.getNumRows() == matrix.getNumRows() : String.format("Invalid operation %dx%d * %dx%d", matrix.getNumRows(), matrix.getNumCols(), other.getNumRows(), other.getNumCols()); return mapi((v, i, j) -> v * other.get(i, 0)); } else { CommonOps_DDRM.elementMult(matrix, ((DDRMWrapper) other).get()); return this; } } /** * Returns the negative in place */ public Matrix negi() { CommonOps_DDRM.changeSign(matrix); return this; } /** * Returns matrix[i][j] = pow(matrix[i][j], value) * * @param value the value */ public Matrix powi(double value) { CommonOps_DDRM.elementPower(matrix, value, matrix); return this; } /** * @param other the other matrix */ public Matrix prod(Matrix other) { assert matrix.getNumRows() == 1 && other.getNumCols() == 1 || matrix.getNumCols() == 1 && other.getNumRows() == 1 : String.format("External product %dx%d ^ %dx%d not allowed", matrix.getNumRows(), matrix.getNumCols(), other.getNumRows(), other.getNumCols()); if (matrix.getNumRows() == 1 && other.getNumCols() == 1) { int n = other.getNumRows(); int m = matrix.getNumCols(); DMatrixRMaj result = new DMatrixRMaj(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { result.set(i, j, matrix.get(0, j) * other.get(i, 0)); } } return new DDRMWrapper(result); } else { int n = matrix.getNumRows(); int m = other.getNumCols(); DMatrixRMaj result = new DMatrixRMaj(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { result.set(i, j, other.get(0, j) * matrix.get(i, 0)); } } return new DDRMWrapper(result); } } /** * @param row the row * @param col the column * @param value the value */ public Matrix set(int row, int col, double value) { matrix.set(row, col, value); return this; } @Override public Matrix softmaxi() { expi(); double sum = CommonOps_DDRM.sumCols( CommonOps_DDRM.sumRows(matrix, null), null ).get(0); return divi(sum); } /** * @param value the value */ public Matrix subi(double value) { return mapi(v -> v - value); } /** * @param other the other matrix */ public Matrix subi(Matrix other) { if (other.getNumRows() == 1) { if (other.getNumCols() == 1) { return subi(other.get(0, 0)); } else { assert other.getNumCols() == matrix.getNumCols() : String.format("Invalid operation %dx%d - %dx%d", matrix.getNumRows(), matrix.getNumCols(), other.getNumRows(), other.getNumCols()); return mapi((v, i, j) -> v - other.get(0, j)); } } else if (other.getNumCols() == 1) { assert other.getNumRows() == matrix.getNumRows() : String.format("Invalid operation %dx%d - %dx%d", matrix.getNumRows(), matrix.getNumCols(), other.getNumRows(), other.getNumCols()); return mapi((v, i, j) -> v - other.get(i, 0)); } else { CommonOps_DDRM.subtractEquals(matrix, ((DDRMWrapper) other).get()); return this; } } /** * */ public Matrix sumCols() { return new DDRMWrapper(CommonOps_DDRM.sumCols(matrix, null)); } @Override public String toString() { return String.valueOf(matrix); } /** * */ public Matrix trasposei() { CommonOps_DDRM.transpose(matrix); return this; } }
32.028192
128
0.532646
dc168bd0e7005a5e22eaf2162f8fc80c926108a9
7,426
py
Python
widgets/RawBitmapAccess.py
iubica/wx-portfolio
12101986db72bcaffd9b744d514d6f9f651ad5a1
[ "MIT" ]
3
2018-03-19T07:57:10.000Z
2021-07-05T08:55:14.000Z
widgets/RawBitmapAccess.py
iubica/wx-portfolio
12101986db72bcaffd9b744d514d6f9f651ad5a1
[ "MIT" ]
6
2020-03-24T15:40:18.000Z
2021-12-13T19:46:09.000Z
widgets/RawBitmapAccess.py
iubica/wx-portfolio
12101986db72bcaffd9b744d514d6f9f651ad5a1
[ "MIT" ]
4
2018-03-29T21:59:55.000Z
2019-12-16T14:56:38.000Z
#!/usr/bin/env python import wx # use the numpy code instead of the raw access code for comparison USE_NUMPY = False # time the execution of making a bitmap? TIMEIT = False # how big to make the bitmaps DIM = 100 # should we use a wx.GraphicsContext for painting? TEST_GC = False #---------------------------------------------------------------------- # attempt to import a numeric module if requested to if USE_NUMPY: try: import numpy def makeByteArray(shape): return numpy.empty(shape, numpy.uint8) numtype = 'numpy' except ImportError: try: import numarray def makeByteArray(shape): arr = numarray.array(shape=shape, typecode='u1') arr[:] = 0 return arr numtype = 'numarray' except ImportError: USE_NUMPY = False #---------------------------------------------------------------------- class TestPanel(wx.Panel): def __init__(self, parent, log): self.log = log wx.Panel.__init__(self, parent, -1) self.Bind(wx.EVT_PAINT, self.OnPaint) if TIMEIT: import timeit timeit.s = self # Put self in timeit's global namespace as # 's' so it can be found in the code # snippets being tested. if not USE_NUMPY: t = timeit.Timer("bmp = s.MakeBitmap(10, 20, 30)") else: t = timeit.Timer("bmp = s.MakeBitmap2(10, 20, 30)") log.write("Timing...\n") num = 100 tm = t.timeit(num) log.write("%d passes in %f seconds == %f seconds per pass " % (num, tm, tm/num)) if not USE_NUMPY: log.write("using raw access\n") self.redBmp = self.MakeBitmap(178, 34, 34) self.greenBmp = self.MakeBitmap( 35, 142, 35) self.blueBmp = self.MakeBitmap( 0, 0, 139) else: log.write("using %s\n" % numtype) self.redBmp = self.MakeBitmap2(178, 34, 34) self.greenBmp = self.MakeBitmap2( 35, 142, 35) self.blueBmp = self.MakeBitmap2( 0, 0, 139) def OnPaint(self, evt): dc = wx.PaintDC(self) if not TEST_GC: dc.DrawBitmap(self.redBmp, 50, 50, True) dc.DrawBitmap(self.greenBmp, 110, 110, True) dc.DrawBitmap(self.blueBmp, 170, 50, True) self.log.write("using wx.DC\n") else: gc = wx.GraphicsContext.Create(dc) gc.DrawBitmap(self.redBmp, 50, 50, DIM,DIM) gc.DrawBitmap(self.greenBmp, 110, 110, DIM,DIM) gc.DrawBitmap(self.blueBmp, 170, 50, DIM,DIM) self.log.write("using wx.GraphicsContext\n") def MakeBitmap(self, red, green, blue, alpha=128): # Create the bitmap that we will stuff pixel values into using # the raw bitmap access classes. bmp = wx.Bitmap(DIM, DIM, 32) # Create an object that facilitates access to the bitmap's # pixel buffer pixelData = wx.AlphaPixelData(bmp) if not pixelData: raise RuntimeError("Failed to gain raw access to bitmap data.") # We have two ways to access each pixel, first we'll use an # iterator to set every pixel to the colour and alpha values # passed in. for pixel in pixelData: pixel.Set(red, green, blue, alpha) # This block of code is another way to do the same as above, # but with the accessor interface instead of the Python # iterator. It is a bit faster than the above because it # avoids the iterator/generator magic, but it is not nearly as # 'clean' looking ;-) #pixels = pixelData.GetPixels() #for y in range(DIM): # pixels.MoveTo(pixelData, 0, y) # for x in range(DIM): # pixels.Set(red, green, blue, alpha) # pixels.nextPixel() # Next we'll use the pixel accessor to set the border pixels # to be fully opaque pixels = pixelData.GetPixels() for x in range(DIM): pixels.MoveTo(pixelData, x, 0) pixels.Set(red, green, blue, wx.ALPHA_OPAQUE) pixels.MoveTo(pixelData, x, DIM-1) pixels.Set(red, green, blue, wx.ALPHA_OPAQUE) for y in range(DIM): pixels.MoveTo(pixelData, 0, y) pixels.Set(red, green, blue, wx.ALPHA_OPAQUE) pixels.MoveTo(pixelData, DIM-1, y) pixels.Set(red, green, blue, wx.ALPHA_OPAQUE) return bmp def MakeBitmap2(self, red, green, blue, alpha=128): # Make an array of bytes that is DIM*DIM in size, with enough # slots for each pixel to have a RGB and A value arr = makeByteArray( (DIM,DIM, 4) ) # just some indexes to keep track of which byte is which R, G, B, A = range(4) # initialize all pixel values to the values passed in arr[:,:,R] = red arr[:,:,G] = green arr[:,:,B] = blue arr[:,:,A] = alpha # Set the alpha for the border pixels to be fully opaque arr[0, 0:DIM, A] = wx.ALPHA_OPAQUE # first row arr[DIM-1, 0:DIM, A] = wx.ALPHA_OPAQUE # last row arr[0:DIM, 0, A] = wx.ALPHA_OPAQUE # first col arr[0:DIM, DIM-1, A] = wx.ALPHA_OPAQUE # last col # finally, use the array to create a bitmap bmp = wx.BitmapFromBufferRGBA(DIM, DIM, arr) return bmp #---------------------------------------------------------------------- def runTest(frame, nb, log): win = TestPanel(nb, log) return win #---------------------------------------------------------------------- overview = """<html><body> <h2><center>Raw Bitmap Access</center></h2> wx.NativePixelData and wx.AlphaPixelData provide a cross-platform way to access the platform-specific pixel buffer within a wx.Bitmap. They provide both a random access method, and an iterator interface. <p>Unfortunately, although these classes are convienient ways to access and update the contents of a wx.Bitmap, we lose most of the efficiency of the C++ classes by requiring one or more Python-to-C++ transitions for each pixel. In fact it can be <b>much</b> slower than the other ways of creating a bitmap from scratch, especially now that wx.BitmapFromBuffer exists and can save the time needed to copy from a wx.Image. <p>To see this difference for yourself this module has been instrumented to allow you to experiment with using either the raw access or numpy/numarray, and also to time how long it takes to create 100 bitmaps like you see on the screen. Simply edit this module in the \"Demo Code\" tab and set TIMEIT to True and then watch the log window when the sample is reloaded. To try numpy or numarray (if you have them installed) then set USE_NUMPY to True as well, and watch the log window again. On my machines there is about <b>an order of magnitude</b> difference between the raw access functions and using a numarray.array with wx.BitmapFromBufferRGBA! Almost another order of magnitude improvement can be gained with using the new numpy module! </body></html> """ if __name__ == '__main__': import sys,os import run run.main(['', os.path.basename(sys.argv[0])] + sys.argv[1:])
35.5311
75
0.58551
74b5358d0a598762ad1fca2d0b407acbb0924990
1,673
js
JavaScript
pages/plugins/index.js
lizheming/drone-plugin-index
9bea7bb84f71d728c91255ee557aba6007e3b0b7
[ "MIT" ]
null
null
null
pages/plugins/index.js
lizheming/drone-plugin-index
9bea7bb84f71d728c91255ee557aba6007e3b0b7
[ "MIT" ]
null
null
null
pages/plugins/index.js
lizheming/drone-plugin-index
9bea7bb84f71d728c91255ee557aba6007e3b0b7
[ "MIT" ]
null
null
null
import Head from "next/head"; import Image from "next/image"; import Link from "next/link"; import layoutStyles from "../../styles/Layout.module.css"; import utilStyles from "../../styles/utils.module.css"; const title = 'Drone Plugin Index' const Plugins = () => { return ( <> <Head> <title>{title}</title> <link rel="icon" href="/favicon.ico" /> <meta name="description" content={title} /> <meta name="og:title" content={title} /> <meta name="twitter:card" content="summary_large_image" /> </Head> <nav className={layoutStyles.pluginHeader}> <Link href="/"> <a className={layoutStyles.logo}> <Image src={`/logo.svg`} alt={`Harness logo`} height="25px" width="115px" /> </a> </Link> <input type="text" placeholder="Search for the plugins that you want..." onKeyUp={(e) => { e.preventDefault(); if (e.key === "Enter") { router.push(`/?search=${e.target.value}`); } }} className={layoutStyles.searchInput} ></input> <Link href="/"> <a className={layoutStyles.linkButton}>Plugins</a> </Link> <Link href="/"> <a className={layoutStyles.linkButton}>Documentation</a> </Link> <Link href="/"> <a className={layoutStyles.linkButton}>Support</a> </Link> </nav> <section className={utilStyles.headingMd}> <p>Plugins galore!</p> </section> </> ); }; export default Plugins;
28.355932
66
0.517035
e7408d9ee53a491a4bc98dfcda8cefe3afb21878
1,076
js
JavaScript
src/admin/components/form/filefield/actions.js
ccetc/mahaplatform.com
6e8610fe6e835e071492784655dbb5502863d031
[ "MIT" ]
null
null
null
src/admin/components/form/filefield/actions.js
ccetc/mahaplatform.com
6e8610fe6e835e071492784655dbb5502863d031
[ "MIT" ]
52
2019-10-28T15:38:35.000Z
2022-02-28T04:23:48.000Z
src/lib/admin/components/form/filefield/actions.js
mahaplatform/mahaplatform.com
a96d8f7b12288c7cb01b036077182238c77d5b03
[ "MIT" ]
null
null
null
export const setReady = () => ({ type: 'SET_READY' }) export const loadFiles = (endpoint, token, ids) => ({ type: 'API_REQUEST', method: 'GET', endpoint, query: { $filter: { id: { $in: ids } } }, token, request: 'LOAD_FILES_REQUEST', success: 'LOAD_FILES_SUCCESS', failure: 'LOAD_FILES_FAILURE' }) export const addFile = (uniqueIdentifier, fileName, fileSize, contentType, totalChunks) => ({ type: 'ADD_FILE', uniqueIdentifier, fileName, fileSize, contentType, totalChunks }) export const uploadBegin = () => ({ type: 'UPLOAD_BEGIN' }) export const uploadProgress = (uniqueIdentifier, progress) => ({ type: 'UPLOAD_PROGRESS', uniqueIdentifier, progress }) export const uploadSuccess = (uniqueIdentifier, response) => ({ type: 'UPLOAD_SUCCESS', uniqueIdentifier, asset: response.data }) export const uploadFailure = () => ({ type: 'UPLOAD_FAILURE' }) export const removeFile = (index) => ({ type: 'REMOVE_FILE', index }) export const uploadComplete = () => ({ type: 'UPLOAD_COMPLETE' })
18.237288
93
0.64777
6da28bf60585f8e4b533a699df4317eb594430ff
6,376
asm
Assembly
src/shaders/h264/ildb/AVC_ILDB_Filter_UV_v.asm
me176c-dev/android_hardware_intel-vaapi-driver
0f2dca8d604220405e4678c0b6c4faa578d994ec
[ "MIT" ]
192
2018-01-26T11:51:55.000Z
2022-03-25T20:04:19.000Z
src/shaders/h264/ildb/AVC_ILDB_Filter_UV_v.asm
me176c-dev/android_hardware_intel-vaapi-driver
0f2dca8d604220405e4678c0b6c4faa578d994ec
[ "MIT" ]
256
2017-01-23T02:10:27.000Z
2018-01-23T10:00:05.000Z
src/shaders/h264/ildb/AVC_ILDB_Filter_UV_v.asm
me176c-dev/android_hardware_intel-vaapi-driver
0f2dca8d604220405e4678c0b6c4faa578d994ec
[ "MIT" ]
64
2018-01-30T19:51:53.000Z
2021-11-24T01:26:14.000Z
/* * Copyright © <2010>, Intel Corporation. * * 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, sub license, 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 (including the * next paragraph) 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 NON-INFRINGEMENT. * IN NO EVENT SHALL PRECISION INSIGHT AND/OR ITS SUPPLIERS 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. * * This file was originally licensed under the following license * * 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. * */ ////////// AVC LDB filter vertical UV /////////////////////////////////////////////////////// // // This filter code prepares the src data and control data for ILDB filtering on all vertical edges of UV. // // It sssumes the data for vertical de-blocking is already transposed. // // Chroma: // // +-------+-------+ // | | | // | | | // | | | // +-------+-------+ // | | | // | | | // | | | // +-------+-------+ // // V0 V1 // Edge Edge // ///////////////////////////////////////////////////////////////////////////// #if defined(_DEBUG) mov (1) EntrySignatureC:w 0xBBBC:w #endif //=============== Chroma deblocking ================ and.z.f0.0 (1) null:w r[ECM_AddrReg, BitFlags]:ub FilterLeftMbEdgeFlag:w // Check for FilterLeftMbEdgeFlag // (f0.0) jmpi BYPASS_EXT_LEFT_EDGE_UV // Get vertical border edge control data. // Get Luma maskA and maskB shr (16) TempRow0(0)<1> r[ECM_AddrReg, wEdgeCntlMapA_ExtLeftVert0]<0;1,0>:uw RRampW(0) shr (16) TempRow1(0)<1> r[ECM_AddrReg, wEdgeCntlMapB_ExtLeftVert0]<0;1,0>:uw RRampW(0) (f0.0) jmpi ILDB_LABEL(BYPASS_EXT_LEFT_EDGE_UV) // Extract UV MaskA and MaskB from every other bit of Y masks and.nz.f0.0 (8) null:w TempRow0(0)<16;8,2> 1:w and.nz.f0.1 (8) null:w TempRow1(0)<16;8,2> 1:w //---------- Deblock U external edge ---------- // p1 = Prev MB U row 0 // p0 = Prev MB U row 1 // q0 = Cur MB U row 0 // q1 = Cur MB U row 1 mov (1) P_AddrReg:w PREV_MB_U_BASE:w { NoDDClr } mov (1) Q_AddrReg:w SRC_MB_U_BASE:w { NoDDChk } // alpha = bAlphaLeft0_Cb, beta = bBetaLeft0_Cb mov (2) alpha<1>:w r[ECM_AddrReg, bAlphaLeft0_Cb]<2;2,1>:ub { NoDDClr } // tc0 has bTc0_v30_0_Cb + bTc0_v20_0_Cb + bTc0_v10_0_Cb + bTc0_v00_0_Cb mov (4) tc0<1>:ub r[ECM_AddrReg, bTc0_v00_0_Cb]<4;4,1>:ub { NoDDChk } // UV MaskA and MaskB mov (2) MaskA<1>:uw f0.0<2;2,1>:uw CALL(FILTER_UV, 1) //---------- Deblock V external edge ---------- // p1 = Prev MB V row 0 // p0 = Prev MB V row 1 // q0 = Cur MB V row 0 // q1 = Cur MB V row 1 mov (1) P_AddrReg:w PREV_MB_V_BASE:w { NoDDClr } mov (1) Q_AddrReg:w SRC_MB_V_BASE:w { NoDDChk } // for vert edge: alpha = bAlphaLeft0_Cr, beta = bBetaLeft0_Cr mov (2) alpha<1>:w r[ECM_AddrReg, bAlphaLeft0_Cr]<2;2,1>:ub { NoDDClr } // tc0 has bTc0_v30_0_Cr + bTc0_v20_0_Cr + bTc0_v10_0_Cr + bTc0_v00_0_Cr mov (4) tc0<1>:ub r[ECM_AddrReg, bTc0_v00_0_Cr]<4;4,1>:ub { NoDDChk } // UV MaskA and MaskB mov (2) f0.0<1>:uw MaskA<2;2,1>:uw CALL(FILTER_UV, 1) ILDB_LABEL(BYPASS_EXT_LEFT_EDGE_UV): // Set EdgeCntlMap2 = 0, so it always uses bS < 4 algorithm. // Same alpha and beta for all internal vert and horiz edges //***** Need to take every other bit to form U or V maskA // Get Luma maskA and maskB shr (16) TempRow0(0)<1> r[ECM_AddrReg, wEdgeCntlMap_IntMidVert]<0;1,0>:uw RRampW(0) //---------- Deblock U internal edge ---------- // p1 = Cur MB U row 2 // p0 = Cur MB U row 3 // q0 = Cur MB U row 4 // q1 = Cur MB U row 5 mov (1) P_AddrReg:w 4*UV_ROW_WIDTH+SRC_MB_U_BASE:w { NoDDClr } mov (1) Q_AddrReg:w 8*UV_ROW_WIDTH+SRC_MB_U_BASE:w { NoDDChk } // alpha = bAlphaInternal_Cb, beta = bBetaInternal_Cb mov (2) alpha<1>:w r[ECM_AddrReg, bAlphaInternal_Cb]<2;2,1>:ub { NoDDClr } // tc0 has bTc0_v32_Cb + bTc0_v22_Cb + bTc0_v12_Cb + bTc0_v02_Cb mov (4) tc0<1>:ub r[ECM_AddrReg, bTc0_v02_Cb]<4;4,1>:ub { NoDDChk } // Extract UV MaskA and MaskB from every other bit of Y masks and.nz.f0.0 (8) null:w TempRow0(0)<16;8,2> 1:w // UV MaskA and MaskB mov (1) f0.1:uw 0:w mov (1) MaskB:uw 0:w { NoDDClr } mov (1) MaskA:uw f0.0:uw { NoDDChk } CALL(FILTER_UV, 1) //---------- Deblock V internal edge ---------- // P1 = Cur MB V row 2 // P0 = Cur MB V row 3 // Q0 = Cur MB V row 4 // Q1 = Cur MB V row 5 mov (1) P_AddrReg:w 4*UV_ROW_WIDTH+SRC_MB_V_BASE:w { NoDDClr } mov (1) Q_AddrReg:w 8*UV_ROW_WIDTH+SRC_MB_V_BASE:w { NoDDChk } // alpha = bAlphaInternal_Cr, beta = bBetaInternal_Cr mov (2) alpha<1>:w r[ECM_AddrReg, bAlphaInternal_Cr]<2;2,1>:ub { NoDDClr } // tc0 has bTc0_v32_Cr + bTc0_v22_Cr + bTc0_v12_Cr + bTc0_v02_Cr mov (4) tc0<1>:ub r[ECM_AddrReg, bTc0_v02_Cr]<4;4,1>:ub { NoDDChk } // UV MaskA and MaskB mov (2) f0.0<1>:uw MaskA<2;2,1>:uw CALL(FILTER_UV, 1) //BYPASS_4x4_DEBLOCK_V:
36.227273
113
0.625
2d9b51f3d4096dd55ae52550374b00dc01128231
1,991
html
HTML
content/post/2020-04-15-virtual-learning-corporate-sponsorship.html
brophyj/cv_brophy_1
073c7f85d41a6e62183716d50a131b430ce2e893
[ "MIT" ]
null
null
null
content/post/2020-04-15-virtual-learning-corporate-sponsorship.html
brophyj/cv_brophy_1
073c7f85d41a6e62183716d50a131b430ce2e893
[ "MIT" ]
null
null
null
content/post/2020-04-15-virtual-learning-corporate-sponsorship.html
brophyj/cv_brophy_1
073c7f85d41a6e62183716d50a131b430ce2e893
[ "MIT" ]
null
null
null
--- title: Virtual Learning & Corporate Sponsorship author: jay brophy date: '2020-04-15' slug: virtual-learning-corporate-sponsorship categories: [] tags: [] subtitle: '' summary: '' authors: [] lastmod: '2020-04-15T20:43:31-04:00' featured: no image: caption: '' focal_point: '' preview_only: no projects: [] --- <p>One positive from the <strong>Covid-19</strong> pandemic, is we have had to learn more techniques about online or virtual learning. The proliferation of these tools, such as Zoom, and our increased familiarity with their use will perhaps have a lasting impact on our learning processes. For example, with increased ease of online learning, perhaps we will reduce our carbon footprint for small, medium and even large medical conferences as we reduce our traveling and need for physical presence at these venues.</p> <p>Certainly in the academic world, we had to rapidly adapt (within a 2 week period) from giving standard onsite lectures to the virtual teaching world. Surprisingly, the transition was relatively painless. For example, I gave the last 12 hours of the winter semester of my intermediate epidemiology course to 71 MSc students via Zoom. The cost of this is farily trivial. I believe the price of a premium Zoom subscription is about $20 / month.</p> <p>Given these facts I was not surprised to receive a recent email about an upcoming virtual course on heart failure.</p> <p><img src="/img/ScreenShot_1.png" /></p> <p>However, what did surprise me was seeing that this symposium had <strong>12 corporate sponsors</strong>!</p> <p><img src="/img/ScreenShot_2.png" /></p> <p>This raises several questions:<br /> - Why are academics so tied in with coroporate interests?<br /> - Are academics only willing to participate if personal financial rewards are present?<br /> - Coroporations are not philatrophic organizations, so what is the payoff for them?<br /> - Is it a quasi guarantee that their products will be highlighted in a positive manner?</p>
60.333333
518
0.765947
e99f0f6926564e9aecab7c628368f305f93e6ea7
2,586
go
Go
server.go
go-pkgz/mongo
ccd6f6bcd446a74698fb3476c9ead00e51d30e64
[ "MIT" ]
14
2018-07-25T07:23:05.000Z
2020-09-15T11:06:17.000Z
server.go
go-pkgz/mongo
ccd6f6bcd446a74698fb3476c9ead00e51d30e64
[ "MIT" ]
2
2019-10-07T02:36:29.000Z
2019-11-22T07:30:55.000Z
server.go
go-pkgz/mongo
ccd6f6bcd446a74698fb3476c9ead00e51d30e64
[ "MIT" ]
null
null
null
package mongo import ( "context" "errors" "fmt" "io" "io/ioutil" "net/url" "strings" "go.mongodb.org/mongo-driver/bson" driver "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) // Connect to mongo url and return client. Supports expanded url params to pass a set of custom values in the url func Connect(ctx context.Context, opts *options.ClientOptions, url string, extras ...string) (*driver.Client, map[string]interface{}, error) { mongoURL, extMap, err := parseExtMongoURI(url, extras) if err != nil { return nil, nil, fmt.Errorf("can't parse mongo url: %w", err) } res, err := driver.Connect(ctx, opts.ApplyURI(mongoURL)) if err != nil { return nil, nil, fmt.Errorf("can't connect to mongo: %w", err) } if err = res.Ping(ctx, nil); err != nil { return nil, nil, fmt.Errorf("can't ping mongo: %w", err) } return res, extMap, nil } // parseExtMongoURI extracts extra params from extras list and remove them from the url. // Input example: mongodb://user:password@127.0.0.1:27017/test?ssl=true&ava_db=db1&ava_coll=coll1 func parseExtMongoURI(uri string, extras []string) (string, map[string]interface{}, error) { if uri == "" { return "", nil, errors.New("empty url") } if len(extras) == 0 { return uri, nil, nil } exMap := map[string]interface{}{} u, err := url.Parse(uri) if err != nil { return "", nil, err } q := u.Query() for _, ex := range extras { if val := u.Query().Get(ex); val != "" { exMap[ex] = val } q.Del(ex) } u.RawQuery = q.Encode() return u.String(), exMap, nil } // PrepSort prepares sort params for mongo driver and returns bson.D // Input string provided as [+|-]field1,[+|-]field2,[+|-]field3... // + means ascending, - means descending. Lack of + or - in the beginning of the field name means ascending sort. func PrepSort(sort ...string) bson.D { res := bson.D{} for _, s := range sort { if s == "" { continue } s = strings.TrimSpace(s) switch s[0] { case '-': res = append(res, bson.E{Key: s[1:], Value: -1}) case '+': res = append(res, bson.E{Key: s[1:], Value: 1}) default: res = append(res, bson.E{Key: s, Value: 1}) } } return res } // PrepIndex prepares index params for mongo driver and returns IndexModel func PrepIndex(keys ...string) driver.IndexModel { return driver.IndexModel{Keys: PrepSort(keys...)} } // Bind request json body from io.Reader to bson record func Bind(r io.Reader, v interface{}) error { body, err := ioutil.ReadAll(r) if err != nil { return err } return bson.UnmarshalExtJSON(body, false, v) }
26.387755
142
0.658159
fba1c07476c59b65391c155b69b1f0231ebd3d5b
877
java
Java
lib/src/main/java/ninja/codingsolutions/solaredgeapiclient/models/EnergyDetails.java
Merano01/solar-edge-api-client
09ef3c85fd170d590ac9a1a0fed3dd61a227eeb0
[ "MIT" ]
1
2021-05-21T10:50:15.000Z
2021-05-21T10:50:15.000Z
lib/src/main/java/ninja/codingsolutions/solaredgeapiclient/models/EnergyDetails.java
Merano01/solar-edge-api-client
09ef3c85fd170d590ac9a1a0fed3dd61a227eeb0
[ "MIT" ]
12
2021-02-10T02:56:08.000Z
2021-07-20T23:48:05.000Z
lib/src/main/java/ninja/codingsolutions/solaredgeapiclient/models/EnergyDetails.java
Merano01/solar-edge-api-client
09ef3c85fd170d590ac9a1a0fed3dd61a227eeb0
[ "MIT" ]
2
2021-02-11T00:59:17.000Z
2021-05-21T06:34:05.000Z
package ninja.codingsolutions.solaredgeapiclient.models; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import ninja.codingsolutions.solaredgeapiclient.models.impl.EnergyDetailsImpl; import java.util.List; /** * Energy details */ @JsonDeserialize(as = EnergyDetailsImpl.class) public interface EnergyDetails { /** * Gets the time unit type associated with this set of energy details * @return {TimeUnitType} time unit type */ TimeUnitType getTimeUnit(); /** * Gets the power unit type associated with this set of energy details * @return {PowerUnitType} power unit type */ PowerUnitType getUnit(); /** * Get the list of detailed energy data associated with each meter on site * @return {java.util.List} list of detailed meter energy data */ List<DetailedMeterEnergy> getMeters(); }
28.290323
78
0.720639
11c61886db6ccef28adb8269ea8d3991cf22f74f
281
sql
SQL
Database/dbo/Stored Procedures/AddTableColumn.sql
cizmiak/ContractManagement
55d46eb0ae32686935bc4704f41343cf166d95b8
[ "MIT" ]
null
null
null
Database/dbo/Stored Procedures/AddTableColumn.sql
cizmiak/ContractManagement
55d46eb0ae32686935bc4704f41343cf166d95b8
[ "MIT" ]
null
null
null
Database/dbo/Stored Procedures/AddTableColumn.sql
cizmiak/ContractManagement
55d46eb0ae32686935bc4704f41343cf166d95b8
[ "MIT" ]
null
null
null
CREATE procedure dbo.AddTableColumn @table nvarchar(128), @column nvarchar(128), @type nvarchar(128) as if not exists (select * from sys.columns where object_id = object_id(@table) and name = @column) begin exec ('alter table ' + @table + ' add ' + @column + ' ' + @type) end
28.1
96
0.690391
8c0feb7f15d8ba5b378ffcc5b760eeb8d566b5b8
384
cql
SQL
demos/demo.cql
bovine/casstcl
67006b9fb4301d3930731ce986d2d00ca950ff5e
[ "BSD-3-Clause" ]
12
2015-02-24T08:32:52.000Z
2021-12-28T03:04:28.000Z
demos/demo.cql
bovine/casstcl
67006b9fb4301d3930731ce986d2d00ca950ff5e
[ "BSD-3-Clause" ]
2
2015-08-21T00:04:01.000Z
2020-08-03T16:19:15.000Z
demos/demo.cql
bovine/casstcl
67006b9fb4301d3930731ce986d2d00ca950ff5e
[ "BSD-3-Clause" ]
5
2015-06-20T08:09:52.000Z
2020-08-04T21:42:02.000Z
DROP KEYSPACE IF EXISTS casstcl_test; CREATE KEYSPACE casstcl_test WITH replication = {'class': 'SimpleStrategy', 'replication_factor':1}; USE casstcl_test; DROP TABLE IF EXISTS numbers; CREATE TABLE numbers ( row int, mylist list<text>, myset set<text>, mymap map<int,text>, primary key(row) ); CREATE TABLE rock_blobster ( row int, blobbie blob, primary key(row) );
15.36
100
0.734375
a9f235714975ea35b0542fc7188209e061f6821c
48
sql
SQL
tests/queries/118-bool-where-lte-1-0.sql
pydemo/spv_14.4
ad3b62d6bdbbfc29e56391f512ba0ee17dad4eb7
[ "Apache-2.0" ]
null
null
null
tests/queries/118-bool-where-lte-1-0.sql
pydemo/spv_14.4
ad3b62d6bdbbfc29e56391f512ba0ee17dad4eb7
[ "Apache-2.0" ]
null
null
null
tests/queries/118-bool-where-lte-1-0.sql
pydemo/spv_14.4
ad3b62d6bdbbfc29e56391f512ba0ee17dad4eb7
[ "Apache-2.0" ]
null
null
null
select count(*) from nulls where bool_0 <= 1 49
16
44
0.708333
58cc75a4fecc2a66a47f5da35135a9ec14d107cc
1,250
rs
Rust
src/main.rs
h0gan1ee/rusty-tree
97dfe0c62b9afd79f47e5dec8d195ed43b618fd6
[ "MIT" ]
1
2022-02-13T10:23:36.000Z
2022-02-13T10:23:36.000Z
src/main.rs
h0gan1ee/rusty-tree
97dfe0c62b9afd79f47e5dec8d195ed43b618fd6
[ "MIT" ]
null
null
null
src/main.rs
h0gan1ee/rusty-tree
97dfe0c62b9afd79f47e5dec8d195ed43b618fd6
[ "MIT" ]
null
null
null
use anyhow::Result; use cli::*; use io::*; use std::path::PathBuf; use structopt::StructOpt; use tree::Tree; mod cli; mod io; mod parse; mod tree; const DEFAULT_FILE_PATH: &str = "./tree.yart"; fn main() -> Result<()> { let CommandLineArgs { action, input_file } = CommandLineArgs::from_args(); let input_file = input_file.unwrap_or(PathBuf::from(DEFAULT_FILE_PATH)); let tree; match action { Action::Read => tree = get_tree_from_file(input_file).unwrap(), }; println!("\n========================================\n"); dbg_ignite(&tree, tree.root_node_index, 0); Ok(()) } fn dbg_ignite(tree: &Tree, index: usize, depth: usize) { print!("\x1b[0m-"); for _i in 0..depth { print!("---"); } print!("\x1b[0;93m[{}] \x1b[0;97m{}", depth, tree.nodes[index].name,); let children_count = tree.nodes[index].children_index_end - tree.nodes[index].children_index_start; if children_count > 0 { print!(" \x1b[0;36m({})", children_count); } println!(); if tree.nodes[index].children_index_end > 0 { for i in tree.nodes[index].children_index_start..tree.nodes[index].children_index_end { dbg_ignite(&tree, i, depth + 1); } } }
26.595745
95
0.5968
7743df2899d6874afb2c53a8fe2aa7537f5c5f8f
91
swift
Swift
Tests/LinuxMain.swift
ghjang/chord
f1b9b114c0b53e29ece66f8ed1932eb055dd47d4
[ "MIT" ]
null
null
null
Tests/LinuxMain.swift
ghjang/chord
f1b9b114c0b53e29ece66f8ed1932eb055dd47d4
[ "MIT" ]
null
null
null
Tests/LinuxMain.swift
ghjang/chord
f1b9b114c0b53e29ece66f8ed1932eb055dd47d4
[ "MIT" ]
null
null
null
import XCTest @testable import chordTests XCTMain([ testCase(chordTests.allTests), ])
13
34
0.758242
a14a3337c1c6391fba83c7423862780c0fc7238f
1,666
swift
Swift
Lemmy-iOS/Sources/Features/Instances/Instances/Views/InstancesView.swift
vladmusuz/Lemmy-iOS
b5697f48bcc2b37c8de89995d795681815675d68
[ "MIT" ]
34
2020-12-19T00:50:47.000Z
2021-07-19T04:02:43.000Z
Lemmy-iOS/Sources/Features/Instances/Instances/Views/InstancesView.swift
vladmusuz/Lemmy-iOS
b5697f48bcc2b37c8de89995d795681815675d68
[ "MIT" ]
17
2021-07-21T12:25:37.000Z
2022-03-31T16:40:03.000Z
Lemmy-iOS/Sources/Features/Instances/Instances/Views/InstancesView.swift
vladmusuz/Lemmy-iOS
b5697f48bcc2b37c8de89995d795681815675d68
[ "MIT" ]
3
2022-03-07T15:01:34.000Z
2022-03-31T23:05:40.000Z
// // InstancesView.swift // Lemmy-iOS // // Created by uuttff8 on 19.12.2020. // Copyright © 2020 Anton Kuzmin. All rights reserved. // import UIKit final class InstancesView: UIView { private let termsView = TermsOfUseView() private let tableView = LemmyTableView(style: .insetGrouped, separator: true) init() { super.init(frame: .zero) setupView() addSubviews() makeConstraints() } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } func updateTableViewData(dataSource: UITableViewDataSource & UITableViewDelegate) { _ = dataSource.tableView(self.tableView, numberOfRowsInSection: 0) // self.emptyStateLabel.isHidden = numberOfRows != 0 self.tableView.dataSource = dataSource self.tableView.delegate = dataSource self.tableView.reloadData() } func showLoadingView() { self.showActivityIndicatorView() } func hideLoadingView() { self.hideActivityIndicatorView() } override func layoutSubviews() { super.layoutSubviews() tableView.layoutTableHeaderView() } } extension InstancesView: ProgrammaticallyViewProtocol { func setupView() { tableView.tableHeaderView = termsView tableView.tableHeaderView?.backgroundColor = .clear } func addSubviews() { self.addSubview(tableView) } func makeConstraints() { self.tableView.snp.makeConstraints { $0.edges.equalToSuperview() } } }
24.144928
87
0.627851
12222e67cc7c7355c9cfe618b10d637711db943e
10,270
sql
SQL
db_onlearning.sql
gnocman/CDTNKHMT
72fb08c1fcf774c15daa693953046ddbd2727316
[ "MIT" ]
null
null
null
db_onlearning.sql
gnocman/CDTNKHMT
72fb08c1fcf774c15daa693953046ddbd2727316
[ "MIT" ]
null
null
null
db_onlearning.sql
gnocman/CDTNKHMT
72fb08c1fcf774c15daa693953046ddbd2727316
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 5.0.1 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Aug 19, 2020 at 02:19 AM -- Server version: 10.4.11-MariaDB -- PHP Version: 7.4.3 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: `db_onlearning` -- -- -------------------------------------------------------- -- -- Table structure for table `courses` -- CREATE TABLE `courses` ( `id` int(11) NOT NULL, `course_name` varchar(300) NOT NULL, `course_describe` varchar(300) NOT NULL, `qty_lesson` int(11) NOT NULL, `less_name` varchar(500) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `courses` -- INSERT INTO `courses` (`id`, `course_name`, `course_describe`, `qty_lesson`, `less_name`) VALUES (1, 'Đại số 10: Mệnh đề tập hợp', 'Mệnh đề tập hợp gồm 5 bài học chính và 1 bài ôn tập cuối chương.', 6, 'Bài 1: Mệnh đề\r\nBài 2: Tập hợp\r\nBài 3: Các phép toán tập hợp\r\nBài 4: Các tập hợp số\r\nBài 5: Số gần đúng Sai số\r\nBài 6: Ôn tập chương 1 Mệnh đề tập hợp'), (2, 'Đại số 10: Hàm số bậc nhất và bậc hai', 'Hàm số bậc nhất và bậc hai gồm 3 bài học và 1 bài ôn tập cuối chương', 4, NULL), (3, 'Đại số 10: Phương trình và hệ phương trình', 'Phương trình và hệ phương trình gồm 3 bài học chính và 1 bài ôn tập cươi chương', 4, NULL), (4, 'Đại số 10: Bất đẳng thức và bát phương trình', 'Bất đẳng thức và bất phương trình gồm 5 bài học chính và 1 bài ôn tập cuối chương', 6, NULL), (5, 'Đại số 10: Thống kê', 'Thống kê gồm 4 bài học chính và 1 bài ôn tập cuối chương', 5, NULL), (6, 'Đại số 10: Cung và góc lượng giác, công thức lượng giác', 'Cung và góc lượng giác, công thức lượng giác gồm 3 bài học chính và 1 bài ôn tập cuối chương', 4, NULL), (7, 'Hình học 10: Vec-tơ', 'Vec-tơ gòm 4 bài học chính và 1 bài ôn tập cuối chương.', 5, NULL), (8, 'Hình học 10: Tích vô hướng của hai vect-tơ và ứng dụng', 'Tích vô hướng của hai vect-tơ và ứng dụng gồm 3 bài học chính và 1 bài ôn tập cuối chương.', 4, NULL), (9, 'Hình học 10: Phương pháp tọa dộ trong mặt phẳng', 'Phương pháp tọa dộ trong mặt phẳng gồm 3 bài học chính và 1 bài ôn tập cuối chương.', 4, NULL), (10, 'Vật lý 10: Động học chất điểm', 'Động học chất điểm gồm 8 bài học chính.', 8, NULL), (11, 'Vật lý 10: Động lực học chất điểm', 'Động lực học chất điểm gồm 8 bài học chính.', 8, NULL), (12, 'Vật lý 10: Cân bằng và chuyển động của vật rắn', 'Cân bằng và chuyển động của vật rắn gồm 6 bài học chính.', 6, NULL), (13, 'Vật lý 10: Các định luật bảo toàn', 'Các định luật bảo toàn gồm 5 bài học chính.', 5, NULL), (14, 'Vật lý 10: Chất khí', 'Chất khí gồm 4 bài học chính.', 4, NULL), (15, 'Vật lý 10: Cơ sở của nhiệt động lực học', 'Cơ sở của nhiệt động lực học gồm 2 ài học chính.', 2, NULL), (16, 'Vật lý 10: Chất rắn và chất lỏng. Sự chuyển thể', 'Chất rắn và chất lỏng. Sự chuyển thể gồm 7 bài học chính.', 7, NULL), (17, 'Hóa học 10: Nguyên tử', 'Nguyên tử gồm 6 bài học chính.', 6, NULL), (18, 'Hóa học 10: Bảng tuần hoàn các nguyên tố hóa học và định luật tuần hoàn', 'Bảng tuần hoàn các nguyên tố hóa học và định luật tuần hoàn gồm 5 baafi học chính.', 5, NULL), (19, 'Hóa học 10: Liên kết hóa học', 'Liên kết hóa học gồm 5 bài học chính.', 5, NULL), (20, 'Hóa học 10: Phản ứng lõi hóa khử', 'Phản ứng õi hóa khử gồm 4 bài học chính.', 4, NULL), (21, 'Hóa học 10: Nhóm Halogen', 'Nhóm Halogen gồm 8 bài học chính.', 8, NULL), (22, 'Hóa học 10: Oxi - Lưu huỳnh', 'Oxi - Lưu huỳnh gồm 7 bài học chính.', 7, NULL), (23, 'Hóa học 10: Tốc độ phản ứng và cân bằng hóa học', 'Tốc độ phản ứng và cân bằng hóa học gồm 4 bài học chính.', 4, NULL); -- -------------------------------------------------------- -- -- Table structure for table `quiz` -- CREATE TABLE `quiz` ( `id` int(11) NOT NULL, `quiz_name` varchar(300) NOT NULL, `quiz_uptime` datetime NOT NULL, `quiz_time` varchar(200) NOT NULL, `quiz_describe` varchar(400) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `quiz` -- INSERT INTO `quiz` (`id`, `quiz_name`, `quiz_uptime`, `quiz_time`, `quiz_describe`) VALUES (2, 'Đề kiểm tra Đại số 10', '2020-08-15 18:23:43', '15 phút', NULL), (3, 'Đề kiểm tra Đại số 10', '2020-08-15 18:26:05', '45 phút', NULL), (4, 'Đề kiểm tra Đại số 10 ', '2020-08-15 18:35:56', '15 phút', NULL), (5, 'Đề kiểm tra Đại số 10 ', '2020-08-15 18:23:43', '45 phút', NULL), (6, 'Đề kiểm tra Đại số 10 ', '2020-08-15 18:37:13', '90 phút', NULL), (7, 'Đề kiểm tra Đại số 10 ', '2020-08-15 18:38:16', '15 phút', NULL), (8, 'Đề kiểm tra Đại số 10 ', '2020-08-15 18:38:54', '15 phút', NULL), (9, 'Đề kiểm tra Đại số 10 ', '2020-08-15 18:39:25', '45 phút', NULL), (10, 'Đề kiểm tra Đại số 10 ', '2020-08-15 18:39:39', '45 phút', NULL), (11, 'Đề kiểm tra Đại số 10 ', '2020-08-15 18:23:43', '90 phút', NULL), (12, 'Đề kiểm tra Hình học 10 ', '2020-08-15 18:40:33', '15 phút', NULL), (13, 'Đề kiểm tra Hình học 10 ', '2020-08-15 18:41:00', '45 phút', NULL), (14, 'Đề kiểm tra Hình học 10 ', '2020-08-15 18:41:18', '45 phút', NULL), (15, 'Đề kiểm tra Hình học 10 ', '2020-08-15 18:41:48', '15 phút', NULL), (16, 'Đề kiểm tra Hình học 10 ', '2020-08-15 18:42:04', '15 phút', NULL), (17, 'Đề kiểm tra Hình học 10 ', '2020-08-15 18:42:24', '45 phút', NULL), (18, 'Đề kiểm tra Hình học 10 ', '2020-08-15 18:42:41', '45 phút', NULL), (19, 'Đề kiểm tra Hình học 10 ', '2020-08-15 18:43:45', '90 phút', NULL), (20, 'Đề kiểm tra Hình học 10 ', '2020-08-15 18:44:04', '90 phút', NULL), (21, 'Đề kiểm tra Vật lý 10 ', '2020-08-15 18:44:19', '15 phút', NULL), (22, 'Đề kiểm tra Vật lý 10 ', '2020-08-15 18:45:52', '45 phút', NULL), (23, 'Đề kiểm tra Vật lý 10 ', '2020-08-15 18:46:48', '45 phút', NULL), (25, 'Đề kiểm tra Vật lý 10 ', '2020-08-15 18:48:26', '90 phút', NULL), (26, 'Đề kiểm tra Vật lý 10 ', '2020-08-15 18:49:45', '15 phút', NULL), (27, 'Đề kiểm tra Vật lý 10 ', '2020-08-15 18:50:19', '15 phút', NULL), (28, 'Đề kiểm tra Vật lý 10 ', '2020-08-15 18:51:16', '15 phút', NULL), (29, 'Đề kiểm tra Vật lý 10 ', '2020-08-15 18:52:07', '45 phút', NULL), (30, 'Đề kiểm tra Vật lý 10 ', '2020-08-15 18:52:36', '45 phút', NULL), (31, 'Đề kiểm tra Hóa học 10 ', '2020-08-15 18:56:21', '15 phút', NULL), (32, 'Đề kiểm tra Hóa học 10 ', '2020-08-15 18:56:59', '15 phút ', NULL), (33, 'Đề kiểm tra Hóa học 10 ', '2020-08-15 18:57:54', '45 phút', NULL), (34, 'Đề kiểm tra Hóa học 10 ', '2020-08-15 19:00:00', '45 phút', NULL), (35, 'Đề kiểm tra Hóa học 10 ', '2020-08-15 19:00:16', '90 phút', NULL), (38, 'Đề kiểm tra Hóa học 10 ', '2020-08-15 19:01:35', '15 phút', NULL), (39, 'Đề kiểm tra Hóa học 10 ', '2020-08-15 19:01:56', '15 phút', NULL), (41, 'Đề kiểm tra Hóa học 10 ', '2020-08-15 19:02:43', '45 phút', NULL), (42, 'Đề kiểm tra Hóa học 10 ', '2020-08-15 19:03:43', '45 phút', 'Đề kiểm tra Hóa học 10 45 phút'); -- -------------------------------------------------------- -- -- Table structure for table `teacher` -- CREATE TABLE `teacher` ( `id` int(11) NOT NULL, `teacher_name` varchar(200) NOT NULL, `teacher_info` varchar(300) NOT NULL, `subject` varchar(200) NOT NULL, `images` varchar(400) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `teacher` -- INSERT INTO `teacher` (`id`, `teacher_name`, `teacher_info`, `subject`, `images`) VALUES (1, 'Nguyễn Thị Thanh Hương', 'Giáo viên tốt nghiệp bằng xuất sắc ngành Sư phạm Toán của trường Đại Học Sư phạm Hà Nội', 'Toán 10', 'images/teachers/teacher1.jpg'), (2, 'Nguyễn Minh Hiếu', 'Giáo viên tốt nghiệp bằng xuất sắc ngành Sư phạm Vật lý của trường Đại Học Sư phạm Hà Nội', 'Vật lý 10', 'images/teachers/teacher2.jpg'), (3, 'Đặng Văn Hùng', 'Giáo viên tốt nghiệp bằng xuất sắc ngành Sư phạm Vật lý của trường Đại Học Sư phạm Hà Nội', 'Vật lý 10', NULL), (4, 'Vũ Anh Tú', 'Giáo viên tốt nghiệp bằng xuất sắc ngành Sư phạm Hóa học của trường Đại Học Sư phạm Hà Nội', 'Hóa học 10', NULL), (5, 'Kiều Văn Tuấn', 'Giáo viên tốt nghiệp bằng xuất sắc ngành Sư phạm Toán của trường Đại Học Sư phạm Hà Nội', 'Toán 10', NULL), (6, 'Vũ Thị Thu Hòa', 'Giáo viên tốt nghiệp bằng xuất sắc ngành Sư phạm Hóa học (Tiếng Anh) của trường Đại Học Sư phạm Hà Nội', 'Hóa học 10', NULL); -- -------------------------------------------------------- -- -- Table structure for table `user` -- CREATE TABLE `user` ( `id` int(11) NOT NULL, `username` varchar(200) NOT NULL, `password` varchar(200) NOT NULL, `is_admin` tinyint(1) NOT NULL, `is_teacher` tinyint(1) NOT NULL, `is_student` tinyint(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `user` -- INSERT INTO `user` (`id`, `username`, `password`, `is_admin`, `is_teacher`, `is_student`) VALUES (1, 'admin', 'admin', 1, 1, 1), (2, 'thuannguyen', 'thuannguyen', 1, 1, 1), (3, 'duong_dang', '12345', 0, 0, 1), (6, 'cuong', '123', 0, 1, 0), (7, 'user2', '123', 0, 0, 1), (8, 'minhhieu', '123', 0, 1, 1); -- -- Indexes for dumped tables -- -- -- Indexes for table `courses` -- ALTER TABLE `courses` ADD PRIMARY KEY (`id`); -- -- Indexes for table `quiz` -- ALTER TABLE `quiz` ADD PRIMARY KEY (`id`); -- -- Indexes for table `teacher` -- ALTER TABLE `teacher` ADD PRIMARY KEY (`id`); -- -- Indexes for table `user` -- ALTER TABLE `user` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `courses` -- ALTER TABLE `courses` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=25; -- -- AUTO_INCREMENT for table `quiz` -- ALTER TABLE `quiz` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=45; -- -- AUTO_INCREMENT for table `teacher` -- ALTER TABLE `teacher` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; -- -- AUTO_INCREMENT for table `user` -- ALTER TABLE `user` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9; 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 */;
43.151261
269
0.639046
9377f91ead7712c61d3ff049de38ae2871e9eb08
1,539
rs
Rust
test/src/sdk-harness/test_projects/script_data/mod.rs
FuelLabs/sway
0190b5dac4735fd2a34528e48cc2e0c9606b5ce8
[ "Apache-2.0" ]
75
2022-01-03T17:05:46.000Z
2022-03-26T13:25:56.000Z
test/src/sdk-harness/test_projects/script_data/mod.rs
FuelLabs/sway
0190b5dac4735fd2a34528e48cc2e0c9606b5ce8
[ "Apache-2.0" ]
442
2022-01-03T17:12:10.000Z
2022-03-31T23:30:21.000Z
test/src/sdk-harness/test_projects/script_data/mod.rs
FuelLabs/sway
0190b5dac4735fd2a34528e48cc2e0c9606b5ce8
[ "Apache-2.0" ]
25
2022-01-03T18:45:19.000Z
2022-03-25T17:24:58.000Z
use assert_matches::assert_matches; use fuel_core::service::{Config, FuelService}; use fuel_gql_client::client::FuelClient; use fuels::contract::script::Script; use fuels::tx::{default_parameters::MAX_GAS_PER_TX, Receipt, Transaction}; async fn call_script(script_data: Vec<u8>) -> Result<Vec<Receipt>, fuels::prelude::Error> { let bin = std::fs::read("test_projects/script_data/out/debug/script_data.bin"); let server = FuelService::new_node(Config::local_node()).await.unwrap(); let client = FuelClient::from(server.bound_address); let tx = Transaction::Script { gas_price: 0, gas_limit: MAX_GAS_PER_TX, maturity: 0, byte_price: 0, receipts_root: Default::default(), script: bin.unwrap(), script_data, inputs: vec![], outputs: vec![], witnesses: vec![vec![].into()], metadata: None, }; let script = Script::new(tx); script.call(&client).await } #[tokio::test] async fn script_data() { let correct_hex = hex::decode("ef86afa9696cf0dc6385e2c407a6e159a1103cefb7e2ae0636fb33d3cb2a9e4a").unwrap(); let call_result = call_script(correct_hex.clone()).await; assert_matches!(call_result, Ok(_)); let receipts = call_result.unwrap(); assert!(correct_hex == receipts[0].data().unwrap()); let bad_hex = hex::decode("bad6afa9696cf0dc6385e2c407a6e159a1103cefb7e2ae0636fb33d3cb2a9e4a").unwrap(); let call_result = call_script(bad_hex).await; assert_matches!(call_result, Err(_)); }
34.977273
97
0.679662
e7507456b74f80b6d4f750753c4f99abb766d8dc
333
js
JavaScript
src/extension/firefox/data/content.js
humina/mraid-extension
96fec2dd85dae8d494ff080ae2d1850e83336d16
[ "Apache-2.0" ]
18
2015-02-03T19:32:51.000Z
2021-03-17T18:06:40.000Z
src/extension/firefox/data/content.js
humina/mraid-extension
96fec2dd85dae8d494ff080ae2d1850e83336d16
[ "Apache-2.0" ]
2
2016-03-16T22:01:41.000Z
2018-02-23T19:59:56.000Z
src/extension/firefox/data/content.js
humina/mraid-extension
96fec2dd85dae8d494ff080ae2d1850e83336d16
[ "Apache-2.0" ]
6
2015-02-03T19:32:53.000Z
2022-02-21T08:54:00.000Z
var Resizer = require('../../resizer'); var resizer = new Resizer(), origins; resizer.on('save-origins', function(ev){ origins = ev.origins || []; self.port.emit('save-origins', origins); }); resizer.on('load-origins', function(ev){ ev.cb(origins); }); self.port.on('load-origins', function(data){ origins = data || []; });
18.5
44
0.636637
76388c673ec3eea248c0543096e28af9fb82e49d
1,607
go
Go
internal/messages/message.go
mattwalo32/RealTimeAPI
dc2fce6dd99cc68b5ab0f192ce54f38044ab0739
[ "MIT" ]
null
null
null
internal/messages/message.go
mattwalo32/RealTimeAPI
dc2fce6dd99cc68b5ab0f192ce54f38044ab0739
[ "MIT" ]
null
null
null
internal/messages/message.go
mattwalo32/RealTimeAPI
dc2fce6dd99cc68b5ab0f192ce54f38044ab0739
[ "MIT" ]
null
null
null
package messages import ( "encoding/json" "fmt" "github.com/google/uuid" "net" ) const ( MESSAGE_INVALID = iota MESSAGE_ACKNOWLEDGE MESSAGE_FIND_ROOM MESSAGE_JOIN_ROOM MESSAGE_LEAVE_ROOM MESSAGE_JOIN_SERVER MESSAGE_GAME_DATA MESSAGE_HEARTBEAT MESSAGE_STATUS MESSAGE_END_GAME ) type Message interface { Encode() ([]byte, error) Decode([]byte) GetSource() net.UDPAddr SetSource(net.UDPAddr) GetDestination() net.UDPAddr SetDestination(net.UDPAddr) SetPacketNumber(int) GetPacketNumber() int IsResponseRequired() bool SetResponseRequired(bool) GetID() uuid.UUID GetMessageType() int } type RoutableMessage interface { Message GetClientID() uuid.UUID } type encodedMessage struct { MessageType int Data []byte } func EncodeWithHeader(encodable Message) ([]byte, error) { data, err := encodable.Encode() if err != nil { return nil, err } message := encodedMessage{ MessageType: encodable.GetMessageType(), Data: data, } return json.Marshal(message) } func DecodeFromHeader(data []byte) (Message, error) { var header encodedMessage err := json.Unmarshal(data, &header) switch header.MessageType { case MESSAGE_FIND_ROOM: message := &FindRoomMessage{} message.Decode(header.Data) return message, err case MESSAGE_ACKNOWLEDGE: message := &AcknowledgementMessage{} message.Decode(header.Data) return message, err case MESSAGE_JOIN_SERVER: message := &JoinServerMessage{} message.Decode(header.Data) return message, err default: return nil, fmt.Errorf("Cannot decode unrecognized message type: %v", header.MessageType) } }
19.361446
91
0.747355
00036849f3c5a44db5b595ae8f0ca1882d792d1e
11,526
swift
Swift
Tests/EditorTests/XCTestManifests.swift
keith/DrString
4fad0e848771e5d19d7db5217402ae504c145afb
[ "MIT" ]
156
2019-09-12T03:08:12.000Z
2022-03-10T02:00:04.000Z
Tests/EditorTests/XCTestManifests.swift
keith/DrString
4fad0e848771e5d19d7db5217402ae504c145afb
[ "MIT" ]
82
2019-09-11T07:06:25.000Z
2022-03-18T20:39:52.000Z
Tests/EditorTests/XCTestManifests.swift
keith/DrString
4fad0e848771e5d19d7db5217402ae504c145afb
[ "MIT" ]
6
2019-10-03T23:14:48.000Z
2021-08-25T14:30:44.000Z
#if !canImport(ObjectiveC) import XCTest extension DocStringDescriptionFormattingTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__DocStringDescriptionFormattingTests = [ ("testDescriptionWithinColumnLimit", testDescriptionWithinColumnLimit), ("testDescriptionWithinColumnLimitWithInitialColumn", testDescriptionWithinColumnLimitWithInitialColumn), ("testEmptyLinesInDescriptionArePreserved", testEmptyLinesInDescriptionArePreserved), ("testExcessiveWhitespaceInEmptyLineAreRemoved", testExcessiveWhitespaceInEmptyLineAreRemoved), ("testFormattingEmptyDocString", testFormattingEmptyDocString), ("testLeadingWhiteSpacesInDescriptionArePreserved", testLeadingWhiteSpacesInDescriptionArePreserved), ("testLinesExceedingColumnLimitFlowsDownward", testLinesExceedingColumnLimitFlowsDownward), ("testLinesExceedingColumnLimitFlowsDownwardAndPreservesLeadingWhitespace", testLinesExceedingColumnLimitFlowsDownwardAndPreservesLeadingWhitespace), ("testSingleLeadingWhiteSpaceIsAddedIfNecessary", testSingleLeadingWhiteSpaceIsAddedIfNecessary), ] } extension DocStringParameterFormattingTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__DocStringParameterFormattingTests = [ ("testContinuationLeadingSpacesArePreservedWhenNecessary0", testContinuationLeadingSpacesArePreservedWhenNecessary0), ("testContinuationLeadingSpacesArePreservedWhenNecessary1", testContinuationLeadingSpacesArePreservedWhenNecessary1), ("testContinuationLineIsPaddedToProperLevel0", testContinuationLineIsPaddedToProperLevel0), ("testContinuationLineIsPaddedToProperLevel1", testContinuationLineIsPaddedToProperLevel1), ("testCorrectContinuationLinesArePreservedForVerticalAlignment", testCorrectContinuationLinesArePreservedForVerticalAlignment), ("testExtraIndentationsAreRemovedAndFoldingWorksProperly", testExtraIndentationsAreRemovedAndFoldingWorksProperly), ("testGroupedMultipleParameters", testGroupedMultipleParameters), ("testGroupedMultipleParametersOverColumnLimit", testGroupedMultipleParametersOverColumnLimit), ("testGroupedMultipleParametersVerticalAligned", testGroupedMultipleParametersVerticalAligned), ("testSeparateMultipleParametersNoVerticalAlignment", testSeparateMultipleParametersNoVerticalAlignment), ("testSeparateMultipleParametersVerticalAlignment", testSeparateMultipleParametersVerticalAlignment), ("testSeparateSingleParameter", testSeparateSingleParameter), ("testSeparateSingleParameterColumnLimit", testSeparateSingleParameterColumnLimit), ("testSeparateSingleParameterLowercase", testSeparateSingleParameterLowercase), ("testSeparateSingleParameterMultlineDescription", testSeparateSingleParameterMultlineDescription), ("testSeparateSingleParameterMultlineDescriptionWithInitialColumn", testSeparateSingleParameterMultlineDescriptionWithInitialColumn), ("testSeparateSingleParameterWithMissingColon", testSeparateSingleParameterWithMissingColon), ("testVerticalAlign", testVerticalAlign), ] } extension DocStringReturnsFormattingTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__DocStringReturnsFormattingTests = [ ("testFormattingBasicReturns", testFormattingBasicReturns), ("testFormattingBasicReturnsWithMissingColon", testFormattingBasicReturnsWithMissingColon), ("testFormattingColumnLimitPreservesLeadingWhitespaces", testFormattingColumnLimitPreservesLeadingWhitespaces), ("testFormattingColumnLimitRemoveExcessLeadingSpaceBeforeColon", testFormattingColumnLimitRemoveExcessLeadingSpaceBeforeColon), ("testFormattingColumnLimitWithAlignAfterColon", testFormattingColumnLimitWithAlignAfterColon), ("testFormattingColumnLimitWithoutAlignAfterColon", testFormattingColumnLimitWithoutAlignAfterColon), ("testFormattingLowercaseKeyword", testFormattingLowercaseKeyword), ] } extension DocStringSectionSeparationFormattingTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__DocStringSectionSeparationFormattingTests = [ ("testDescriptionSeparatorDoesNotGetAddedIfItsTheLastSection", testDescriptionSeparatorDoesNotGetAddedIfItsTheLastSection), ("testDescriptionSeparatorDoesNotGetAddedIfUnnecessary", testDescriptionSeparatorDoesNotGetAddedIfUnnecessary), ("testDescriptionSeparatorGetsAdded", testDescriptionSeparatorGetsAdded), ("testFormattingEmptyDocString", testFormattingEmptyDocString), ("testParameterSeparatorDoesNotGetAddedIfItsTheLastSection", testParameterSeparatorDoesNotGetAddedIfItsTheLastSection), ("testParameterSeparatorGetsAdded", testParameterSeparatorGetsAdded), ("testParametersSeparatorDoesNotGetAddedIfUnnecessary", testParametersSeparatorDoesNotGetAddedIfUnnecessary), ("testThrowsSeparatorDoesNotGetAddedIfItsTheLastSection", testThrowsSeparatorDoesNotGetAddedIfItsTheLastSection), ("testThrowsSeparatorDoesNotGetAddedIfUnnecessary", testThrowsSeparatorDoesNotGetAddedIfUnnecessary), ("testThrowsSeparatorGetsAdded", testThrowsSeparatorGetsAdded), ] } extension DocStringSeparatorTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__DocStringSeparatorTests = [ ("testAddsMissingSeparatorAfterDescription", testAddsMissingSeparatorAfterDescription), ("testAddsMissingSeparatorAfterParameters", testAddsMissingSeparatorAfterParameters), ("testAddsMissingSeparatorAfterThrows", testAddsMissingSeparatorAfterThrows), ("testDoesNotAddSeparatorAfterDescriptionIfNotNecessary", testDoesNotAddSeparatorAfterDescriptionIfNotNecessary), ("testDoesNotAddSeparatorAfterDescriptionIfNotRequired", testDoesNotAddSeparatorAfterDescriptionIfNotRequired), ("testDoesNotAddSeparatorAfterParametersIfNotNecessary", testDoesNotAddSeparatorAfterParametersIfNotNecessary), ("testDoesNotAddSeparatorAfterParametersIfNotRequired", testDoesNotAddSeparatorAfterParametersIfNotRequired), ("testDoesNotAddSeparatorAfterThrowsIfNotNecessary", testDoesNotAddSeparatorAfterThrowsIfNotNecessary), ("testDoesNotAddSeparatorAfterThrowsIfNotRequired", testDoesNotAddSeparatorAfterThrowsIfNotRequired), ] } extension DocStringThrowsFormattingTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__DocStringThrowsFormattingTests = [ ("testFormattingBasicThrows", testFormattingBasicThrows), ("testFormattingBasicThrowsWithMissingColon", testFormattingBasicThrowsWithMissingColon), ("testFormattingColumnLimitPreservesExcessLeadingSpaceAfterColon", testFormattingColumnLimitPreservesExcessLeadingSpaceAfterColon), ("testFormattingColumnLimitPreservesLeadingWhitespaces", testFormattingColumnLimitPreservesLeadingWhitespaces), ("testFormattingColumnLimitRemoveExcessLeadingSpaceBeforeColon", testFormattingColumnLimitRemoveExcessLeadingSpaceBeforeColon), ("testFormattingColumnLimitWithAlignAfterColon", testFormattingColumnLimitWithAlignAfterColon), ("testFormattingColumnLimitWithoutAlignAfterColon", testFormattingColumnLimitWithoutAlignAfterColon), ("testFormattingLowercaseKeyword", testFormattingLowercaseKeyword), ] } extension FormatRangeTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__FormatRangeTests = [ ("testAt_0_0", testAt_0_0), ("testAt_0_1", testAt_0_1), ("testAt_0_3", testAt_0_3), ("testAt_0_5", testAt_0_5), ("testAt_0_6", testAt_0_6), ("testAt_0_8", testAt_0_8), ("testAt_4_4", testAt_4_4), ("testAt_5_8", testAt_5_8), ("testAt_8_8", testAt_8_8), ] } extension LineFoldingTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__LineFoldingTests = [ ("testLineExceedingLimitFlowsDownward", testLineExceedingLimitFlowsDownward), ("testLineWithinLimitRemains", testLineWithinLimitRemains), ("testWordExceedingLimitFormItsOwnLine", testWordExceedingLimitFormItsOwnLine), ] } extension ParameterPlaceholderTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__ParameterPlaceholderTests = [ ("testGeneratePlaceholderAtAnywhereButMiddle", testGeneratePlaceholderAtAnywhereButMiddle), ("testGeneratePlaceholderAtBeginning", testGeneratePlaceholderAtBeginning), ("testGeneratePlaceholderAtEnd", testGeneratePlaceholderAtEnd), ("testGeneratePlaceholderAtMiddle", testGeneratePlaceholderAtMiddle), ("testGeneratePlaceholderWhileKeepingRedundantDoc", testGeneratePlaceholderWhileKeepingRedundantDoc), ("testNoPlaceholderNecessary", testNoPlaceholderNecessary), ] } extension ReturnsPlaceholderTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__ReturnsPlaceholderTests = [ ("testGeneratingReturns", testGeneratingReturns), ("testGeneratingReturnsIgnored", testGeneratingReturnsIgnored), ("testGeneratingReturnsNotNecessary", testGeneratingReturnsNotNecessary), ("testNotGeneratingReturns", testNotGeneratingReturns), ] } extension ThrowsPlaceholderTests { // DO NOT MODIFY: This is autogenerated, use: // `swift test --generate-linuxmain` // to regenerate. static let __allTests__ThrowsPlaceholderTests = [ ("testGeneratingThrows", testGeneratingThrows), ("testGeneratingThrowsIgnored", testGeneratingThrowsIgnored), ("testGeneratingThrowsNotNecessary", testGeneratingThrowsNotNecessary), ("testNotGeneratingThrows", testNotGeneratingThrows), ] } public func __allTests() -> [XCTestCaseEntry] { return [ testCase(DocStringDescriptionFormattingTests.__allTests__DocStringDescriptionFormattingTests), testCase(DocStringParameterFormattingTests.__allTests__DocStringParameterFormattingTests), testCase(DocStringReturnsFormattingTests.__allTests__DocStringReturnsFormattingTests), testCase(DocStringSectionSeparationFormattingTests.__allTests__DocStringSectionSeparationFormattingTests), testCase(DocStringSeparatorTests.__allTests__DocStringSeparatorTests), testCase(DocStringThrowsFormattingTests.__allTests__DocStringThrowsFormattingTests), testCase(FormatRangeTests.__allTests__FormatRangeTests), testCase(LineFoldingTests.__allTests__LineFoldingTests), testCase(ParameterPlaceholderTests.__allTests__ParameterPlaceholderTests), testCase(ReturnsPlaceholderTests.__allTests__ReturnsPlaceholderTests), testCase(ThrowsPlaceholderTests.__allTests__ThrowsPlaceholderTests), ] } #endif
59.107692
157
0.798542
af02f028ecaaffad5d1a17df8cab031d7ab1ce30
1,388
kt
Kotlin
common/src/commonMain/kotlin/com.ottamotta.mozoli/dto/Solution.kt
rodionaltshuler/mozolimobile
5a8ef86cf5d1eaa6177d2cdf50705ae1979a4e7b
[ "Apache-2.0" ]
3
2018-11-18T19:44:53.000Z
2018-11-19T15:00:47.000Z
common/src/commonMain/kotlin/com.ottamotta.mozoli/dto/Solution.kt
rodionaltshuler/mozolimobile
5a8ef86cf5d1eaa6177d2cdf50705ae1979a4e7b
[ "Apache-2.0" ]
null
null
null
common/src/commonMain/kotlin/com.ottamotta.mozoli/dto/Solution.kt
rodionaltshuler/mozolimobile
5a8ef86cf5d1eaa6177d2cdf50705ae1979a4e7b
[ "Apache-2.0" ]
null
null
null
package com.ottamotta.mozoli.dto import kotlinx.serialization.Optional import kotlinx.serialization.Serializable import kotlin.jvm.JvmName @Serializable class Solution(var problemId: String? = null) { @Optional var isFlash: Boolean? = false @JvmName("getIsFlash") get() = field @Optional val id: String? = null @Optional var isRedpoint: Boolean? = false @JvmName("getIsRedpoint") get() = field @Optional var attemptsNumber: Int? = null @Optional val points: Int? = null @Optional val userId: String? = null @Optional val solvedDate: String? = null fun solved() = isFlash?:false || isRedpoint?:false override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null || this::class != other::class) return false other as Solution if (id != other.id) return false if (attemptsNumber != other.attemptsNumber) return false if (isFlash != other.isFlash) return false if (isRedpoint != other.isRedpoint) return false return true } override fun hashCode(): Int { var result = id?.hashCode() ?: 0 result = 31 * result + (attemptsNumber ?: 0) result = 31 * result + isFlash.hashCode() result = 31 * result + isRedpoint.hashCode() return result } }
25.703704
70
0.618876
0430c8afa168954f53e8e756ff9e731839dc523e
1,424
java
Java
javaStudy/src/main/java/Test3.java
pysmell/git-practice
083ac4b42dce0ed54988204c51accbf486c2c008
[ "Apache-2.0" ]
null
null
null
javaStudy/src/main/java/Test3.java
pysmell/git-practice
083ac4b42dce0ed54988204c51accbf486c2c008
[ "Apache-2.0" ]
null
null
null
javaStudy/src/main/java/Test3.java
pysmell/git-practice
083ac4b42dce0ed54988204c51accbf486c2c008
[ "Apache-2.0" ]
null
null
null
import java.util.*; public class Test3 { public static void main(String[] args) { Map<String, String> map = new HashMap<>(); for (int i = 0;i < 100;i++) { if (i < 10) { map.put("0" + i, "djasj" + i); } else { map.put(i + "", "ssdsdjasj" + i); } } for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey()); } System.out.println(map instanceof List); Map<String, Map> temp = new HashMap<>(); temp.put("112", new HashMap()); temp.put("113", new HashMap()); List<Map> mapList = new ArrayList<>(); mapList.addAll(temp.values()); System.out.println(mapList); String tempString = "04"; Integer tempInteger = Integer.valueOf(tempString); Boolean b1 = Boolean.valueOf(false); Boolean b2 = Boolean.valueOf(false); Boolean boolean1 = new Boolean(false); Boolean boolean2 = new Boolean(false); System.out.println(b1 == b2); System.out.println(b1.equals(b2)); System.out.println(boolean1 == boolean2); System.out.println(boolean1.equals(boolean2)); StringBuilder stringBuilder = new StringBuilder(); System.out.println(stringBuilder.toString() == null); System.out.println("".equals(stringBuilder.toString())); } }
26.867925
64
0.550562
3a964952950f719117d4c11bbf7d781a73625f1c
2,022
swift
Swift
Pulse/Pulse/Core/Models/DataEngine.swift
tamirarnesty/Pulse
07488624390ed241a3401c7834ce50519ba74fb3
[ "MIT" ]
null
null
null
Pulse/Pulse/Core/Models/DataEngine.swift
tamirarnesty/Pulse
07488624390ed241a3401c7834ce50519ba74fb3
[ "MIT" ]
null
null
null
Pulse/Pulse/Core/Models/DataEngine.swift
tamirarnesty/Pulse
07488624390ed241a3401c7834ce50519ba74fb3
[ "MIT" ]
null
null
null
// // DataEngine.swift // Pulse // // Created by Tamir Arnesty on 2020-03-10. // Copyright © 2020 Tamir Arnesty. All rights reserved. // import Foundation // Shared singleton data instance, holds workouts for now class DataEngine { static let shared: DataEngine = DataEngine() var user: User = User(firstName: "Codie", lastName: "McConkey") var workouts: [Workout] = [] { didSet { self.postHomeWorkoutsChanged() } } var friendsList: [Friend] = [] { didSet { self.postFriendsListChanged() } } var invitedFriends: [Friend] = [] func addWorkout(_ workout: Workout) { workouts.append(workout) user.workouts.append(workout) } func addFriend(_ friend: Friend) { friendsList.append(friend) user.friends.append(friend) } } extension DataEngine { func postHomeWorkoutsChanged() { print("DATA: Workouts changed!") NotificationCenter.default.post(name: .homeChanged, object: self) } func postCalendarChanged() { print("DATA: Calendar changed!") NotificationCenter.default.post(name: .calendarChanged, object: self) } func postProfileChanged() { print("DATA: Profile changed!") NotificationCenter.default.post(name: .profileChanged, object: self) } func postFriendsListChanged() { print("DATA: Profile changed!") NotificationCenter.default.post(name: .friendsListChanged, object: self) } } // MARK: Notification Names extension Notification.Name { static var homeChanged: Notification.Name { Notification.Name("HOME_CHANGED") } static var calendarChanged: Notification.Name { Notification.Name("CALENDAR_CHANGED") } static var profileChanged: Notification.Name { Notification.Name("PROFILE_CHANGED") } static var friendsListChanged: Notification.Name { Notification.Name("PROFILE_CHANGED") } }
25.923077
93
0.637982
dda7a6d52008778db0e516fd494347cc7d80698c
707
php
PHP
app/Http/Controllers/AuthorsController.php
winter666/library
3d18669229f0ccaa1e69c36085c0ba3135d7160e
[ "MIT" ]
null
null
null
app/Http/Controllers/AuthorsController.php
winter666/library
3d18669229f0ccaa1e69c36085c0ba3135d7160e
[ "MIT" ]
1
2021-02-02T19:20:15.000Z
2021-02-02T19:20:15.000Z
app/Http/Controllers/AuthorsController.php
winter666/library
3d18669229f0ccaa1e69c36085c0ba3135d7160e
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Authors; use App\Books; class AuthorsController extends Controller { public function showList () { $authors = Authors::paginate(4); foreach ($authors as $author) { $books[$author->id] = Books::all()->where('author_id', $author->id); } return view('authors.list', compact('authors', 'books')); } public function showDetail ($id) { $author = Authors::find($id); if ($author) { $books = Books::all()->where('author_id', $author->id); return view('authors.detail', compact('author', 'books')); } return redirect('404'); } }
24.37931
80
0.584158
850169a7cbfce6ac778d2d31d29254252b2f058c
2,253
asm
Assembly
programs/oeis/081/A081586.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
1
2021-03-15T11:38:20.000Z
2021-03-15T11:38:20.000Z
programs/oeis/081/A081586.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
programs/oeis/081/A081586.asm
karttu/loda
9c3b0fc57b810302220c044a9d17db733c76a598
[ "Apache-2.0" ]
null
null
null
; A081586: Fourth row of Pascal-(1,3,1) array A081578. ; 1,13,73,245,593,1181,2073,3333,5025,7213,9961,13333,17393,22205,27833,34341,41793,50253,59785,70453,82321,95453,109913,125765,143073,161901,182313,204373,228145,253693,281081,310373,341633,374925,410313,447861,487633,529693,574105,620933,670241,722093,776553,833685,893553,956221,1021753,1090213,1161665,1236173,1313801,1394613,1478673,1566045,1656793,1750981,1848673,1949933,2054825,2163413,2275761,2391933,2511993,2636005,2764033,2896141,3032393,3172853,3317585,3466653,3620121,3778053,3940513,4107565,4279273,4455701,4636913,4822973,5013945,5209893,5410881,5616973,5828233,6044725,6266513,6493661,6726233,6964293,7207905,7457133,7712041,7972693,8239153,8511485,8789753,9074021,9364353,9660813,9963465,10272373,10587601,10909213,11237273,11571845,11912993,12260781,12615273,12976533,13344625,13719613,14101561,14490533,14886593,15289805,15700233,16117941,16542993,16975453,17415385,17862853,18317921,18780653,19251113,19729365,20215473,20709501,21211513,21721573,22239745,22766093,23300681,23843573,24394833,24954525,25522713,26099461,26684833,27278893,27881705,28493333,29113841,29743293,30381753,31029285,31685953,32351821,33026953,33711413,34405265,35108573,35821401,36543813,37275873,38017645,38769193,39530581,40301873,41083133,41874425,42675813,43487361,44309133,45141193,45983605,46836433,47699741,48573593,49458053,50353185,51259053,52175721,53103253,54041713,54991165,55951673,56923301,57906113,58900173,59905545,60922293,61950481,62990173,64041433,65104325,66178913,67265261,68363433,69473493,70595505,71729533,72875641,74033893,75204353,76387085,77582153,78789621,80009553,81242013,82487065,83744773,85015201,86298413,87594473,88903445,90225393,91560381,92908473,94269733,95644225,97032013,98433161,99847733,101275793,102717405,104172633,105641541,107124193,108620653,110130985,111655253,113193521,114745853,116312313,117892965,119487873,121097101,122720713,124358773,126011345,127678493,129360281,131056773,132768033,134494125,136235113,137991061,139762033,141548093,143349305,145165733,146997441,148844493,150706953,152584885,154478353,156387421,158312153,160252613,162208865,164180973 mul $0,2 mov $2,$0 mul $2,2 bin $2,3 mov $3,$2 div $3,4 add $0,$3 mov $1,$0 mul $1,4 add $1,1
160.928571
2,102
0.861074
d1f5c4b32bf9c46ed4d0b9b52265b7b5a6e5aed3
2,848
sql
SQL
scripts/upgrades/1.0.3 to 2.0.0/db-updates/mysql-2011-04-28.sql
bhutchinson/rice
5c2f51ebe21704d3019ae6e3e25d33c1beaeda1c
[ "ECL-2.0" ]
null
null
null
scripts/upgrades/1.0.3 to 2.0.0/db-updates/mysql-2011-04-28.sql
bhutchinson/rice
5c2f51ebe21704d3019ae6e3e25d33c1beaeda1c
[ "ECL-2.0" ]
null
null
null
scripts/upgrades/1.0.3 to 2.0.0/db-updates/mysql-2011-04-28.sql
bhutchinson/rice
5c2f51ebe21704d3019ae6e3e25d33c1beaeda1c
[ "ECL-2.0" ]
1
2021-06-04T01:14:38.000Z
2021-06-04T01:14:38.000Z
-- -- Copyright 2005-2015 The Kuali Foundation -- -- Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php -- -- 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. -- -- -- KULRICE-4794 -- The following statements will change the DOC_HDR_ID from a decimal to a VARCHAR(40) on various tables. -- ALTER TABLE KREW_ACTN_ITM_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) NOT NULL / ALTER TABLE KREW_ACTN_RQST_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) NOT NULL / ALTER TABLE KREW_ACTN_TKN_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) NOT NULL / ALTER TABLE KREW_APP_DOC_STAT_TRAN_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) / ALTER TABLE KREW_DOC_HDR_CNTNT_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) NOT NULL / ALTER TABLE KREW_DOC_HDR_EXT_DT_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) NOT NULL / ALTER TABLE KREW_DOC_HDR_EXT_FLT_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) NOT NULL / ALTER TABLE KREW_DOC_HDR_EXT_LONG_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) NOT NULL / ALTER TABLE KREW_DOC_HDR_EXT_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) NOT NULL / ALTER TABLE KREW_DOC_HDR_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) NOT NULL / ALTER TABLE KREW_DOC_NTE_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) NOT NULL / ALTER TABLE KREW_DOC_TYP_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) / ALTER TABLE KREW_EDL_DMP_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) NOT NULL / ALTER TABLE KREW_EDL_FLD_DMP_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) NOT NULL / ALTER TABLE KREW_INIT_RTE_NODE_INSTN_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) NOT NULL / ALTER TABLE KREW_OUT_BOX_ITM_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) NOT NULL / ALTER TABLE KREW_RMV_RPLC_DOC_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) NOT NULL / ALTER TABLE KREW_RMV_RPLC_GRP_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) NOT NULL / ALTER TABLE KREW_RMV_RPLC_RULE_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) NOT NULL / ALTER TABLE KREW_RTE_NODE_INSTN_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) NOT NULL / ALTER TABLE KREW_RULE_T CHANGE DOC_HDR_ID DOC_HDR_ID VARCHAR(40) / -- -- The following statements will change the ORGN_DOC_ID and DEST_DOC_ID -- from a decimal to a VARCHAR(40) on the KREW_DOC_LNK_T table -- ALTER TABLE KREW_DOC_LNK_T CHANGE ORGN_DOC_ID ORGN_DOC_ID VARCHAR(40) NOT NULL / ALTER TABLE KREW_DOC_LNK_T CHANGE DEST_DOC_ID DEST_DOC_ID VARCHAR(40) NOT NULL
39.013699
107
0.793188
9c43073510d57db26c331a3d3e9a8a0315bf9b79
4,925
js
JavaScript
bitrix/modules/intranet/install/templates/bitrix24/components/bitrix/socialnetwork.group_menu/.default/script.js
BuildingBridge/biznet
0e9e864be99e01bd35f4321a04736866937897b0
[ "Unlicense" ]
null
null
null
bitrix/modules/intranet/install/templates/bitrix24/components/bitrix/socialnetwork.group_menu/.default/script.js
BuildingBridge/biznet
0e9e864be99e01bd35f4321a04736866937897b0
[ "Unlicense" ]
null
null
null
bitrix/modules/intranet/install/templates/bitrix24/components/bitrix/socialnetwork.group_menu/.default/script.js
BuildingBridge/biznet
0e9e864be99e01bd35f4321a04736866937897b0
[ "Unlicense" ]
null
null
null
(function(){ if (!!BX.BXSGM24) { return; } BX.BXSGM24 = { currentUserId: null, groupdId: null, groupType: null, userIsMember: null, userIsAutoMember: null, userRole: null, isProject: null, favoritesValue: null, canInitiate: null, canModify: null, editFeaturesAllowed: true }; BX.BXSGM24.init = function(params) { this.currentUserId = parseInt(params.currentUserId); this.groupId = parseInt(params.groupId); this.groupType = params.groupType; this.userIsMember = !!params.userIsMember; this.userIsAutoMember = !!params.userIsAutoMember; this.userRole = params.userRole; this.isProject = !!params.isProject; this.isOpened = !!params.isOpened; this.favoritesValue = !!params.favoritesValue; this.canInitiate = !!params.canInitiate; this.canModify = !!params.canModify; if (typeof params.urls != 'undefined') { this.urls = params.urls; } this.editFeaturesAllowed = (typeof params.editFeaturesAllowed != 'undefined' ? !!params.editFeaturesAllowed : true); var f = BX.delegate(function(eventData){ if (BX.type.isNotEmptyString(eventData.code)) { if (BX.util.in_array(eventData.code, [ 'afterJoinRequestSend', 'afterEdit' ])) { if (BX('bx-group-menu-join-cont')) { BX('bx-group-menu-join-cont').style.display = "none"; } BX.SocialnetworkUICommon.reload(); } else if (BX.util.in_array(eventData.code, [ 'afterSetFavorites' ])) { var sonetGroupMenu = BX.SocialnetworkUICommon.SonetGroupMenu.getInstance(); var favoritesValue = sonetGroupMenu.favoritesValue; sonetGroupMenu.setItemTitle(!favoritesValue); sonetGroupMenu.favoritesValue = !favoritesValue; } } }, this); BX.addCustomEvent('SidePanel.Slider:onMessage', BX.delegate(function(event) { if (event.getEventId() == 'sonetGroupEvent') { var eventData = event.getData(); f(eventData) } }, this)); BX.addCustomEvent('sonetGroupEvent', f); if (BX('bx-group-menu-join')) { BX.bind(BX('bx-group-menu-join'), 'click', BX.delegate(this.sendJoinRequest, this)); } if (BX('bx-group-menu-settings')) { var sonetGroupMenu = BX.SocialnetworkUICommon.SonetGroupMenu.getInstance(); sonetGroupMenu.favoritesValue = this.favoritesValue; BX.bind(BX('bx-group-menu-settings'), 'click', BX.delegate(function(event) { BX.SocialnetworkUICommon.showGroupMenuPopup({ bindElement: BX.getEventTarget(event), groupId: this.groupId, groupType: this.groupType, userIsMember: this.userIsMember, userIsAutoMember: this.userIsAutoMember, userRole: this.userRole, isProject: this.isProject, isOpened: this.isOpened, editFeaturesAllowed: this.editFeaturesAllowed, perms: { canInitiate: this.canInitiate, canProcessRequestsIn: this.canProcessRequestsIn, canModify: this.canModify }, urls: { requestUser: BX.message('SGMPathToRequestUser'), edit: BX.message('SGMPathToEdit'), delete: BX.message('SGMPathToDelete'), features: BX.message('SGMPathToFeatures'), members: BX.message('SGMPathToMembers'), requests: BX.message('SGMPathToRequests'), requestsOut: BX.message('SGMPathToRequestsOut'), userRequestGroup: BX.message('SGMPathToUserRequestGroup'), userLeaveGroup: BX.message('SGMPathToUserLeaveGroup') } }); event.preventDefault(); }, this)); } BX.addCustomEvent('SidePanel.Slider:onMessage', BX.delegate(function(event){ if (event.getEventId() == 'sonetGroupEvent') { var eventData = event.getData(); if ( BX.type.isNotEmptyString(eventData.code) && typeof eventData.data != 'undefined' && BX.util.in_array(eventData.code, [ 'afterDelete', 'afterLeave' ]) && typeof eventData.data.groupId != 'undefined' && parseInt(eventData.data.groupId) == this.groupId ) { top.location.href = this.urls.groupsList; } } }, this)); }; BX.BXSGM24.sendJoinRequest = function(event) { var button = event.currentTarget; BX.SocialnetworkUICommon.showButtonWait(button); BX.ajax({ url: button.getAttribute('bx-request-url'), method: 'POST', dataType: 'json', data: { groupID: this.groupId, MESSAGE: '', ajax_request: 'Y', save: 'Y', sessid: BX.bitrix_sessid() }, onsuccess: BX.delegate(function(responseData) { BX.SocialnetworkUICommon.hideButtonWait(button); if ( typeof responseData.MESSAGE != 'undefined' && responseData.MESSAGE == 'SUCCESS' && typeof responseData.URL != 'undefined' ) { BX.onCustomEvent(window.top, 'sonetGroupEvent', [ { code: 'afterJoinRequestSend', data: { groupId: this.groupId } } ]); top.location.href = responseData.URL; } }, this), onfailure: BX.delegate(function() { BX.SocialnetworkUICommon.hideButtonWait(button); }, this) }); }; })();
27.982955
118
0.671269
59f60aa01cd7937007d2d9b45939cb3c01a723f3
819
kt
Kotlin
midi-server/src/main/kotlin/fi/ardento/easychords/midiserver/controllers/DeviceController.kt
Joosakur/easy-chords
f87e63af9eac8b8c19990636a0bbaccb4594e042
[ "MIT" ]
1
2021-06-21T12:24:29.000Z
2021-06-21T12:24:29.000Z
midi-server/src/main/kotlin/fi/ardento/easychords/midiserver/controllers/DeviceController.kt
Joosakur/easy-chords
f87e63af9eac8b8c19990636a0bbaccb4594e042
[ "MIT" ]
null
null
null
midi-server/src/main/kotlin/fi/ardento/easychords/midiserver/controllers/DeviceController.kt
Joosakur/easy-chords
f87e63af9eac8b8c19990636a0bbaccb4594e042
[ "MIT" ]
null
null
null
package fi.ardento.easychords.midiserver.controllers import fi.ardento.easychords.midiserver.services.MidiDevice import fi.ardento.easychords.midiserver.services.MidiService import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* @RestController @RequestMapping("/devices") @CrossOrigin(origins = ["http://localhost:3000", "https://easy-chords.io"]) class DeviceController( private val midiService: MidiService ) { @GetMapping fun getDevices(): ResponseEntity<List<MidiDevice>> { return midiService.getDevices().let { ResponseEntity.ok(it) } } @PutMapping fun setDevice( @RequestBody device: MidiDevice ): ResponseEntity<Unit> { midiService.setMidiReceiver(device) return ResponseEntity.noContent().build() } }
29.25
75
0.74359
2c5a67d0f2cf9fd4cfacd5f0567438f78ba53422
467
lua
Lua
learn/sky/testunique.lua
qiuhoude/skynet_learn_dir
ae000c051cc44eb8f858fb5851fca16058b62410
[ "MIT" ]
null
null
null
learn/sky/testunique.lua
qiuhoude/skynet_learn_dir
ae000c051cc44eb8f858fb5851fca16058b62410
[ "MIT" ]
null
null
null
learn/sky/testunique.lua
qiuhoude/skynet_learn_dir
ae000c051cc44eb8f858fb5851fca16058b62410
[ "MIT" ]
null
null
null
local skynet = require "skynet" print("uniqueservice call ..... ") local args = { ... } if(#args == 0) then table.insert(args, "uniqueservice") end skynet.start(function() local us skynet.error("test unique service testunique") if ( #args == 2 and args[1] == "true" ) then us = skynet.uniqueservice(true, args[2]) else us =skynet.uniqueservice(args[1]) end skynet.error("uniqueservice handler:", skynet.address(us)) end)
25.944444
62
0.633833
e8e1a7dd4c0096be6dc41884969338ea14fb0ae3
326
kt
Kotlin
app/src/main/java/com/yyusufsefa/videogamesapp/data/viewstate/GameItemViewState.kt
Yusufsefa/VideoGamesApp
bad61e44d8788584480016528ba307e87af033ce
[ "MIT" ]
2
2021-05-15T11:43:21.000Z
2021-05-16T12:22:49.000Z
app/src/main/java/com/yyusufsefa/videogamesapp/data/viewstate/GameItemViewState.kt
Yusufsefa/VideoGamesApp
bad61e44d8788584480016528ba307e87af033ce
[ "MIT" ]
null
null
null
app/src/main/java/com/yyusufsefa/videogamesapp/data/viewstate/GameItemViewState.kt
Yusufsefa/VideoGamesApp
bad61e44d8788584480016528ba307e87af033ce
[ "MIT" ]
null
null
null
package com.yyusufsefa.videogamesapp.data.viewstate import com.yyusufsefa.videogamesapp.data.model.Game class GameItemViewState(private val game: Game) { fun getName() = game.name.orEmpty() fun getRatingAndReleased() = "${game.rating} - ${game.released}" fun getImageUrl() = game.backgroundImage.orEmpty() }
27.166667
70
0.739264
175f6c3ed6c81e89f9165ec2ced6b2406ecd4331
5,069
html
HTML
html/books/Pro_HTML5_CSS3_Design_Patterns/Chapter17/Layout_Example/example.html
anpham6/squared
375107a2c60bbe15a6b953bddcffe361b106b653
[ "MIT" ]
20
2019-02-24T19:28:00.000Z
2021-10-02T16:38:35.000Z
html/books/Pro_HTML5_CSS3_Design_Patterns/Chapter17/Layout_Example/example.html
anpham6/squared
375107a2c60bbe15a6b953bddcffe361b106b653
[ "MIT" ]
2
2019-05-18T15:13:17.000Z
2019-11-14T02:13:25.000Z
html/books/Pro_HTML5_CSS3_Design_Patterns/Chapter17/Layout_Example/example.html
anpham6/squared
375107a2c60bbe15a6b953bddcffe361b106b653
[ "MIT" ]
4
2019-02-24T19:28:03.000Z
2020-01-06T16:22:37.000Z
<!DOCTYPE html> <html lang="en"> <head> <title>Layout Example</title> <meta charset="utf-8" /> <link rel="stylesheet" href="page.css" media="all" /> <script src="/dist/squared.js"></script> <script src="/dist/squared.base.js"></script> <script src="/dist/android.framework.js"></script> <script src="/common/loader.js"></script> </head> <body> <div id="page"> <div id="preheader"> <p class="part1"><a href="#main">Skip to main content</a></p> <p class="part2">Preheader message </p> </div> <div id="header"><div class="oi"> <div id="title"><h1>Layout Example</h1><div class="float-divider"></div> <div class="menu"> <h3 class="menu-head" >Menu 1</h3> <ul class="dropdown hidden"> <li class="menu-item"><a href="#">menu item</a></li> <li class="menu-item"><a href="#">menu item</a></li> <li class="menu-item"><a href="#">menu item</a></li> <li class="menu-item"><a href="#">menu item</a></li> </ul> </div> <div class="menu"> <h3 class="menu-head" >Menu 2</h3> <ul class="dropdown hidden"> <li class="menu-item"><a href="#">menu item</a></li> <li class="menu-item"><a href="#">menu item</a></li> <li class="menu-item"><a href="#">menu item</a></li> <li class="menu-item"><a href="#">menu item</a></li> </ul> </div> </div> <div id="search"><h3>Search:</h3> <form method="post" action="http://www.tipjar.com/cgi-bin/test"> <input type="text" id="searchtext" name="searchtext" value="" size="32" /> <input type="submit" id="find" name="find" class="button" value="Search" /> </form> <p class="message">Search message</p> </div> <div class="float-divider"></div></div></div> <div id="postheader"> <p class="breadcrumbs"><a href="#">Home</a> » <a href="#">Layouts</a> » Layout Example</p> <p class="sequential"><a href="#">« Previous</a> | <a href="#">Next »</a></p> </div> <div id="body"> <div id="nav"><div class="oi"><h2 class="screenreader-only">Navigation</h2> <div id="site-map" class="rollup section"><h3 class="rollup-trigger">Site Map</h3> <ul class="block"> <li><a href="http://www.cssdesignpatterns.com">cssDesignPatterns</a></li> <li><a href="http://www.apress.com">apress.com</a></li> </ul> <p class="more"><a href="#">» More Links</a></p> </div> <div id="links" class="rollup section"><h3 class="rollup-trigger">Links</h3> <ul class="block"> <li>&middot;&nbsp;<a href="#">Link1</a></li> <li>&middot;&nbsp;<a href="#">Link2</a></li> <li>&middot;&nbsp;<a href="#">Link3</a></li> <li>&middot;&nbsp;<a href="#">Link4</a></li> </ul> <p class="more"><a href="#">» More Products</a></p> </div> </div></div> <div id="main"><div class="oi"><h2 class="screenreader-only">Main</h2> <ul class="tabs"> <li class="selected"><h3 class="tab-label">Product 1</h3> <div id="section1" class="tab-content"><div class="oi2"> <h4>Product 1 Content</h4> <p>This is the message of tab 1. More message... I added more to this message to show how the tab automatically displays scrollbars when it exceeds the height and/or width of the tab container. Most of this text is not shown in the book to save room in the example. Note that Internet Explorer 6 has a bug that requires you to fix the width of this content. Also note that you add margins, border, and padding to the outside-in box rather than the tab so that the tab's scrollbar is located in the proper place. </p></div></div></li> <li><h3 class="tab-label">Product 2</h3> <div id="section2" class="tab-content"><div class="oi2"> <h4>Product 2 Content</h4><p>This is the message of tab 2.</p></div></div></li> <li><h3 class="tab-label">Product 3</h3> <div id="section2" class="tab-content"><div class="oi2"> <h4>Product 3 Content</h4><p>This is the message of tab 3.</p></div></div></li> </ul> <div class="float-divider"></div></div></div> <div id="extras"><div class="oi"><h2 class="screenreader-only">Extras</h2> <div id="news" class="rollup section"><h3 class="rollup-trigger">News</h3> <p>Content: This is a good place for press releases and news.</p> <p class="more"><a href="#">» More News</a></p> </div> <div id="about-us" class="rollup section"><h3 class="rollup-trigger">About us</h3> <p>Content: This is a good place for company information. </p> <p class="more"><a href="#">» More About Us</a></p> </div> </div></div> </div> <div id="footer"> <ul class="inline"> <li><a href="http://www.apress.com">apress.com</a></li> </ul> <p class="copyright">Copyright &copy; 2011 Michael Bowers All rights reserved.</p> </div> </div> </body> </html>
36.731884
549
0.565792
4196b34f3ed984208ae85d19a2f09fe4accf423b
1,781
h
C
Signal/General/dsp/PolnReshape.h
rwharton/dspsr_dsn
135cc86c43931311424beeb5a459ba570f1f83f7
[ "AFL-2.1" ]
null
null
null
Signal/General/dsp/PolnReshape.h
rwharton/dspsr_dsn
135cc86c43931311424beeb5a459ba570f1f83f7
[ "AFL-2.1" ]
null
null
null
Signal/General/dsp/PolnReshape.h
rwharton/dspsr_dsn
135cc86c43931311424beeb5a459ba570f1f83f7
[ "AFL-2.1" ]
null
null
null
//-*-C++-*- /*************************************************************************** * * Copyright (C) 2015 by Matthew Kerr * Licensed under the Academic Free License version 2.1 * ***************************************************************************/ #ifndef __baseband_dsp_PolnReshape_h #define __baseband_dsp_PolnReshape_h #include "dsp/Transformation.h" #include "dsp/TimeSeries.h" // Detection is handled very efficiently on the GPU for 2pol, analytic data. // But other formats may be more useful down the signal path. This // Transformation allows post-detection conversion from 2pol,2dim data to // a variety of formats: // In the 2pol, 2dim case the coherency parameters are packed such that // AA and BB are the 2 dimensions of a sample in the pol=0 stream, and // AB and BA* are the 2 dimensions of a sample in the pol=1 stream. // npol=4, ndim = 1: Coherence / Stokes // npol=2, ndim = 1: PPQQ // npol=1, ndim = 1: Intensity // The transformation performed is determined uniquely by the output state. namespace dsp { //! Convert npol=2,ndim=2 format to variety of other data shapes class PolnReshape : public Transformation<TimeSeries,TimeSeries> { public: //! Default constructor PolnReshape (); //! Apply the npol to single-pol transformation void transformation (); //! Reshape the poln index to keep void set_state ( Signal::State _state) { state = _state; } protected: //! The polarization to keep Signal::State state; //! Handle 2x2 --> 4x1 (Coherence or Stokes) void p2d2_p4d1(); //! Handle 2x2 --> 2x1 (PPQQ) void p2d2_p2d1(); //! Handle 2x2 --> 1x1 (Intensity) void p2d2_p1d1(); //! Handle 1x1 --> 1x1 (Intensity) void p1d1_p1d1(); }; } #endif
25.811594
77
0.62493
d5d9d5408da3e06daba50ab34416d906dc10efb9
550
sql
SQL
Structure.sql
jeschwarz0/MvcWorkspace-Sql
3e5b27bf7229a3fd07819ac80127cd23ded485b2
[ "MIT" ]
null
null
null
Structure.sql
jeschwarz0/MvcWorkspace-Sql
3e5b27bf7229a3fd07819ac80127cd23ded485b2
[ "MIT" ]
null
null
null
Structure.sql
jeschwarz0/MvcWorkspace-Sql
3e5b27bf7229a3fd07819ac80127cd23ded485b2
[ "MIT" ]
null
null
null
-- Create Youtube Channel table CREATE TABLE YoutubeChannel( ChannelID int NOT NULL PRIMARY KEY IDENTITY(1,1), [Name] varchar(128) NOT NULL, Category varchar(128) DEFAULT('Gaming'), ChannelIdentifier varchar(250) NOT NULL ) -- Create Youtube Video table CREATE TABLE YoutubeVideo( VideoID int NOT NULL PRIMARY KEY IDENTITY(1,1), Identifier varchar(100), ChannelID int NOT NULL FOREIGN KEY REFERENCES YoutubeChannel(ChannelID) ) ALTER TABLE YoutubeVideo ADD Title varchar(100); ALTER TABLE YoutubeVideo ALTER COLUMN Identifier varchar(11);
32.352941
72
0.785455
50118aa8fdcc4725778b0623b3f12ca26ac00694
13,180
swift
Swift
Examples/Sudoku/Sudoku/Views/Custom Shapes/PopoverShape.swift
chipjarred/MacMenuBar
9a296a18a3a7d546f86d78bf698343257b2ddb94
[ "MIT" ]
18
2021-03-16T12:58:02.000Z
2022-03-31T05:03:03.000Z
Examples/Sudoku/Sudoku/Views/Custom Shapes/PopoverShape.swift
chipjarred/MacMenuBar
9a296a18a3a7d546f86d78bf698343257b2ddb94
[ "MIT" ]
1
2021-08-03T13:57:49.000Z
2021-08-08T10:56:31.000Z
Examples/Sudoku/Sudoku/Views/Custom Shapes/PopoverShape.swift
chipjarred/MacMenuBar
9a296a18a3a7d546f86d78bf698343257b2ddb94
[ "MIT" ]
2
2021-03-23T10:21:18.000Z
2021-11-04T12:30:08.000Z
// Copyright 2021 Chip Jarred // // 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. import SwiftUI // ------------------------------------- struct PopoverShape: Shape, InsettableShape { /* Interpret arrowSize.height as the arrow's length, the distance it projects outward from the background rectangle. arrowSize.width is the distance along the background rectangle's edge that the arrow occupies */ static let arrowSize = CGSize(width: 36, height: 18) var arrowEdge: Edge var insetDelta: CGFloat = 0 // ------------------------------------- private func backgroundRect(from rect: CGRect) -> CGRect { let arrowLength: CGSize switch arrowEdge { case .leading, .trailing: arrowLength = CGSize(width: Self.arrowSize.height, height: 0) case .top, .bottom: arrowLength = CGSize(width: 0, height: Self.arrowSize.height) } let bgRect = CGRect(origin: rect.origin, size: rect.size - arrowLength) switch arrowEdge { case .top, .leading: return bgRect.translate(by: arrowLength) default: return bgRect } } // ------------------------------------- private func startEndArrorPoints( for rect: CGRect, bgRect: CGRect) -> (startPoint: CGPoint, endPoint: CGPoint, arrowPoint: CGPoint) { let startPoint: CGPoint let endPoint: CGPoint let arrowTipPoint: CGPoint switch arrowEdge { case .leading: startPoint = bgRect.topLeft.midPoint( to: bgRect.bottomLeft ).translate(deltaY: -Self.arrowSize.width / 2) endPoint = bgRect.topLeft.midPoint( to: bgRect.bottomLeft ).translate(deltaY: Self.arrowSize.width / 2) arrowTipPoint = rect.topLeft.midPoint( to: rect.bottomLeft ) case .trailing: startPoint = bgRect.topRight.midPoint( to: bgRect.bottomRight ).translate(deltaY: Self.arrowSize.width / 2) endPoint = bgRect.topRight.midPoint( to: bgRect.bottomRight ).translate(deltaY: -Self.arrowSize.width / 2) arrowTipPoint = rect.topRight.midPoint( to: rect.bottomRight ) case .top: startPoint = bgRect.topLeft.midPoint( to: bgRect.topRight ).translate(deltaX: Self.arrowSize.width / 2) endPoint = bgRect.topLeft.midPoint( to: bgRect.topRight ).translate(deltaX: -Self.arrowSize.width / 2) arrowTipPoint = rect.topLeft.midPoint( to: rect.topRight ) case .bottom: startPoint = bgRect.bottomRight.midPoint( to: bgRect.bottomLeft ).translate(deltaX: -Self.arrowSize.width / 2) endPoint = bgRect.bottomRight.midPoint( to: bgRect.bottomLeft ).translate(deltaX: Self.arrowSize.width / 2) arrowTipPoint = rect.bottomRight.midPoint( to: rect.bottomLeft ) } return (startPoint, endPoint, arrowTipPoint) } // ------------------------------------- private func lineRoundingCorner( from start: CGPoint, to end: CGPoint, around rect: CGRect, in path: inout Path, cornerRadius: CGFloat) -> (newStart: CGPoint, isFinished: Bool) { let hRadius = CGSize(width: cornerRadius, height: 0) let vRadius = CGSize(width: 0, height: cornerRadius) switch end { case rect.topLeft: assert(start.x == end.x, "Not on rectangle edge") assert(start.y > end.y, "Not going clockwise") path.addLine(to: end + vRadius) let p = end + hRadius path.addQuadCurve(to: p, control: end) return (p, false) case rect.topRight: assert(start.y == end.y, "Not on rectangle edge") assert(start.x < end.x, "Not going clockwise") path.addLine(to: end - hRadius) let p = end + vRadius path.addQuadCurve(to: p, control: end) return (p, false) case rect.bottomRight: assert(start.x == end.x, "Not on rectangle edge") assert(start.y < end.y, "Not going clockwise") path.addLine(to: end - vRadius) let p = end - hRadius path.addQuadCurve(to: p, control: end) return (p, false) case rect.bottomLeft: assert(start.y == end.y, "Not on rectangle edge") assert(start.x > end.x, "Not going clockwise") path.addLine(to: end + hRadius) let p = end - vRadius path.addQuadCurve(to: p, control: end) return (p, false) default: break } if end.y == rect.minY { assert(start.y == end.y, "Not on rectangle") assert(start.x < end.x, "Not going clockwise") let p = end - hRadius path.addLine(to: p) return (p, true) } if end.x == rect.maxX { assert(start.x == end.x, "Not on rectangle") assert(start.y < end.y, "Not going clockwise") let p = end - vRadius path.addLine(to: p) return (p, true) } if end.y == rect.maxY { assert(start.y == end.y, "Not on rectangle") assert(start.x > end.x, "Not going clockwise") let p = end + hRadius path.addLine(to: p) return (p, true) } if end.x == rect.minX { assert(start.x == end.x, "Not on rectangle") assert(start.y > end.y, "Not going clockwise") let p = end + vRadius path.addLine(to: p) return (p, true) } fatalError("Not on rectangle edges") } // ------------------------------------- private func mainPath( from startPoint: CGPoint, to endPoint: CGPoint, around rect: CGRect, cornerRadius: CGFloat) -> Path { var path = Path() var curPoint = startPoint path.move(to: curPoint) var finished = false repeat { var nextPoint: CGPoint if curPoint.y == rect.minY { nextPoint = rect.topRight if curPoint != startPoint && nextPoint.y == endPoint.y { nextPoint = endPoint } } else if curPoint.x == rect.maxX { nextPoint = rect.bottomRight if curPoint != startPoint && nextPoint.x == endPoint.x { nextPoint = endPoint } } else if curPoint.y == rect.maxY { nextPoint = rect.bottomLeft if curPoint != startPoint && nextPoint.y == endPoint.y { nextPoint = endPoint } } else if curPoint.x == rect.minX { nextPoint = rect.topLeft if curPoint != startPoint && nextPoint.x == endPoint.x { nextPoint = endPoint } } else { fatalError("Invalid current point for path") } (curPoint, finished) = lineRoundingCorner( from: curPoint, to: nextPoint, around: rect, in: &path, cornerRadius: cornerRadius ) } while !finished return path } // ------------------------------------- private func addArrowPoint( from start: CGPoint, to end: CGPoint, through arrowTip: CGPoint, on rect: CGRect, in path: inout Path, cornerRadius: CGFloat) { let line1 = arrowTip - start let line1Delta = cornerRadius * (line1 / line1.vectorLength) var p11 = start + line1Delta let p12 = arrowTip - line1Delta p11 = p11.midPoint(to: p12) let line2 = end - arrowTip let line2Delta = cornerRadius * (line2 / line2.vectorLength) let p21 = arrowTip + line2Delta var p22 = end - line2Delta p22 = p21.midPoint(to: p22) let hDelta = CGSize(width: cornerRadius, height: 0) let vDelta = CGSize(width: 0, height: cornerRadius) let arrowControl: CGPoint let c1: CGPoint let c2: CGPoint if start.x == rect.minX { c1 = start - vDelta c2 = end + vDelta arrowControl = arrowTip - hDelta / 2 } else if start.y == rect.minY { c1 = start + hDelta c2 = end - hDelta arrowControl = arrowTip - vDelta / 2 } else if start.x == rect.maxX { c1 = start + vDelta c2 = end - vDelta arrowControl = arrowTip + hDelta / 2 } else if start.y == rect.maxY { c1 = start - hDelta c2 = end + hDelta arrowControl = arrowTip + vDelta / 2 } else { fatalError("Unreachable") } path.addQuadCurve(to: p12, control: c1) path.addQuadCurve(to: p21, control: arrowControl) path.addQuadCurve(to: end, control: c2) } // ------------------------------------- public func path(in rect: CGRect) -> Path { let cornerRadius: CGFloat = 6 let bgRect = backgroundRect(from: rect) let (startPoint, endPoint, arrowTipPoint) = startEndArrorPoints( for: rect, bgRect: bgRect ) var path = mainPath( from: startPoint, to: endPoint, around: bgRect, cornerRadius: cornerRadius ) addArrowPoint( from: endPoint, to: startPoint, through: arrowTipPoint, on: bgRect, in: &path, cornerRadius: cornerRadius ) return path } // ------------------------------------- public func inset(by amount: CGFloat) -> some InsettableShape { var newShape = self newShape.insetDelta += amount return newShape } } // ------------------------------------- struct PopoverShape_Previews: PreviewProvider { // ------------------------------------- static var previews: some View { VStack { HStack { PopoverShape(arrowEdge: .leading) .stroke(Color.blue) .frame(width: 100, height: 100) PopoverShape(arrowEdge: .top) .stroke(Color.blue) .frame(width: 100, height: 100) } HStack { PopoverShape(arrowEdge: .trailing) .stroke(Color.blue) .frame(width: 100, height: 100) PopoverShape(arrowEdge: .bottom) .stroke(Color.blue) .frame(width: 100, height: 100) } } } }
32.704715
80
0.487405
6c635d4c7da5fac6b5bb75e2fd89c873970c3d80
1,765
go
Go
migration_test.go
pubkraal/schema
531e542ba48435855be4e3d91b21d1d654b5e53b
[ "MIT" ]
14
2019-09-24T23:26:09.000Z
2022-03-25T23:17:40.000Z
migration_test.go
pubkraal/schema
531e542ba48435855be4e3d91b21d1d654b5e53b
[ "MIT" ]
12
2019-11-16T00:16:59.000Z
2022-03-25T21:43:50.000Z
migration_test.go
pubkraal/schema
531e542ba48435855be4e3d91b21d1d654b5e53b
[ "MIT" ]
5
2019-11-16T03:52:27.000Z
2022-03-14T11:55:34.000Z
package schema import ( "regexp" "testing" ) func TestMD5(t *testing.T) { testMigration := Migration{Script: "test"} expected := "098f6bcd4621d373cade4e832627b4f6" if testMigration.MD5() != expected { t.Errorf("Expected '%s', got '%s'", expected, testMigration.MD5()) } } func TestSortMigrations(t *testing.T) { migrations := []*Migration{ {ID: "2020-01-01"}, {ID: "2021-01-01"}, {ID: "2000-01-01"}, } expectedOrder := []string{"2000-01-01", "2020-01-01", "2021-01-01"} SortMigrations(migrations) for i, migration := range migrations { if migration.ID != expectedOrder[i] { t.Errorf("Expected migration #%d to be %s, got %s", i, expectedOrder[i], migration.ID) } } } func unorderedMigrations() []*Migration { return []*Migration{ { ID: "2021-01-01 002", Script: `CREATE TABLE data_table ( id INTEGER PRIMARY KEY, name VARCHAR(255), created_at TIMESTAMP )`, }, { ID: "2021-01-01 001", Script: "CREATE TABLE first_table (first_name VARCHAR(255), last_name VARCHAR(255))", }, { ID: "2021-01-01 003", Script: `INSERT INTO first_table (first_name, last_name) VALUES ('John', 'Doe')`, }, } } func expectID(t *testing.T, migration *Migration, expectedID string) { t.Helper() if migration.ID != expectedID { t.Errorf("Expected Migration to have ID '%s', got '%s' instead", expectedID, migration.ID) } } func expectScriptMatch(t *testing.T, migration *Migration, regexpString string) { t.Helper() re, err := regexp.Compile(regexpString) if err != nil { t.Fatalf("Invalid regexp: '%s': %s", regexpString, err) } if !re.MatchString(migration.Script) { t.Errorf("Expected migration Script to match '%s', but it did not. Script was:\n%s", regexpString, migration.Script) } }
25.57971
118
0.658357
17e0ac21dcfbf7fb4817896bacdd59af778dd5ea
625
lua
Lua
moonpie/utility/swap_function_spec.lua
tredfern/moonpie
b7b6542007a4acd6ca01c7d36957b10774ba242b
[ "MIT" ]
5
2019-04-16T09:55:57.000Z
2021-01-31T21:50:47.000Z
moonpie/utility/swap_function_spec.lua
tredfern/moonpie
b7b6542007a4acd6ca01c7d36957b10774ba242b
[ "MIT" ]
7
2021-04-26T12:14:05.000Z
2022-02-15T13:26:13.000Z
moonpie/utility/swap_function_spec.lua
tredfern/moonpie
b7b6542007a4acd6ca01c7d36957b10774ba242b
[ "MIT" ]
null
null
null
-- Copyright (c) 2021 Trevor Redfern -- -- This software is released under the MIT License. -- https://opensource.org/licenses/MIT describe("moonpie.utility.swap_function", function() local swapFunction = require "moonpie.utility.swap_function" it("can replace a function in a table", function() local orig = function() end local new = spy.new(function() end) local t = { f = orig } swapFunction(t, "f", new) t.f(1) assert.spy(new).was.called_with(1) t:f() assert.spy(new).was.called_with(t) t.f:revert() assert.equals(orig, t.f) end) end)
24.038462
63
0.6256
2636506d8d5f36bdd71e277175739ff00d954d18
19,061
java
Java
src/main/java/be/ugent/rml/Executor.java
champtc/rmlmapper-java
5915b03ae953e58683f9f91115219a9c7476e807
[ "MIT" ]
null
null
null
src/main/java/be/ugent/rml/Executor.java
champtc/rmlmapper-java
5915b03ae953e58683f9f91115219a9c7476e807
[ "MIT" ]
null
null
null
src/main/java/be/ugent/rml/Executor.java
champtc/rmlmapper-java
5915b03ae953e58683f9f91115219a9c7476e807
[ "MIT" ]
null
null
null
package be.ugent.rml; import be.ugent.rml.functions.FunctionLoader; import be.ugent.rml.functions.MultipleRecordsFunctionExecutor; import be.ugent.rml.metadata.Metadata; import be.ugent.rml.metadata.MetadataGenerator; import be.ugent.rml.records.Record; import be.ugent.rml.records.RecordsFactory; import be.ugent.rml.store.RDF4JStore; import be.ugent.rml.store.SimpleQuadStore; import be.ugent.rml.store.RDF4JStore; import be.ugent.rml.term.ProvenancedQuad; import be.ugent.rml.store.QuadStore; import be.ugent.rml.term.NamedNode; import be.ugent.rml.term.ProvenancedTerm; import be.ugent.rml.term.Term; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.sql.SQLException; import java.util.*; import java.util.function.BiConsumer; public class Executor { private static final Logger logger = LoggerFactory.getLogger(Executor.class); private Initializer initializer; private HashMap<Term, List<Record>> recordsHolders; // this map stores for every Triples Map, which is a Term, a map with the record index and the record's corresponding subject, // which is a ProvenancedTerm. private HashMap<Term, HashMap<Integer, ProvenancedTerm>> subjectCache; private QuadStore resultingQuads; private QuadStore rmlStore; private HashMap<Term, QuadStore> targetStores; private RecordsFactory recordsFactory; private static int blankNodeCounter = 0; private HashMap<Term, Mapping> mappings; private String baseIRI; public Executor(QuadStore rmlStore, RecordsFactory recordsFactory, String baseIRI) throws Exception { this(rmlStore, recordsFactory, null, null, baseIRI); } public Executor(QuadStore rmlStore, RecordsFactory recordsFactory, FunctionLoader functionLoader, String baseIRI) throws Exception { this(rmlStore, recordsFactory, functionLoader, null, baseIRI); } public Executor(QuadStore rmlStore, RecordsFactory recordsFactory, FunctionLoader functionLoader, QuadStore resultingQuads, String baseIRI) throws Exception { this.initializer = new Initializer(rmlStore, functionLoader); this.mappings = this.initializer.getMappings(); this.rmlStore = rmlStore; this.recordsFactory = recordsFactory; this.baseIRI = baseIRI; this.recordsHolders = new HashMap<Term, List<Record>>(); this.subjectCache = new HashMap<Term, HashMap<Integer, ProvenancedTerm>>(); this.targetStores = new HashMap<Term, QuadStore>(); // Default store if no Targets are available for a triple if (resultingQuads == null) { this.resultingQuads = new RDF4JStore(); } else { this.resultingQuads = resultingQuads; } // Output stores for Targets in Term Maps for (Map.Entry<Term, Mapping> tm: this.mappings.entrySet()) { Term triplesMap = tm.getKey(); Mapping mapping = tm.getValue(); Set<Term> targets = new HashSet<Term>(); // Subject Map MappingInfo subjectMapInfo = mapping.getSubjectMappingInfo(); targets.addAll(subjectMapInfo.getTargets()); // Predicate, Object and Language Maps for(PredicateObjectGraphMapping pog: mapping.getPredicateObjectGraphMappings()) { if(pog.getPredicateMappingInfo() != null) { targets.addAll(pog.getPredicateMappingInfo().getTargets()); } if(pog.getObjectMappingInfo() != null) { targets.addAll(pog.getObjectMappingInfo().getTargets()); } } // Graph Map for(MappingInfo g: mapping.getGraphMappingInfos()) { targets.addAll(g.getTargets()); } // Create stores for (Term t: targets) { logger.debug("Adding target for " + t); this.targetStores.put(t, new RDF4JStore()); } } } /* * Backwards compatibility for the V4.X.X releases. * This API will be deprecated in the first V5.X.X release in which this API will change to the new one. */ @Deprecated public QuadStore execute(List<Term> triplesMaps, boolean removeDuplicates, MetadataGenerator metadataGenerator) throws Exception { HashMap<Term, QuadStore> result = this.executeV5(triplesMaps, removeDuplicates, metadataGenerator); return result.get(new NamedNode("rmlmapper://legacy.store")); } @Deprecated public QuadStore executeWithFunction(List<Term> triplesMaps, boolean removeDuplicates, BiConsumer<ProvenancedTerm, PredicateObjectGraph> pogFunction) throws Exception { HashMap<Term, QuadStore> result = this.executeWithFunctionV5(triplesMaps, removeDuplicates, pogFunction); return result.get(new NamedNode("rmlmapper://legacy.store")); } @Deprecated public QuadStore execute(List<Term> triplesMaps) throws Exception { HashMap<Term, QuadStore> result = this.executeV5(triplesMaps, false, null); return result.get(new NamedNode("rmlmapper://legacy.store")); } /* * New public API for the V5.X.X. releases */ public HashMap<Term, QuadStore> executeV5(List<Term> triplesMaps, boolean removeDuplicates, MetadataGenerator metadataGenerator) throws Exception { BiConsumer<ProvenancedTerm, PredicateObjectGraph> pogFunction; if (metadataGenerator != null && metadataGenerator.getDetailLevel().getLevel() >= MetadataGenerator.DETAIL_LEVEL.TRIPLE.getLevel()) { pogFunction = (subject, pog) -> { generateQuad(subject, pog.getPredicate(), pog.getObject(), pog.getGraph()); metadataGenerator.insertQuad(new ProvenancedQuad(subject, pog.getPredicate(), pog.getObject(), pog.getGraph())); }; } else { pogFunction = (subject, pog) -> { generateQuad(subject, pog.getPredicate(), pog.getObject(), pog.getGraph()); }; } return executeWithFunctionV5(triplesMaps, removeDuplicates, pogFunction); } public HashMap<Term, QuadStore> executeWithFunctionV5(List<Term> triplesMaps, boolean removeDuplicates, BiConsumer<ProvenancedTerm, PredicateObjectGraph> pogFunction) throws Exception { //check if TriplesMaps are provided if (triplesMaps == null || triplesMaps.isEmpty()) { triplesMaps = this.initializer.getTriplesMaps(); } //we execute every mapping for (Term triplesMap : triplesMaps) { Mapping mapping = this.mappings.get(triplesMap); List<Record> records = this.getRecords(triplesMap); for (int j = 0; j < records.size(); j++) { Record record = records.get(j); ProvenancedTerm subject = getSubject(triplesMap, mapping, record, j); // If we have subject and it's a named node, // we validate it and make it an absolute IRI if needed. if (subject != null && subject.getTerm() instanceof NamedNode) { String iri = subject.getTerm().getValue(); // Is the IRI valid? if (!Utils.isValidIRI(iri)) { logger.error("The subject \"" + iri + "\" is not a valid IRI. Skipped."); subject = null; // Is the IRI relative? } else if (Utils.isRelativeIRI(iri)) { // Check the base IRI to see if we can use it to turn the IRI into an absolute one. if (this.baseIRI == null) { logger.error("The base IRI is null, so relative IRI of subject cannot be turned in to absolute IRI. Skipped."); subject = null; } else { logger.debug("The IRI of subject is made absolute via base IRI."); iri = this.baseIRI + iri; // Check if the new absolute IRI is valid. if (Utils.isValidIRI(iri)) { subject = new ProvenancedTerm(new NamedNode(iri), subject.getMetadata(), subject.getTargets()); } else { logger.error("The subject \"" + iri + "\" is not a valid IRI. Skipped."); } } } } final ProvenancedTerm finalSubject = subject; //TODO validate subject or check if blank node if (subject != null) { List<ProvenancedTerm> subjectGraphs = new ArrayList<>(); mapping.getGraphMappingInfos().forEach(mappingInfo -> { List<Term> terms = null; try { terms = mappingInfo.getTermGenerator().generate(record); } catch (Exception e) { //todo be more nice and gentle e.printStackTrace(); } terms.forEach(term -> { if (!term.equals(new NamedNode(NAMESPACES.RR + "defaultGraph"))) { subjectGraphs.add(new ProvenancedTerm(term)); } }); }); List<PredicateObjectGraph> pogs = this.generatePredicateObjectGraphs(mapping, record, subjectGraphs); pogs.forEach(pog -> pogFunction.accept(finalSubject, pog)); } } } if (removeDuplicates) { this.resultingQuads.removeDuplicates(); } // Add the legacy store to the list of targets as well this.targetStores.put(new NamedNode("rmlmapper://default.store"), this.resultingQuads); return this.targetStores; } public HashMap<Term, QuadStore> executeV5(List<Term> triplesMaps) throws Exception { return this.executeV5(triplesMaps, false, null); } private List<PredicateObjectGraph> generatePredicateObjectGraphs(Mapping mapping, Record record, List<ProvenancedTerm> alreadyNeededGraphs) throws Exception { ArrayList<PredicateObjectGraph> results = new ArrayList<>(); List<PredicateObjectGraphMapping> predicateObjectGraphMappings = mapping.getPredicateObjectGraphMappings(); for (PredicateObjectGraphMapping pogMapping : predicateObjectGraphMappings) { ArrayList<ProvenancedTerm> predicates = new ArrayList<>(); ArrayList<ProvenancedTerm> poGraphs = new ArrayList<>(); poGraphs.addAll(alreadyNeededGraphs); if (pogMapping.getGraphMappingInfo() != null && pogMapping.getGraphMappingInfo().getTermGenerator() != null) { pogMapping.getGraphMappingInfo().getTermGenerator().generate(record).forEach(term -> { if (!term.equals(new NamedNode(NAMESPACES.RR + "defaultGraph"))) { poGraphs.add(new ProvenancedTerm(term)); } }); } pogMapping.getPredicateMappingInfo().getTermGenerator().generate(record).forEach(p -> { predicates.add(new ProvenancedTerm(p, pogMapping.getPredicateMappingInfo())); }); if (pogMapping.getObjectMappingInfo() != null && pogMapping.getObjectMappingInfo().getTermGenerator() != null) { List<Term> objects = pogMapping.getObjectMappingInfo().getTermGenerator().generate(record); ArrayList<ProvenancedTerm> provenancedObjects = new ArrayList<>(); objects.forEach(object -> { provenancedObjects.add(new ProvenancedTerm(object, pogMapping.getObjectMappingInfo())); }); if (objects.size() > 0) { //add pogs results.addAll(combineMultiplePOGs(predicates, provenancedObjects, poGraphs)); } //check if we are dealing with a parentTriplesMap (RefObjMap) } else if (pogMapping.getParentTriplesMap() != null) { List<ProvenancedTerm> objects; //check if need to apply a join condition if (!pogMapping.getJoinConditions().isEmpty()) { objects = this.getIRIsWithConditions(record, pogMapping.getParentTriplesMap(), pogMapping.getJoinConditions()); //this.generateTriples(subject, po.getPredicateGenerator(), objects, record, combinedGraphs); } else { objects = this.getAllIRIs(pogMapping.getParentTriplesMap()); } results.addAll(combineMultiplePOGs(predicates, objects, poGraphs)); } } return results; } private void generateQuad(ProvenancedTerm subject, ProvenancedTerm predicate, ProvenancedTerm object, ProvenancedTerm graph) { Term g = null; Set<Term> targets = new HashSet<Term>(); if (graph != null) { g = graph.getTerm(); targets.addAll(graph.getTargets()); } if (subject != null && predicate != null && object != null) { // Get all possible targets for triple, the Set guarantees that we don't have duplicates targets.addAll(subject.getTargets()); targets.addAll(predicate.getTargets()); targets.addAll(object.getTargets()); // If we have targets, write to them if (!targets.isEmpty()) { for(Term t: targets) { this.targetStores.get(t).addQuad(subject.getTerm(), predicate.getTerm(), object.getTerm(), g); } } // If not, use the default processor target else { this.resultingQuads.addQuad(subject.getTerm(), predicate.getTerm(), object.getTerm(), g); } } } private List<ProvenancedTerm> getIRIsWithConditions(Record record, Term triplesMap, List<MultipleRecordsFunctionExecutor> conditions) throws Exception { ArrayList<ProvenancedTerm> goodIRIs = new ArrayList<ProvenancedTerm>(); ArrayList<List<ProvenancedTerm>> allIRIs = new ArrayList<List<ProvenancedTerm>>(); for (MultipleRecordsFunctionExecutor condition : conditions) { allIRIs.add(this.getIRIsWithTrueCondition(record, triplesMap, condition)); } if (!allIRIs.isEmpty()) { goodIRIs.addAll(allIRIs.get(0)); for(int i = 1; i < allIRIs.size(); i ++) { List<ProvenancedTerm> list = allIRIs.get(i); for (int j = 0; j < goodIRIs.size(); j ++) { if (!list.contains(goodIRIs.get(j))) { goodIRIs.remove(j); j --; } } } } return goodIRIs; } private List<ProvenancedTerm> getIRIsWithTrueCondition(Record child, Term triplesMap, MultipleRecordsFunctionExecutor condition) throws Exception { Mapping mapping = this.mappings.get(triplesMap); //iterator over all the records corresponding with @triplesMap List<Record> records = this.getRecords(triplesMap); //this array contains all the IRIs that are valid regarding @path and @values ArrayList<ProvenancedTerm> iris = new ArrayList<ProvenancedTerm>(); for (int i = 0; i < records.size(); i++) { Record parent = records.get(i); HashMap<String, Record> recordsMap = new HashMap<>(); recordsMap.put("child", child); recordsMap.put("parent", parent); Object expectedBoolean = condition.execute(recordsMap); if (expectedBoolean instanceof Boolean) { if ((boolean) expectedBoolean) { ProvenancedTerm subject = this.getSubject(triplesMap, mapping, parent, i); iris.add(subject); } } else { logger.warn("The used condition with the Parent Triples Map does not return a boolean."); } } return iris; } private ProvenancedTerm getSubject(Term triplesMap, Mapping mapping, Record record, int i) throws Exception { if (!this.subjectCache.containsKey(triplesMap)) { this.subjectCache.put(triplesMap, new HashMap<Integer, ProvenancedTerm>()); } if (!this.subjectCache.get(triplesMap).containsKey(i)) { List<Term> nodes = mapping.getSubjectMappingInfo().getTermGenerator().generate(record); if (!nodes.isEmpty()) { //todo: only create metadata when it's required Metadata meta = new Metadata(triplesMap, mapping.getSubjectMappingInfo().getTerm()); List<Term> targets = mapping.getSubjectMappingInfo().getTargets(); this.subjectCache.get(triplesMap).put(i, new ProvenancedTerm(nodes.get(0), meta, targets)); } } return this.subjectCache.get(triplesMap).get(i); } private List<ProvenancedTerm> getAllIRIs(Term triplesMap) throws Exception { Mapping mapping = this.mappings.get(triplesMap); List<Record> records = getRecords(triplesMap); ArrayList<ProvenancedTerm> iris = new ArrayList<ProvenancedTerm>(); for (int i = 0; i < records.size(); i++) { Record record = records.get(i); ProvenancedTerm subject = getSubject(triplesMap, mapping, record, i); iris.add(subject); } return iris; } private List<Record> getRecords(Term triplesMap) throws IOException, SQLException, ClassNotFoundException { if (!this.recordsHolders.containsKey(triplesMap)) { this.recordsHolders.put(triplesMap, this.recordsFactory.createRecords(triplesMap, this.rmlStore)); } return this.recordsHolders.get(triplesMap); } public FunctionLoader getFunctionLoader() { return this.initializer.getFunctionLoader(); } private List<PredicateObjectGraph> combineMultiplePOGs(List<ProvenancedTerm> predicates, List<ProvenancedTerm> objects, List<ProvenancedTerm> graphs) { ArrayList<PredicateObjectGraph> results = new ArrayList<>(); if (graphs.isEmpty()) { graphs.add(null); } predicates.forEach(p -> { objects.forEach(o -> { graphs.forEach(g -> { results.add(new PredicateObjectGraph(p, o, g)); }); }); }); return results; } public static String getNewBlankNodeID() { String temp = "" + Executor.blankNodeCounter; Executor.blankNodeCounter++; return temp; } public List<Term> getTriplesMaps() { return initializer.getTriplesMaps(); } }
42.642058
189
0.607733
1253ad30aaf9a53798715e38cacba72d6cb6ef7c
726
kt
Kotlin
app/src/main/java/com/sduduzog/slimlauncher/ui/main/SearchAppFragment.kt
koppen37/slim-launcher
6423107b901bebc13178f2458fea3d554d5f015b
[ "MIT" ]
null
null
null
app/src/main/java/com/sduduzog/slimlauncher/ui/main/SearchAppFragment.kt
koppen37/slim-launcher
6423107b901bebc13178f2458fea3d554d5f015b
[ "MIT" ]
null
null
null
app/src/main/java/com/sduduzog/slimlauncher/ui/main/SearchAppFragment.kt
koppen37/slim-launcher
6423107b901bebc13178f2458fea3d554d5f015b
[ "MIT" ]
null
null
null
package com.sduduzog.slimlauncher.ui.main import android.os.Bundle import com.sduduzog.slimlauncher.data.model.App import com.sduduzog.slimlauncher.ui.options.AddAppFragment import androidx.navigation.Navigation import kotlinx.android.synthetic.main.add_app_fragment.* class SearchAppFragment : AddAppFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel.setShowAllApps(bool = false) } override fun onAppClicked(app: App) { onLaunch(app, getFragmentView()) inputMethodManager.hideSoftInputFromWindow(add_app_fragment_edit_text.windowToken, 0) Navigation.findNavController(add_app_fragment).popBackStack() } }
33
93
0.77686
19e8335beeb8b5b7de556f70fade7be1776c7964
5,143
go
Go
x/stake/msg_test.go
jlandrews/cosmos-sdk
187be1a5df81de1fd71da9053102d3a4868ec979
[ "Apache-2.0" ]
2
2018-06-18T05:31:38.000Z
2018-06-18T05:34:37.000Z
x/stake/msg_test.go
InsChain/inschain-public
ab6b1d12b1f3db1d677ffe51f212f98451d324ba
[ "Apache-2.0" ]
null
null
null
x/stake/msg_test.go
InsChain/inschain-public
ab6b1d12b1f3db1d677ffe51f212f98451d324ba
[ "Apache-2.0" ]
2
2018-06-10T07:31:14.000Z
2018-06-18T10:14:13.000Z
package stake import ( "testing" "github.com/stretchr/testify/assert" sdk "github.com/cosmos/cosmos-sdk/types" crypto "github.com/tendermint/go-crypto" ) var ( coinPos = sdk.Coin{"steak", 1000} coinZero = sdk.Coin{"steak", 0} coinNeg = sdk.Coin{"steak", -10000} coinPosNotAtoms = sdk.Coin{"foo", 10000} coinZeroNotAtoms = sdk.Coin{"foo", 0} coinNegNotAtoms = sdk.Coin{"foo", -10000} ) // test ValidateBasic for MsgDeclareCandidacy func TestMsgDeclareCandidacy(t *testing.T) { tests := []struct { name, moniker, identity, website, details string candidateAddr sdk.Address pubkey crypto.PubKey bond sdk.Coin expectPass bool }{ {"basic good", "a", "b", "c", "d", addrs[0], pks[0], coinPos, true}, {"partial description", "", "", "c", "", addrs[0], pks[0], coinPos, true}, {"empty description", "", "", "", "", addrs[0], pks[0], coinPos, false}, {"empty address", "a", "b", "c", "d", emptyAddr, pks[0], coinPos, false}, {"empty pubkey", "a", "b", "c", "d", addrs[0], emptyPubkey, coinPos, true}, {"empty bond", "a", "b", "c", "d", addrs[0], pks[0], coinZero, false}, {"negative bond", "a", "b", "c", "d", addrs[0], pks[0], coinNeg, false}, {"negative bond", "a", "b", "c", "d", addrs[0], pks[0], coinNeg, false}, {"wrong staking token", "a", "b", "c", "d", addrs[0], pks[0], coinPosNotAtoms, false}, } for _, tc := range tests { description := NewDescription(tc.moniker, tc.identity, tc.website, tc.details) msg := NewMsgDeclareCandidacy(tc.candidateAddr, tc.pubkey, tc.bond, description) if tc.expectPass { assert.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) } else { assert.NotNil(t, msg.ValidateBasic(), "test: %v", tc.name) } } } // test ValidateBasic for MsgEditCandidacy func TestMsgEditCandidacy(t *testing.T) { tests := []struct { name, moniker, identity, website, details string candidateAddr sdk.Address expectPass bool }{ {"basic good", "a", "b", "c", "d", addrs[0], true}, {"partial description", "", "", "c", "", addrs[0], true}, {"empty description", "", "", "", "", addrs[0], false}, {"empty address", "a", "b", "c", "d", emptyAddr, false}, } for _, tc := range tests { description := NewDescription(tc.moniker, tc.identity, tc.website, tc.details) msg := NewMsgEditCandidacy(tc.candidateAddr, description) if tc.expectPass { assert.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) } else { assert.NotNil(t, msg.ValidateBasic(), "test: %v", tc.name) } } } // test ValidateBasic for MsgDelegate func TestMsgDelegate(t *testing.T) { tests := []struct { name string delegatorAddr sdk.Address candidateAddr sdk.Address bond sdk.Coin expectPass bool }{ {"basic good", addrs[0], addrs[1], coinPos, true}, {"self bond", addrs[0], addrs[0], coinPos, true}, {"empty delegator", emptyAddr, addrs[0], coinPos, false}, {"empty candidate", addrs[0], emptyAddr, coinPos, false}, {"empty bond", addrs[0], addrs[1], coinZero, false}, {"negative bond", addrs[0], addrs[1], coinNeg, false}, {"wrong staking token", addrs[0], addrs[1], coinPosNotAtoms, false}, } for _, tc := range tests { msg := NewMsgDelegate(tc.delegatorAddr, tc.candidateAddr, tc.bond) if tc.expectPass { assert.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) } else { assert.NotNil(t, msg.ValidateBasic(), "test: %v", tc.name) } } } // test ValidateBasic for MsgUnbond func TestMsgUnbond(t *testing.T) { tests := []struct { name string delegatorAddr sdk.Address candidateAddr sdk.Address shares string expectPass bool }{ {"max unbond", addrs[0], addrs[1], "MAX", true}, {"decimal unbond", addrs[0], addrs[1], "0.1", true}, {"negative decimal unbond", addrs[0], addrs[1], "-0.1", false}, {"zero unbond", addrs[0], addrs[1], "0.0", false}, {"invalid decimal", addrs[0], addrs[0], "sunny", false}, {"empty delegator", emptyAddr, addrs[0], "0.1", false}, {"empty candidate", addrs[0], emptyAddr, "0.1", false}, } for _, tc := range tests { msg := NewMsgUnbond(tc.delegatorAddr, tc.candidateAddr, tc.shares) if tc.expectPass { assert.Nil(t, msg.ValidateBasic(), "test: %v", tc.name) } else { assert.NotNil(t, msg.ValidateBasic(), "test: %v", tc.name) } } } // TODO introduce with go-amino //func TestSerializeMsg(t *testing.T) { //// make sure all types construct properly //bondAmt := 1234321 //bond := sdk.Coin{Denom: "atom", Amount: int64(bondAmt)} //tests := []struct { //tx sdk.Msg //}{ //{NewMsgDeclareCandidacy(addrs[0], pks[0], bond, Description{})}, //{NewMsgEditCandidacy(addrs[0], Description{})}, //{NewMsgDelegate(addrs[0], addrs[1], bond)}, //{NewMsgUnbond(addrs[0], addrs[1], strconv.Itoa(bondAmt))}, //} //for i, tc := range tests { //var tx sdk.Tx //bs := wire.BinaryBytes(tc.tx) //err := wire.ReadBinaryBytes(bs, &tx) //if assert.NoError(t, err, "%d", i) { //assert.Equal(t, tc.tx, tx, "%d", i) //} //} //}
32.757962
88
0.603733
cb6c4013e75ef6deebc7c647f722bf35505b8982
518
ddl
SQL
Resources/DdlFiles/Tables/Create/SecurityAssessmentProceduresTestReferences.ddl
cloudsTrafton/Vulnerator
51109db23592a24751d8f54e69c0a44dfff699ee
[ "MIT" ]
175
2016-05-16T19:33:12.000Z
2022-03-02T20:41:14.000Z
Resources/DdlFiles/Tables/Create/SecurityAssessmentProceduresTestReferences.ddl
amkuchta/Vulnerator
fb3d7c7019a7a466f049af5a960a85398edb4e8f
[ "MIT" ]
173
2016-05-16T14:38:59.000Z
2022-01-07T16:03:18.000Z
Resources/DdlFiles/Tables/Create/SecurityAssessmentProceduresTestReferences.ddl
cloudsTrafton/Vulnerator
51109db23592a24751d8f54e69c0a44dfff699ee
[ "MIT" ]
73
2016-05-16T19:01:24.000Z
2021-08-04T20:00:23.000Z
CREATE TABLE IF NOT EXISTS SecurityAssessmentProceduresTestReferences ( SecurityAssessmentProcedureTestReference_ID INTEGER PRIMARY KEY, SecurityAssessmentProcedure_ID INTEGER NOT NULL, TestReference_ID INTEGER NOT NULL, UNIQUE (SecurityAssessmentProcedure_ID, TestReference_ID) ON CONFLICT IGNORE, FOREIGN KEY (SecurityAssessmentProcedure_ID) REFERENCES SecurityAssessmentProcedures(SecurityAssessmentProcedure_ID), FOREIGN KEY (TestReference_ID) REFERENCES TestReferences(TestReference_ID) );
64.75
121
0.849421
86605c1ee2af2f2b79583f8c16c841b57da8b612
1,976
go
Go
go/advanced-go/23.go-protobuf/protoc-gen-go-netrpc/netrpc/netrpc.go
wjiec/packages
4ccaf8f717265a1f8a9af533f9a998b935efb32a
[ "MIT" ]
null
null
null
go/advanced-go/23.go-protobuf/protoc-gen-go-netrpc/netrpc/netrpc.go
wjiec/packages
4ccaf8f717265a1f8a9af533f9a998b935efb32a
[ "MIT" ]
1
2016-09-15T07:06:15.000Z
2016-09-15T07:06:15.000Z
go/advanced-go/23.go-protobuf/protoc-gen-go-netrpc/netrpc/netrpc.go
wjiec/packages
4ccaf8f717265a1f8a9af533f9a998b935efb32a
[ "MIT" ]
null
null
null
package netrpc import ( "fmt" "google.golang.org/protobuf/compiler/protogen" ) func GenerateFileContent(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile) { if len(file.Services) > 0 { g.QualifiedGoIdent(protogen.GoIdent{ GoName: "rpc", GoImportPath: "net/rpc", }) for _, srv := range file.Services { genRpcService(srv, g) } } } func genRpcService(srv *protogen.Service, g *protogen.GeneratedFile) { genServiceInterface(srv, g) genServiceClient(srv, g) genServiceDialer(srv, g) } func genServiceInterface(srv *protogen.Service, g *protogen.GeneratedFile) { g.P(fmt.Sprintf("type %s interface {", srv.GoName)) for _, method := range srv.Methods { g.P(fmt.Sprintf("%s(%s, *%s) error", method.GoName, method.Input.Desc.Name(), method.Output.Desc.Name())) } g.P("}") } func genServiceClient(srv *protogen.Service, g *protogen.GeneratedFile) { g.P(fmt.Sprintf("type %sClient struct {", srv.GoName)) g.P("c *rpc.Client") g.P("}") g.P() g.P(fmt.Sprintf("var _ *%sClient = (*%sClient)(nil)", srv.GoName, srv.GoName)) g.P() for _, method := range srv.Methods { g.P(fmt.Sprintf("func (srv *%sClient) %s(in %s, out *%s) error {", srv.GoName, method.GoName, method.Input.Desc.Name(), method.Output.Desc.Name())) g.P(fmt.Sprintf(`return srv.c.Call("%s.%s", in, out)`, srv.GoName, method.GoName)) g.P("}") } g.P() g.P(fmt.Sprintf("func Dial%s(network, address string) (*%sClient, error) {", srv.GoName, srv.GoName)) g.P("c, err := rpc.Dial(network, address)") g.P("if err != nil {") g.P("return nil, err") g.P("}") g.P(fmt.Sprintf("return &%sClient{c: c}, nil", srv.GoName)) g.P("}") } func genServiceDialer(srv *protogen.Service, g *protogen.GeneratedFile) { g.P() g.P(fmt.Sprintf("func Register%s(srv *rpc.Server, v %s) error {", srv.GoName, srv.GoName)) g.P(fmt.Sprintf(`if err := srv.RegisterName("%s", v); err != nil {`, srv.GoName)) g.P("return err") g.P("}") g.P("return nil") g.P("}") }
29.058824
107
0.65081
b5cb35464efeecb770c713ee320e33d0782c52db
579
asm
Assembly
oeis/103/A103453.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/103/A103453.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/103/A103453.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A103453: a(n) = 0^n + 3^n - 1. ; 1,2,8,26,80,242,728,2186,6560,19682,59048,177146,531440,1594322,4782968,14348906,43046720,129140162,387420488,1162261466,3486784400,10460353202,31381059608,94143178826,282429536480,847288609442,2541865828328,7625597484986,22876792454960,68630377364882,205891132094648,617673396283946,1853020188851840,5559060566555522,16677181699666568,50031545098999706,150094635296999120,450283905890997362,1350851717672992088,4052555153018976266,12157665459056928800,36472996377170786402,109418989131512359208 mov $1,3 pow $1,$0 trn $1,2 add $1,1 mov $0,$1
64.333333
497
0.849741
85a2b1a8b17ded882bc0a8e337e96269c2fb8127
402
js
JavaScript
example/web/src/api/order.js
usmbest/ocean.one
362a7da571ee5a9ccb9fa3685a398cf2e705a326
[ "Apache-2.0" ]
175
2018-07-20T14:16:48.000Z
2022-03-04T14:03:21.000Z
example/web/src/api/order.js
fox-one/ocean.one
377db7b8b24b115f49c8a97c8a2d24fd125f5252
[ "Apache-2.0" ]
259
2018-08-10T03:32:05.000Z
2022-03-22T16:35:37.000Z
example/web/src/api/order.js
fox-one/ocean.one
377db7b8b24b115f49c8a97c8a2d24fd125f5252
[ "Apache-2.0" ]
52
2018-08-02T00:52:44.000Z
2022-02-17T18:24:38.000Z
function Order(api) { this.api = api; } Order.prototype = { create: function (callback, params) { this.api.request('POST', '/orders', params, function (resp) { return callback(resp); }); }, cancel: function (callback, id) { this.api.request('POST', '/orders/' + id + '/cancel', undefined, function (resp) { return callback(resp); }); } }; export default Order;
20.1
86
0.599502
e640855b7c21a681039f4787fe7c8448db826484
2,787
go
Go
pkg/cloud/provider.go
zjfqxa/cyclone
8b4fa4bfc4248c067dc1aa25465536f2998f01ec
[ "Apache-2.0" ]
null
null
null
pkg/cloud/provider.go
zjfqxa/cyclone
8b4fa4bfc4248c067dc1aa25465536f2998f01ec
[ "Apache-2.0" ]
null
null
null
pkg/cloud/provider.go
zjfqxa/cyclone
8b4fa4bfc4248c067dc1aa25465536f2998f01ec
[ "Apache-2.0" ]
null
null
null
/* Copyright 2018 caicloud authors. 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. */ package cloud import ( "fmt" "io/ioutil" "time" log "github.com/golang/glog" mgo "gopkg.in/mgo.v2" apiv1 "k8s.io/api/core/v1" "github.com/caicloud/cyclone/cmd/worker/options" "github.com/caicloud/cyclone/pkg/api" "github.com/caicloud/cyclone/pkg/store" ) const ( DefaultCloudPingTimeout = time.Duration(5 * time.Second) WorkerTimeout = time.Duration(2 * time.Hour) DefaultCloudName = "_inCluster" ) var DefaultNamespace = "default" type newCloudFunc func(c *api.Cloud) (Provider, error) var cloudProviderFactory map[api.CloudType]newCloudFunc func init() { cloudProviderFactory = make(map[api.CloudType]newCloudFunc) } func RegistryCloudProvider(ct api.CloudType, ncf newCloudFunc) error { if _, ok := cloudProviderFactory[ct]; ok { return fmt.Errorf("cloud provider %s has been registried", ct) } cloudProviderFactory[ct] = ncf return nil } func InitCloud(autoDiscovery bool) error { ds := store.NewStore() defer ds.Close() _, err := ds.FindCloudByName(DefaultCloudName) if err != nil && err == mgo.ErrNotFound { if autoDiscovery { log.Info("add the default incluster cloud %s", DefaultCloudName) namespace, err := ioutil.ReadFile("/var/run/secrets/kubernetes.io/serviceaccount/" + apiv1.ServiceAccountNamespaceKey) if err != nil { log.Error(err) // error when running cyclone not in a k8s system, e.g. local docker system. //return err } DefaultNamespace = string(namespace) defaultK8sCloud := &api.Cloud{ Name: DefaultCloudName, Type: api.CloudTypeKubernetes, Kubernetes: &api.CloudKubernetes{ InCluster: true, }, } return ds.InsertCloud(defaultK8sCloud) } } return nil } type Provider interface { CanProvision(quota options.Quota) (bool, error) Resource() (*options.Resource, error) Provision(info *api.WorkerInfo, opts *options.WorkerOptions) (*api.WorkerInfo, error) TerminateWorker(string) error Ping() error ListWorkers() ([]api.WorkerInstance, error) } func NewCloudProvider(c *api.Cloud) (Provider, error) { ncf, ok := cloudProviderFactory[c.Type] if !ok { err := fmt.Errorf("cloud type %s is not supported", c.Type) log.Error(err) return nil, err } return ncf(c) }
24.663717
121
0.731252
b087f858c3a89f2a6d53b2a09a0cd0ce8b065762
1,704
rs
Rust
src/main.rs
DanielSchuette/expr_parser
bc531582fe872c3a78e495fd522c80b2111d2131
[ "MIT" ]
null
null
null
src/main.rs
DanielSchuette/expr_parser
bc531582fe872c3a78e495fd522c80b2111d2131
[ "MIT" ]
null
null
null
src/main.rs
DanielSchuette/expr_parser
bc531582fe872c3a78e495fd522c80b2111d2131
[ "MIT" ]
null
null
null
/* * Author: Daniel Schuette * Date: 04/26/2019 * License: MIT * (see LICENSE.md at https://github.com/DanielSchuette/expr_parser) * TODO: correct the mult-div parsing error! */ #![allow(dead_code)] #![allow(unused_imports)] mod draw; mod lexer; mod parser; mod utils; mod vm; use lexer::lex; use parser::parse; use std::process::exit; use utils::{exit_with_err, get_configs}; fn main() { let configs = get_configs(); // if the user provided an expression via `-e', lex & parse and // evaluate it manually; return afterwards if !configs.expression.is_empty() { /* * FIXME: handle errors inbetween lexing and parsing instead of * delegating things to `parse'. This involves calling `exit_with_err' * when appropriate. */ let tokens = lex(&configs.expression); let res = parse(tokens); if let Ok(ast) = res { if configs.is_debug { eprintln!("{}: {:#?}", configs.progname, ast); } if configs.make_graph { utils::draw(&ast, &configs.graph_file, true); } /* let res = vm::evaluate(&ast); // TODO: clean this code up if let Ok(res) = res { eprintln!("{}: Expression result = {}.", configs.progname, res); } else if let Err(e) = res { eprintln!("{}: error: {}", configs.progname, e); } */ } else if let Err(e) = res { exit_with_err(e, &configs.expression, 1); } exit(0); } // delegate IO, lexing & parsing, and evaluation of a resulting AST to the // virtual machine vm::run(&configs); }
26.625
78
0.558685
acbcd8c22ddefa95369c7c56adda4bde75e3cd1d
324
asm
Assembly
test/test.std.outsln.asm
richRemer/atlatl
169c0c9c29d277dc1295e6c37b0963af6e02741a
[ "MIT" ]
null
null
null
test/test.std.outsln.asm
richRemer/atlatl
169c0c9c29d277dc1295e6c37b0963af6e02741a
[ "MIT" ]
null
null
null
test/test.std.outsln.asm
richRemer/atlatl
169c0c9c29d277dc1295e6c37b0963af6e02741a
[ "MIT" ]
null
null
null
global test_case extern std.outsln %include "String.inc" section .text test_case: lea rax, [test_str] ; message call std.outsln ret section .data test_str_data: db "Bar" junk_data: db "junk" test_str: istruc String at String.pdata, dq test_str_data at String.length, dq 3 iend
14.727273
41
0.666667
9e9b32a5c3f0e384dfd7558292b87ffb00a778b3
2,279
rs
Rust
einsteinml-causet-query-pull/src/causetpullbackman.rs
rishabh96b/EinsteinDB
ffda0a8b6dfdf31000e06f1dd921a8088b11e0a9
[ "Apache-2.0" ]
null
null
null
einsteinml-causet-query-pull/src/causetpullbackman.rs
rishabh96b/EinsteinDB
ffda0a8b6dfdf31000e06f1dd921a8088b11e0a9
[ "Apache-2.0" ]
null
null
null
einsteinml-causet-query-pull/src/causetpullbackman.rs
rishabh96b/EinsteinDB
ffda0a8b6dfdf31000e06f1dd921a8088b11e0a9
[ "Apache-2.0" ]
null
null
null
//Copyright 2020 WHTCORPS INC // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. use std::collections::{ BTreeMap, }; use std::collections::btree_map::{ Entry, }; use std::path::{ Path, PathBuf, }; use std::sync::{ Arc, Mutex, RwLock, }; use error::{ StoreError, }; use crate::causetC; lazy_static! { //One open universe. static ref MANIFOLD: RwLock<<Manifold> = RwLock::new(Manifold::new()); } pub struct Manifold { persist: Mutex<BTreeMap<Pathbuf, Arc<RwLock<causetC>>>>, } //Don't open environments directly. impl Manifold { fn new() -> Manifold { Manifold { persist: Default::default(), } } //Now we can handle manifold as an instance of shareable. pub fn turing() -> &'static RwLock<Manifold> { &MANIFOLD } //We leave causet stores to be holographic in that they are pluggable //Berkeley instances with key value stores for every solitondID we //percolate via our Coset Poset of all bundles around a root. pub fn get<'p, P>(&self, path: P) -> Result<Option<Arc<RwLock<causetC>>>, ::std::io::Error> where P: Into<&'p Path>, { let canonical = normalize_path(path)?; //at least one path. //pipeline the environment and handle it as a manifold of manifolds //Ok(self.persist.lock().unwrap().get(&canonical).cloned()) } //If the open persist cell at Path is indeed entangled pub fn get_or_create<'p, F, P>(&mut self, path: P, f :F) -> Result<Arc<RwLock<causetC>>, persistError> where F: FnOnce(&Path) -> Result<causetC, PersistError>, P: Into<&'p Path>, { let canonical = normalize_path(path)?; Ok(math self.) } }
25.897727
106
0.636683
33849b7f7830e776c0c345ea32185fe434695190
225
kt
Kotlin
src/main/kotlin/ContaSalario.kt
oliveira-italo/alura-kotlin-bytebank
31c4fb0b951c9814598d8a7bcc601bb1ce5bb00b
[ "Apache-2.0" ]
null
null
null
src/main/kotlin/ContaSalario.kt
oliveira-italo/alura-kotlin-bytebank
31c4fb0b951c9814598d8a7bcc601bb1ce5bb00b
[ "Apache-2.0" ]
null
null
null
src/main/kotlin/ContaSalario.kt
oliveira-italo/alura-kotlin-bytebank
31c4fb0b951c9814598d8a7bcc601bb1ce5bb00b
[ "Apache-2.0" ]
null
null
null
class ContaSalario( titular: String, numero: Int ) : Conta(titular = titular, numero = numero) { override fun sacar(valor: Double) { if (saldo >= valor) { this.saldo -= valor } } }
20.454545
47
0.546667
85a4c144961aa12bffe95b29e995e63ded33c26b
639
h
C
Classes/zScoringLogic.h
stevewight/BounceZBallz
708803fc1882f281a0816b7333672ef07fced891
[ "Zlib", "MIT" ]
1
2019-07-10T08:58:03.000Z
2019-07-10T08:58:03.000Z
Classes/zScoringLogic.h
stevewight/BounceZBallz
708803fc1882f281a0816b7333672ef07fced891
[ "Zlib", "MIT" ]
null
null
null
Classes/zScoringLogic.h
stevewight/BounceZBallz
708803fc1882f281a0816b7333672ef07fced891
[ "Zlib", "MIT" ]
null
null
null
// // zScoringLogic.h // bounceZballs // // Created by Steve Wight on 2/20/11. // Copyright 2011 __MyCompanyName__. All rights reserved. // #import <Foundation/Foundation.h> @interface zScoringLogic : NSObject { int ballCount; int secondsCount; int totalScore; int levelNumber; } @property(nonatomic,assign)int ballCount; @property(nonatomic,assign)int secondsCount; @property(nonatomic,assign)int totalScore; @property(nonatomic,assign)int levelNumber; -(id) initWithBallCount:(int)bc seconds:(int)s level:(int)l; -(int) findPossiblePoints; -(double) findBallPercent; -(double) findSecondsPercent; -(int) findStarCount; @end
21.3
60
0.758998
f4712de7d25bf0fca1e083ffe359f2c984bfaa77
3,719
go
Go
container_test.go
joushou/qp
45c4de09f88d1631da04fccf8a650bf35d794ece
[ "MIT" ]
11
2015-12-01T11:56:56.000Z
2017-03-28T05:56:01.000Z
container_test.go
kennylevinsen/qp
45c4de09f88d1631da04fccf8a650bf35d794ece
[ "MIT" ]
1
2016-02-05T22:17:35.000Z
2016-02-05T22:17:35.000Z
container_test.go
joushou/qp
45c4de09f88d1631da04fccf8a650bf35d794ece
[ "MIT" ]
2
2016-12-06T20:48:08.000Z
2017-01-06T12:37:57.000Z
package qp import ( "bytes" "io" "testing" "time" ) const reruns = 1000 // ByteReader is a read that only reads a single byte at a time. type ByteReader struct { io.Reader } func (b *ByteReader) Read(p []byte) (int, error) { if len(p) == 0 { return 0, nil } return b.Reader.Read(p[0:1]) } func TestDecoder(t *testing.T) { // Prepare the input inputbuf := new(bytes.Buffer) r := &ByteReader{Reader: inputbuf} // We write the 9P test-set reruns' times to have a decent amount of data. for y := 0; y < reruns; y++ { for _, tt := range MessageTestData { inputbuf.Write(tt.container) } } provided := inputbuf.Len() // Prepare decoder d := Decoder{ Protocol: NineP2000, Reader: r, MessageSize: 1024, } d.Reset() // Run decoder // Time limit donech := make(chan bool, 1) go func() { select { case <-time.After(5 * time.Second): t.Errorf("decoder never terminated: %d bytes read, %d bytes provided", provided-inputbuf.Len(), provided) case <-donech: } }() for y := 0; y < reruns; y++ { for i := range MessageTestData { mtd := MessageTestData[i].input m, err := d.ReadMessage() if err != nil { t.Fatalf("test %dx%d: failed on %T with error: %v", y, i, mtd, err) } if !CompareMarshallables(mtd, m) { t.Errorf("test %dx%d: failed on %T\n\tExpected: %#v\n\tGot: %#v", y, i, mtd, mtd, m) } } } donech <- true if inputbuf.Len() > 0 { t.Errorf("buffer has unread data: %d bytes read, %d bytes provided", provided-inputbuf.Len(), provided) } } func TestDecoderGreedy(t *testing.T) { // Prepare the input inputbuf := new(bytes.Buffer) r := &ByteReader{Reader: inputbuf} // We write the 9P test-set reruns' times to have a decent amount of data. for y := 0; y < reruns; y++ { for _, tt := range MessageTestData { inputbuf.Write(tt.container) } } provided := inputbuf.Len() // Prepare decoder d := Decoder{ Protocol: NineP2000, Reader: r, MessageSize: 1024, Greedy: true, } d.Reset() // Run decoder // Time limit donech := make(chan bool, 1) go func() { select { case <-time.After(5 * time.Second): t.Errorf("decoder never terminated: %d bytes read, %d bytes provided", provided-inputbuf.Len(), provided) case <-donech: } }() for y := 0; y < reruns; y++ { for i := range MessageTestData { mtd := MessageTestData[i].input m, err := d.ReadMessage() if err != nil { t.Fatalf("test %dx%d: failed on %T with error: %v", y, i, mtd, err) } if !CompareMarshallables(mtd, m) { t.Errorf("test %dx%d: failed on %T\n\tExpected: %#v\n\tGot: %#v", y, i, mtd, mtd, m) } } } donech <- true if inputbuf.Len() > 0 { t.Errorf("buffer has unread data: %d bytes read, %d bytes provided", provided-inputbuf.Len(), provided) } } func TestEncoder(t *testing.T) { buf := new(bytes.Buffer) e := Encoder{ Protocol: NineP2000, Writer: buf, MessageSize: 1024, } // We write the 9P test-set reruns' times to have a decent amount of data. for y := 0; y < reruns; y++ { for _, tt := range MessageTestData { err := e.WriteMessage(tt.input) if err != nil { t.Fatalf("unable to write to buffer: %v", err) } } } x := buf.Bytes() for y := 0; y < reruns; y++ { for i, v := range MessageTestData { length := len(v.container) if len(x) < length { t.Fatalf("test %dx%d: not enough data written to read %T: Expected %d, got %d", y, i, v.input, length, len(x)) } segment := x[:length] x = x[length:] if bytes.Compare(segment, v.container) != 0 { t.Errorf("test %dx%d: encoded message did not match reference.\nExpected: %#v\n\tGot: %#v", y, i, v.container, segment) } } } }
21.748538
128
0.606346
2c2fda6dd0d9fcc18f94a2d5bc855b6c733a4e3a
1,704
asm
Assembly
chap18/ex28/adj_vpgatherpd.asm
JamesType/optimization-manual
61cdcebb16e0768a6ab7e85ed535e64e9d8cc31a
[ "0BSD" ]
374
2021-06-08T10:42:01.000Z
2022-03-29T14:21:45.000Z
chap18/ex28/adj_vpgatherpd.asm
JamesType/optimization-manual
61cdcebb16e0768a6ab7e85ed535e64e9d8cc31a
[ "0BSD" ]
1
2021-06-11T20:24:02.000Z
2021-06-11T20:24:02.000Z
chap18/ex28/adj_vpgatherpd.asm
JamesType/optimization-manual
61cdcebb16e0768a6ab7e85ed535e64e9d8cc31a
[ "0BSD" ]
39
2021-06-08T11:25:29.000Z
2022-03-05T05:14:17.000Z
; ; Copyright (C) 2021 by Intel Corporation ; ; Permission to use, copy, modify, and/or distribute this software for any ; purpose with or without fee is hereby granted. ; ; THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH ; REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY ; AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, ; INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM ; LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR ; OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR ; PERFORMANCE OF THIS SOFTWARE. ; ; .globl adj_vpgatherpd ; void adj_vpgatherpd(int64_t len, const int32_t *indices, ; const elem_struct_t *elems, double *out); ; rcx = len ; rdx = indices ; r8 = elems ; r9 = out _RDATA SEGMENT READ ALIGN(32) 'DATA' index_inc DD 0, 8, 16, 24, 0, 8, 16, 24 index_scale DD 32, 32, 32, 32, 32, 32, 32, 32 _RDATA ENDS .code adj_vpgatherpd PROC public sub rsp, 24 vmovaps xmmword ptr[rsp], xmm6 vmovaps ymm0, index_inc vmovaps ymm1, index_scale mov eax, 0f0h kmovd k1, eax mov r10, rdx ; indices xor edx, edx loop1: vpbroadcastd ymm3, DWORD PTR [r10+rdx*4] mov r11d, edx vpbroadcastd xmm2, DWORD PTR [r10+rdx*4+04h] add rdx, 02h vpbroadcastd ymm3{k1}, xmm2 vpmulld ymm4, ymm3, ymm1 vpaddd ymm5, ymm4, ymm0 vpcmpeqb k2, xmm0, xmm0 shl r11d, 02h movsxd r11, r11d vpxord zmm6, zmm6, zmm6 vgatherdpd zmm6{k2}, [r8+ymm5*1] vmovups [r9+r11*8], zmm6 cmp rdx, rcx jl loop1 vzeroupper vmovaps xmm6, xmmword ptr[rsp] add rsp, 24 ret adj_vpgatherpd ENDP end
23.342466
79
0.714202
ff29b6bc197081afc6210a54265ffde07847ff27
817
swift
Swift
ArtistFinder/Combine/InitialPublished.swift
squallone/ArtistFinder
a1d77341d1f6f1d00ec31aff181711704989dc13
[ "MIT" ]
9
2019-09-11T02:09:29.000Z
2020-04-22T07:45:44.000Z
ArtistFinder/Combine/InitialPublished.swift
squallone/ArtistFinder
a1d77341d1f6f1d00ec31aff181711704989dc13
[ "MIT" ]
null
null
null
ArtistFinder/Combine/InitialPublished.swift
squallone/ArtistFinder
a1d77341d1f6f1d00ec31aff181711704989dc13
[ "MIT" ]
2
2019-09-08T23:09:15.000Z
2019-09-11T02:07:29.000Z
// // InitialPublished.swift // ArtistFinder // // Created by Abdiel Soto Barrera (Vendor) on 9/9/19. // Copyright © 2019 iOSDevsMx. All rights reserved. // import UIKit import Combine @propertyWrapper // @propertyDelegate struct InitialPublished<Value>: Publisher { typealias Output = Value typealias Failure = Never private let subject: CurrentValueSubject<Output, Failure> var wrappedValue: Value { get { subject.value } set { subject.send(newValue) } } init(wrappedValue initialValue: Value) { subject = CurrentValueSubject(initialValue) } func receive<S>(subscriber: S) where S : Subscriber, Failure == S.Failure, Value == S.Input { subject.receive(subscriber: subscriber) } }
22.694444
97
0.634027
c7d2b9d5045a980a8f74ddcb22bdfb7a365758fc
455
py
Python
Lista_33.py
Arestideschale/python
5aef01b5fa66b71fa91d0062b703d52731c75fe9
[ "Apache-2.0" ]
1
2022-01-16T17:24:57.000Z
2022-01-16T17:24:57.000Z
Lista_33.py
Arestideschale/python
5aef01b5fa66b71fa91d0062b703d52731c75fe9
[ "Apache-2.0" ]
null
null
null
Lista_33.py
Arestideschale/python
5aef01b5fa66b71fa91d0062b703d52731c75fe9
[ "Apache-2.0" ]
null
null
null
n_temperaturas = int(input("Quantidade de temperaturas que irá digitar: ")) temperaturas = [] n_temperatura = 1 for i in range(n_temperaturas): print("Temperatura n° ", n_temperatura) temperatura = temperaturas.append(float(input("Digite a temperatura: "))) n_temperatura += 1 print("Maior temperatura = ", max(temperaturas)) print("Menor temperatura = ", min(temperaturas)) print("Média = ", round(sum(temperaturas) / len(temperaturas), 2))
37.916667
77
0.723077
5810ea412023541206a32a79dfa84a3cd974f229
103,115
c
C
python/libvncxx/libvnc/src/vnsensor.c
dawonn/vnproglib
a1444675049fef7a327ff9069fbad1560342fd4a
[ "MIT" ]
1
2017-08-23T18:52:21.000Z
2017-08-23T18:52:21.000Z
python/libvncxx/libvnc/src/vnsensor.c
dawonn/vnproglib
a1444675049fef7a327ff9069fbad1560342fd4a
[ "MIT" ]
10
2018-05-30T15:49:45.000Z
2019-06-12T18:20:29.000Z
data_acquisition/ptu/libs/vectornav/libvncxx/libvnc/src/vnsensor.c
HoliestCow/wind_daq
6a8b30ba6b14b3162f2fa3144b52cdf7ed17ec3a
[ "MIT" ]
null
null
null
#include "vnsensor.h" #include "vnerror.h" #include <string.h> #include "vntime.h" #include "vnstring.h" #define DEFAULT_RESPONSE_TIMEOUT_MS 500 #define DEFAULT_RETRANSMIT_DELAY_MS 200 #define DEFAULT_READ_BUFFER_SIZE 256 #define COMMAND_MAX_LENGTH 0x100 void VnSensor_dataReceivedHandler( void *userData); void VnSensor_packetFoundHandler( void *userData, struct VnUartPacket *packet, size_t runningIndex); enum VnError VnSensor_transactionNoFinalize( struct VnSensor *s, char *toSend, size_t toSendLength, bool waitForReply, char *responseBuffer, size_t *responseSize); enum VnError VnSensor_transactionNoFinalizeWithTiming( struct VnSensor *s, char *toSend, size_t toSendLength, bool waitForReply, char *responseBuffer, size_t* responseBufferSize, uint16_t responseTimeoutMs, uint16_t retransmitDelayMs); enum VnError to_string_SENSORERROR( char* out, size_t outSize, enum SENSORERROR val) { switch (val) { case ERR_HARD_FAULT: return strcpy_x(out, outSize, "HardFault"); case ERR_SERIAL_BUFFER_OVERFLOW: return strcpy_x(out, outSize, "SerialBufferOverflow"); case ERR_INVALID_CHECKSUM: return strcpy_x(out, outSize, "InvalidChecksum"); case ERR_INVALID_COMMAND: return strcpy_x(out, outSize, "InvalidCommand"); case ERR_NOT_ENOUGH_PARAMETERS: return strcpy_x(out, outSize, "NotEnoughParameters"); case ERR_TOO_MANY_PARAMETERS: return strcpy_x(out, outSize, "TooManyParameters"); case ERR_INVALID_PARAMETER: return strcpy_x(out, outSize, "InvalidParameter"); case ERR_INVALID_REGISTER: return strcpy_x(out, outSize, "InvalidRegister"); case ERR_UNAUTHORIZED_ACCESS: return strcpy_x(out, outSize, "UnauthorizedAccess"); case ERR_WATCHDOG_RESET: return strcpy_x(out, outSize, "WatchdogReset"); case ERR_OUTPUT_BUFFER_OVERFLOW: return strcpy_x(out, outSize, "OutputBufferOverflow"); case ERR_INSUFFICIENT_BAUD_RATE: return strcpy_x(out, outSize, "InsufficientBaudRate"); case ERR_ERROR_BUFFER_OVERFLOW: return strcpy_x(out, outSize, "ErrorBufferOverflow"); default: return strcpy_x(out, outSize, "Unknown"); } } void BinaryOutputRegister_initialize( struct BinaryOutputRegister *reg, enum ASYNCMODE asyncMode, uint32_t rateDivisor, enum COMMONGROUP commonField, enum TIMEGROUP timeField, enum IMUGROUP imuField, enum GPSGROUP gpsField, enum ATTITUDEGROUP attitudeField, enum INSGROUP insField) { reg->asyncMode = asyncMode; reg->rateDivisor = rateDivisor; reg->commonField = commonField; reg->timeField = timeField; reg->imuField = imuField; reg->gpsField = gpsField; reg->attitudeField = attitudeField; reg->insField = insField; } enum VnError VnSensor_initialize( struct VnSensor *s) { VnSerialPort_initialize(&s->serialPort); s->sendErrorDetectionMode = VNERRORDETECTIONMODE_CHECKSUM; s->responseTimeoutMs = DEFAULT_RESPONSE_TIMEOUT_MS; s->retransmitDelayMs = DEFAULT_RETRANSMIT_DELAY_MS; VnCriticalSection_initialize(&s->transactionCS); s->responseWaitingForProcessing = false; s->waitingForResponse = false; VnEvent_initialize(&s->newResponsesEvent); s->responseLength = 0; s->runningDataIndex = 0; VnUartPacketFinder_initialize(&s->packetFinder); s->asyncPacketFoundHandler = NULL; s->asyncPacketFoundHandlerUserData = NULL; s->errorMessageReceivedHandler = NULL; s->errorMessageReceivedHandlerUserData = NULL; VnUartPacketFinder_registerPacketFoundHandler(&s->packetFinder, VnSensor_packetFoundHandler, s); return E_NONE; } enum VnError VnSensor_connect( struct VnSensor *s, const char *portName, uint32_t baudrate) { enum VnError error; if (VnSensor_isConnected(s)) return E_INVALID_OPERATION; if ((error = VnSerialPort_open_pnbr(&s->serialPort, portName, baudrate)) != E_NONE) return error; VnSerialPort_registerDataReceivedHandler(&s->serialPort, VnSensor_dataReceivedHandler, s); return E_NONE; } enum VnError VnSensor_disconnect( struct VnSensor *s) { enum VnError error; if (!VnSensor_isConnected(s)) return E_INVALID_OPERATION; VnSerialPort_unregisterDataReceivedHandler(&s->serialPort); if ((error = VnSerialPort_close(&s->serialPort)) != E_NONE) return error; return E_NONE; } enum VnError VnSensor_changeBaudrate( struct VnSensor *s, uint32_t baudrate) { enum VnError error; if ((error = VnSensor_writeSerialBaudRate(s, baudrate, true)) != E_NONE) return error; return VnSerialPort_changeBaudrate(&s->serialPort, baudrate); } enum VnError VnSensor_transaction( struct VnSensor *s, char *toSend, size_t toSendLength, char *response, size_t *responseLength) { char buffer[COMMAND_MAX_LENGTH]; size_t finalLength = toSendLength; /* Copy over what was provided. */ memcpy(buffer, toSend, toSendLength); /* Add null termination for string operations below. */ buffer[toSendLength] = '\0'; /* First see if an '*' is present. */ if (strchr(buffer, '*') == NULL) { VnUartPacket_finalizeCommand(s->sendErrorDetectionMode, (uint8_t*)buffer, sizeof(buffer), &finalLength); } else if (buffer[finalLength - 2] != '\r' && buffer[finalLength - 1] != '\n') { buffer[finalLength++] = '\r'; buffer[finalLength++] = '\n'; } return VnSensor_transactionNoFinalize(s, buffer, finalLength, true, response, responseLength); } bool VnSensor_isConnected( struct VnSensor *s) { return VnSerialPort_isOpen(&s->serialPort); } enum VnError VnSensor_writeSettings( struct VnSensor* s, bool waitForReply) { enum VnError error; char toSend[37]; size_t toSendLength; char responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genCmdWriteSettings( (uint8_t*)toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength)) != E_NONE) { return error; } return VnSensor_transactionNoFinalizeWithTiming(s, toSend, toSendLength, waitForReply, responseBuffer, &responseLength, 2500, 1000); } enum VnError VnSensor_restoreFactorySettings( struct VnSensor * s, bool waitForReply) { enum VnError error; char toSend[37]; size_t toSendLength; char responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genCmdRestoreFactorySettings( (uint8_t*)toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength)) != E_NONE) { return error; } return VnSensor_transactionNoFinalizeWithTiming(s, toSend, toSendLength, waitForReply, responseBuffer, &responseLength, 2500, 1000); } enum VnError VnSensor_reset( struct VnSensor* s, bool waitForReply) { enum VnError error; char toSend[37]; size_t toSendLength; char responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genCmdReset( (uint8_t*)toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength)) != E_NONE) { return error; } return VnSensor_transactionNoFinalizeWithTiming(s, toSend, toSendLength, waitForReply, responseBuffer, &responseLength, 2500, 1000); } enum VnError VnSensor_tare( struct VnSensor *s, bool waitForReply) { enum VnError error; char toSend[14]; size_t toSendLength; char responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genCmdTare( (uint8_t*)toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength)) != E_NONE) { return error; } return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, responseBuffer, &responseLength); } enum VnError VnSensor_setGyroBias( struct VnSensor *s, bool waitForReply) { enum VnError error; char toSend[14]; size_t toSendLength; char responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genCmdSetGyroBias( (uint8_t*)toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength)) != E_NONE) { return error; } return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, responseBuffer, &responseLength); } enum VnError VnSensor_magneticDisturbancePresent( struct VnSensor *s, bool disturbancePresent, bool waitForReply) { enum VnError error; char toSend[14]; size_t toSendLength; char responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genCmdKnownMagneticDisturbance( (uint8_t*)toSend, sizeof(toSend), s->sendErrorDetectionMode, disturbancePresent, &toSendLength)) != E_NONE) { return error; } return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, responseBuffer, &responseLength); } enum VnError VnSensor_accelerationDisturbancePresent( struct VnSensor *s, bool disturbancePresent, bool waitForReply) { enum VnError error; char toSend[14]; size_t toSendLength; char responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genCmdKnownAccelerationDisturbance( (uint8_t*)toSend, sizeof(toSend), s->sendErrorDetectionMode, disturbancePresent, &toSendLength)) != E_NONE) { return error; } return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, responseBuffer, &responseLength); } bool VnSensor_verifySensorConnectivity( struct VnSensor *s) { char temp[50]; return VnSensor_readModelNumber(s, temp, sizeof(temp)) == E_NONE; } uint16_t VnSensor_getResponseTimeoutMs( struct VnSensor *s) { return s->responseTimeoutMs; } enum VnError VnSensor_setResponseTimeoutMs( struct VnSensor *s, uint16_t reponseTimeoutMs) { s->responseTimeoutMs = reponseTimeoutMs; return E_NONE; } uint16_t VnSensor_getRetransmitDelayMs( struct VnSensor *s) { return s->retransmitDelayMs; } enum VnError VnSensor_setRetransmitDelayMs( struct VnSensor *s, uint16_t retransmitDelayMs) { s->retransmitDelayMs = retransmitDelayMs; return E_NONE; } enum VnError VnSensor_registerAsyncPacketReceivedHandler( struct VnSensor *s, VnSensor_PacketFoundHandler handler, void *userData) { if (s->asyncPacketFoundHandler != NULL) return E_INVALID_OPERATION; s->asyncPacketFoundHandler = handler; s->asyncPacketFoundHandlerUserData = userData; return E_NONE; } enum VnError VnSensor_unregisterAsyncPacketReceivedHandler( struct VnSensor *s) { if (s->asyncPacketFoundHandler == NULL) return E_INVALID_OPERATION; s->asyncPacketFoundHandler = NULL; s->asyncPacketFoundHandlerUserData = NULL; return E_NONE; } enum VnError VnSensor_registerErrorPacketReceivedHandler( struct VnSensor *s, VnSensor_PacketFoundHandler handler, void *userData) { if (s->errorMessageReceivedHandler != NULL) return E_INVALID_OPERATION; s->errorMessageReceivedHandler = handler; s->errorMessageReceivedHandlerUserData = userData; return E_NONE; } enum VnError VnSensor_unregisterErrorPacketReceivedHandler( struct VnSensor *s) { if (s->errorMessageReceivedHandler == NULL) return E_INVALID_OPERATION; s->errorMessageReceivedHandler = NULL; s->errorMessageReceivedHandlerUserData = NULL; return E_NONE; } void VnSensor_dataReceivedHandler( void *userData) { char readBuffer[DEFAULT_READ_BUFFER_SIZE]; size_t numOfBytesRead = 0; struct VnSensor *s = (struct VnSensor*) userData; VnSerialPort_read(&s->serialPort, readBuffer, sizeof(readBuffer), &numOfBytesRead); if (numOfBytesRead == 0) return; VnUartPacketFinder_processData(&s->packetFinder, (uint8_t*)readBuffer, numOfBytesRead); s->runningDataIndex += numOfBytesRead; } void VnSensor_onErrorPacketReceived( struct VnSensor *s, struct VnUartPacket *packet, size_t runningIndex) { if (s->errorMessageReceivedHandler != NULL) s->errorMessageReceivedHandler(s->errorMessageReceivedHandlerUserData, packet, runningIndex); } void VnSensor_onAsyncPacketReceived( struct VnSensor *s, struct VnUartPacket *packet, size_t runningIndex) { if (s->asyncPacketFoundHandler != NULL) s->asyncPacketFoundHandler(s->asyncPacketFoundHandlerUserData, packet, runningIndex); } void VnSensor_packetFoundHandler( void *userData, struct VnUartPacket *packet, size_t runningIndex) { struct VnSensor *s = (struct VnSensor*) userData; /* Packet should be valid at this point so no need to check its validity. */ if (VnUartPacket_isError(packet)) { if (s->waitingForResponse) { VnCriticalSection_enter(&s->transactionCS); memcpy(s->response, packet->data, packet->length); s->responseLength = packet->length; VnEvent_signal(&s->newResponsesEvent); VnCriticalSection_leave(&s->transactionCS); } VnSensor_onErrorPacketReceived(s, packet, runningIndex); return; } if (VnUartPacket_isResponse(packet)) { if (s->waitingForResponse) { VnCriticalSection_enter(&s->transactionCS); memcpy(s->response, packet->data, packet->length); s->responseLength = packet->length; VnEvent_signal(&s->newResponsesEvent); VnCriticalSection_leave(&s->transactionCS); } return; } /* This wasn't anything else. We assume it is an async packet. */ VnSensor_onAsyncPacketReceived(s, packet, runningIndex); } enum VnError transactionWithWait( struct VnSensor *s, char* toSend, size_t length, uint16_t responseTimeoutMs, uint16_t retransmitDelayMs, char *responseBuffer, size_t *responseLength) { struct VnStopwatch timeoutSw; float curElapsedTime; enum VnError waitResult; /* Make sure we don't have any existing responses. */ VnCriticalSection_enter(&s->transactionCS); s->responseWaitingForProcessing = false; s->waitingForResponse = true; VnCriticalSection_leave(&s->transactionCS); /* Send the command and continue sending if retransmits are enabled until * we receive the response or timeout. */ VnStopwatch_initializeAndStart(&timeoutSw); VnSerialPort_write(&s->serialPort, toSend, length); VnStopwatch_elapsedMs(&timeoutSw, &curElapsedTime); while (true) { bool shouldRetransmit = false; /* Compute how long we should wait for a response before taking more * action. */ float responseWaitTime = responseTimeoutMs - curElapsedTime; if (responseWaitTime > retransmitDelayMs) { responseWaitTime = retransmitDelayMs; shouldRetransmit = true; } /* See if we have time left. */ if (responseWaitTime < 0) { s->waitingForResponse = false; return E_TIMEOUT; } /* Wait for any new responses that come in or until it is time to send * a new retransmit. */ waitResult = VnEvent_waitMs(&s->newResponsesEvent, (uint32_t) responseWaitTime); if (waitResult == E_TIMEOUT) { if (!shouldRetransmit) { s->waitingForResponse = false; return E_TIMEOUT; } } if (waitResult == E_SIGNALED) { /* Get the current collection of responses. */ VnCriticalSection_enter(&s->transactionCS); memcpy(responseBuffer, s->response, s->responseLength); *responseLength = s->responseLength; VnCriticalSection_leave(&s->transactionCS); /* Process the collection of responses we have. */ if (VnUartPacket_isErrorRaw((uint8_t*)responseBuffer)) { uint8_t sensorError; s->waitingForResponse = false; VnUartPacket_parseErrorRaw((uint8_t*)responseBuffer, &sensorError); return (enum VnError) (sensorError + E_SENSOR_HARD_FAULT - 1); } /* We must have a response packet. */ s->waitingForResponse = false; return E_NONE; } /* Retransmit. */ VnSerialPort_write(&s->serialPort, toSend, length); VnStopwatch_elapsedMs(&timeoutSw, &curElapsedTime); } } enum VnError VnSensor_transactionNoFinalizeWithTiming( struct VnSensor *s, char *toSend, size_t toSendLength, bool waitForReply, char *responseBuffer, size_t* responseBufferSize, uint16_t responseTimeoutMs, uint16_t retransmitDelayMs) { if (!VnSensor_isConnected(s)) return E_INVALID_OPERATION; if (waitForReply) { size_t responseLength; return transactionWithWait(s, toSend, toSendLength, responseTimeoutMs, retransmitDelayMs, responseBuffer, &responseLength); } else { VnSerialPort_write(&s->serialPort, toSend, toSendLength); } return E_NONE; } enum VnError VnSensor_transactionNoFinalize( struct VnSensor *s, char *toSend, size_t toSendLength, bool waitForReply, char *responseBuffer, size_t *responseSize) { return VnSensor_transactionNoFinalizeWithTiming( s, toSend, toSendLength, waitForReply, responseBuffer, responseSize, s->responseTimeoutMs, s->retransmitDelayMs); } enum VnError VnSensor_readBinaryOutput1( struct VnSensor *s, struct BinaryOutputRegister *fields) { char toSend[17]; size_t length; enum VnError error; char responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint16_t asyncMode, outputGroup, commonField, timeField, imuField, gpsField, attitudeField, insField; if ((error = VnUartPacket_genReadBinaryOutput1((uint8_t*)toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, responseBuffer, &responseLength)) != E_NONE) return error; VnUartPacket_parseBinaryOutputRaw((uint8_t*)responseBuffer, &asyncMode, &fields->rateDivisor, &outputGroup, &commonField, &timeField, &imuField, &gpsField, &attitudeField, &insField); fields->asyncMode = (enum ASYNCMODE) asyncMode; fields->commonField = (enum COMMONGROUP) commonField; fields->timeField = (enum TIMEGROUP) timeField; fields->imuField = (enum IMUGROUP) imuField; fields->gpsField = (enum GPSGROUP) gpsField; fields->attitudeField = (enum ATTITUDEGROUP) attitudeField; fields->insField = (enum INSGROUP) insField; return E_NONE; } enum VnError VnSensor_writeBinaryOutput1( struct VnSensor *s, struct BinaryOutputRegister *fields, bool waitForReply) { char toSend[256]; size_t length; enum VnError error; char responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteBinaryOutput1((uint8_t*)toSend, sizeof(toSend), s->sendErrorDetectionMode, &length, fields->asyncMode, fields->rateDivisor, fields->commonField, fields->timeField, fields->imuField, fields->gpsField, fields->attitudeField, fields->insField)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, length, waitForReply, responseBuffer, &responseLength); } enum VnError VnSensor_readBinaryOutput2( struct VnSensor *s, struct BinaryOutputRegister *fields) { char toSend[17]; size_t length; enum VnError error; char responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint16_t asyncMode, outputGroup, commonField, timeField, imuField, gpsField, attitudeField, insField; if ((error = VnUartPacket_genReadBinaryOutput2((uint8_t*)toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, responseBuffer, &responseLength)) != E_NONE) return error; VnUartPacket_parseBinaryOutputRaw((uint8_t*)responseBuffer, &asyncMode, &fields->rateDivisor, &outputGroup, &commonField, &timeField, &imuField, &gpsField, &attitudeField, &insField); fields->asyncMode = (enum ASYNCMODE) asyncMode; fields->commonField = (enum COMMONGROUP) commonField; fields->timeField = (enum TIMEGROUP) timeField; fields->imuField = (enum IMUGROUP) imuField; fields->gpsField = (enum GPSGROUP) gpsField; fields->attitudeField = (enum ATTITUDEGROUP) attitudeField; fields->insField = (enum INSGROUP) insField; return E_NONE; } enum VnError VnSensor_writeBinaryOutput2( struct VnSensor *s, struct BinaryOutputRegister *fields, bool waitForReply) { char toSend[256]; size_t length; enum VnError error; char responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteBinaryOutput2((uint8_t*)toSend, sizeof(toSend), s->sendErrorDetectionMode, &length, fields->asyncMode, fields->rateDivisor, fields->commonField, fields->timeField, fields->imuField, fields->gpsField, fields->attitudeField, fields->insField)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, length, waitForReply, responseBuffer, &responseLength); } enum VnError VnSensor_readBinaryOutput3( struct VnSensor *s, struct BinaryOutputRegister *fields) { char toSend[17]; size_t length; enum VnError error; char responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint16_t asyncMode, outputGroup, commonField, timeField, imuField, gpsField, attitudeField, insField; if ((error = VnUartPacket_genReadBinaryOutput3((uint8_t*)toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, responseBuffer, &responseLength)) != E_NONE) return error; VnUartPacket_parseBinaryOutputRaw((uint8_t*)responseBuffer, &asyncMode, &fields->rateDivisor, &outputGroup, &commonField, &timeField, &imuField, &gpsField, &attitudeField, &insField); fields->asyncMode = (enum ASYNCMODE) asyncMode; fields->commonField = (enum COMMONGROUP) commonField; fields->timeField = (enum TIMEGROUP) timeField; fields->imuField = (enum IMUGROUP) imuField; fields->gpsField = (enum GPSGROUP) gpsField; fields->attitudeField = (enum ATTITUDEGROUP) attitudeField; fields->insField = (enum INSGROUP) insField; return E_NONE; } enum VnError VnSensor_writeBinaryOutput3( struct VnSensor *s, struct BinaryOutputRegister *fields, bool waitForReply) { char toSend[256]; size_t length; enum VnError error; char responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteBinaryOutput3((uint8_t*)toSend, sizeof(toSend), s->sendErrorDetectionMode, &length, fields->asyncMode, fields->rateDivisor, fields->commonField, fields->timeField, fields->imuField, fields->gpsField, fields->attitudeField, fields->insField)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, length, waitForReply, responseBuffer, &responseLength); } #if VN_EXTRA enum VnError VnSensor_readBinaryOutput4( struct VnSensor *s, struct BinaryOutputRegister *fields) { char toSend[17]; size_t length; enum VnError error; char responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint16_t asyncMode, outputGroup, commonField, timeField, imuField, gpsField, attitudeField, insField; if ((error = VnUartPacket_genReadBinaryOutput4(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, responseBuffer, &responseLength)) != E_NONE) return error; VnUartPacket_parseBinaryOutputRaw(responseBuffer, &asyncMode, &fields->rateDivisor, &outputGroup, &commonField, &timeField, &imuField, &gpsField, &attitudeField, &insField); fields->asyncMode = (enum AsyncMode) asyncMode; fields->commonField = (enum CommonGroup) commonField; fields->timeField = (enum TimeGroup) timeField; fields->imuField = (enum ImuGroup) imuField; fields->gpsField = (enum GpsGroup) gpsField; fields->attitudeField = (enum AttitudeGroup) attitudeField; fields->insField = (enum InsGroup) insField; return E_NONE; } enum VnError VnSensor_writeBinaryOutput4( struct VnSensor *s, struct BinaryOutputRegister *fields, bool waitForReply) { char toSend[256]; size_t length; enum VnError error; char responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteBinaryOutput4(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length, fields->asyncMode, fields->rateDivisor, fields->commonField, fields->timeField, fields->imuField, fields->gpsField, fields->attitudeField, fields->insField)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, length, waitForReply, responseBuffer, &responseLength); } enum VnError VnSensor_readBinaryOutput5( struct VnSensor *s, struct BinaryOutputRegister *fields) { char toSend[17]; size_t length; enum VnError error; char responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint16_t asyncMode, outputGroup, commonField, timeField, imuField, gpsField, attitudeField, insField; if ((error = VnUartPacket_genReadBinaryOutput5(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, responseBuffer, &responseLength)) != E_NONE) return error; VnUartPacket_parseBinaryOutputRaw(responseBuffer, &asyncMode, &fields->rateDivisor, &outputGroup, &commonField, &timeField, &imuField, &gpsField, &attitudeField, &insField); fields->asyncMode = (enum AsyncMode) asyncMode; fields->commonField = (enum CommonGroup) commonField; fields->timeField = (enum TimeGroup) timeField; fields->imuField = (enum ImuGroup) imuField; fields->gpsField = (enum GpsGroup) gpsField; fields->attitudeField = (enum AttitudeGroup) attitudeField; fields->insField = (enum InsGroup) insField; return E_NONE; } enum VnError VnSensor_writeBinaryOutput5( struct VnSensor *s, struct BinaryOutputRegister *fields, bool waitForReply) { char toSend[256]; size_t length; enum VnError error; char responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteBinaryOutput5(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length, fields->asyncMode, fields->rateDivisor, fields->commonField, fields->timeField, fields->imuField, fields->gpsField, fields->attitudeField, fields->insField)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, length, waitForReply, responseBuffer, &responseLength); } #endif enum VnError VnSensor_readUserTag( struct VnSensor *s, char *tagBuffer, size_t tagBufferLength) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadUserTag(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseUserTag_raw(responseBuffer, sizeof(responseBuffer), tagBuffer, tagBufferLength); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_writeUserTag( struct VnSensor *s, char* tag, bool waitForReply) { enum VnError error; char toSend[37]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteUserTag( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, tag)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readModelNumber( struct VnSensor *s, char *productNameBuffer, size_t productNameBufferLength) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadModelNumber(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseModelNumber_raw(responseBuffer, sizeof(responseBuffer), productNameBuffer, productNameBufferLength); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readHardwareRevision( struct VnSensor *s, uint32_t *revision) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadHardwareRevision(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseHardwareRevision_raw(responseBuffer, sizeof(responseBuffer), revision); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readSerialNumber( struct VnSensor *s, uint32_t *serialNum) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadSerialNumber(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseSerialNumber_raw(responseBuffer, sizeof(responseBuffer), serialNum); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readFirmwareVersion( struct VnSensor *s, char *firmwareVersionBuffer, size_t firmwareVersionBufferLength) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadFirmwareVersion(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseFirmwareVersion_raw(responseBuffer, sizeof(responseBuffer), firmwareVersionBuffer, firmwareVersionBufferLength); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readSerialBaudRate( struct VnSensor *s, uint32_t *baudrate) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadSerialBaudRate(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseSerialBaudRate_raw(responseBuffer, sizeof(responseBuffer), baudrate); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_writeSerialBaudRate( struct VnSensor *s, uint32_t baudrate, bool waitForReply) { enum VnError error; char toSend[25]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteSerialBaudRate( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, baudrate)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readAsyncDataOutputType( struct VnSensor *s, enum VnAsciiAsync *ador) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint32_t adorPlaceholder; if ((error = VnUartPacket_genReadAsyncDataOutputType(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseAsyncDataOutputType_raw(responseBuffer, sizeof(responseBuffer), &adorPlaceholder); if (error != E_NONE) return error; *ador = (enum VnAsciiAsync) adorPlaceholder; return E_NONE; } enum VnError VnSensor_writeAsyncDataOutputType( struct VnSensor *s, enum VnAsciiAsync ador, bool waitForReply) { enum VnError error; char toSend[19]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteAsyncDataOutputType( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, ador)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readAsyncDataOutputFrequency( struct VnSensor *s, uint32_t *adof) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadAsyncDataOutputFrequency(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseAsyncDataOutputFrequency_raw(responseBuffer, sizeof(responseBuffer), adof); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_writeAsyncDataOutputFrequency( struct VnSensor *s, uint32_t adof, bool waitForReply) { enum VnError error; char toSend[26]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteAsyncDataOutputFrequency( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, adof)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readYawPitchRoll( struct VnSensor *s, union vn_vec3f *yawPitchRoll) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadYawPitchRoll(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseYawPitchRoll_raw(responseBuffer, sizeof(responseBuffer), yawPitchRoll); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readAttitudeQuaternion( struct VnSensor *s, union vn_vec4f *quat) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadAttitudeQuaternion(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseAttitudeQuaternion_raw(responseBuffer, sizeof(responseBuffer), quat); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readQuaternionMagneticAccelerationAndAngularRates( struct VnSensor *s, struct QuaternionMagneticAccelerationAndAngularRatesRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadQuaternionMagneticAccelerationAndAngularRates(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseQuaternionMagneticAccelerationAndAngularRates_raw(responseBuffer, sizeof(responseBuffer), &reg->quat, &reg->mag, &reg->accel, &reg->gyro); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readMagneticMeasurements( struct VnSensor *s, union vn_vec3f *mag) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadMagneticMeasurements(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseMagneticMeasurements_raw(responseBuffer, sizeof(responseBuffer), mag); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readAccelerationMeasurements( struct VnSensor *s, union vn_vec3f *accel) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadAccelerationMeasurements(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseAccelerationMeasurements_raw(responseBuffer, sizeof(responseBuffer), accel); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readAngularRateMeasurements( struct VnSensor *s, union vn_vec3f *gyro) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadAngularRateMeasurements(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseAngularRateMeasurements_raw(responseBuffer, sizeof(responseBuffer), gyro); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readMagneticAccelerationAndAngularRates( struct VnSensor *s, struct MagneticAccelerationAndAngularRatesRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadMagneticAccelerationAndAngularRates(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseMagneticAccelerationAndAngularRates_raw(responseBuffer, sizeof(responseBuffer), &reg->mag, &reg->accel, &reg->gyro); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readMagneticAndGravityReferenceVectors( struct VnSensor *s, struct MagneticAndGravityReferenceVectorsRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadMagneticAndGravityReferenceVectors(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseMagneticAndGravityReferenceVectors_raw(responseBuffer, sizeof(responseBuffer), &reg->magRef, &reg->accRef); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_writeMagneticAndGravityReferenceVectors( struct VnSensor *s, struct MagneticAndGravityReferenceVectorsRegister fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteMagneticAndGravityReferenceVectors( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.magRef, fields.accRef)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readMagnetometerCompensation( struct VnSensor *s, struct MagnetometerCompensationRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadMagnetometerCompensation(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseMagnetometerCompensation_raw(responseBuffer, sizeof(responseBuffer), &reg->c, &reg->b); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_writeMagnetometerCompensation( struct VnSensor *s, struct MagnetometerCompensationRegister fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteMagnetometerCompensation( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.c, fields.b)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readAccelerationCompensation( struct VnSensor *s, struct AccelerationCompensationRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadAccelerationCompensation(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseAccelerationCompensation_raw(responseBuffer, sizeof(responseBuffer), &reg->c, &reg->b); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_writeAccelerationCompensation( struct VnSensor *s, struct AccelerationCompensationRegister fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteAccelerationCompensation( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.c, fields.b)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readReferenceFrameRotation( struct VnSensor *s, union vn_mat3f *c) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadReferenceFrameRotation(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseReferenceFrameRotation_raw(responseBuffer, sizeof(responseBuffer), c); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_writeReferenceFrameRotation( struct VnSensor *s, union vn_mat3f c, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteReferenceFrameRotation( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, c)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readYawPitchRollMagneticAccelerationAndAngularRates( struct VnSensor *s, struct YawPitchRollMagneticAccelerationAndAngularRatesRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadYawPitchRollMagneticAccelerationAndAngularRates(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseYawPitchRollMagneticAccelerationAndAngularRates_raw(responseBuffer, sizeof(responseBuffer), &reg->yawPitchRoll, &reg->mag, &reg->accel, &reg->gyro); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readCommunicationProtocolControl( struct VnSensor *s, struct CommunicationProtocolControlRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint8_t serialCountPlaceholder; uint8_t serialStatusPlaceholder; uint8_t spiCountPlaceholder; uint8_t spiStatusPlaceholder; uint8_t serialChecksumPlaceholder; uint8_t spiChecksumPlaceholder; uint8_t errorModePlaceholder; if ((error = VnUartPacket_genReadCommunicationProtocolControl(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseCommunicationProtocolControl_raw(responseBuffer, sizeof(responseBuffer), &serialCountPlaceholder, &serialStatusPlaceholder, &spiCountPlaceholder, &spiStatusPlaceholder, &serialChecksumPlaceholder, &spiChecksumPlaceholder, &errorModePlaceholder); if (error != E_NONE) return error; reg->serialCount = (enum VnCountMode) serialCountPlaceholder; reg->serialStatus = (enum VnStatusMode) serialStatusPlaceholder; reg->spiCount = (enum VnCountMode) spiCountPlaceholder; reg->spiStatus = (enum VnStatusMode) spiStatusPlaceholder; reg->serialChecksum = (enum VnChecksumMode) serialChecksumPlaceholder; reg->spiChecksum = (enum VnChecksumMode) spiChecksumPlaceholder; reg->errorMode = (enum VnErrorMode) errorModePlaceholder; return E_NONE; } enum VnError VnSensor_writeCommunicationProtocolControl( struct VnSensor *s, struct CommunicationProtocolControlRegister fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteCommunicationProtocolControl( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.serialCount, fields.serialStatus, fields.spiCount, fields.spiStatus, fields.serialChecksum, fields.spiChecksum, fields.errorMode)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readSynchronizationControl( struct VnSensor *s, struct SynchronizationControlRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint8_t syncInModePlaceholder; uint8_t syncInEdgePlaceholder; uint32_t reserved1Placeholder; uint8_t syncOutModePlaceholder; uint8_t syncOutPolarityPlaceholder; uint32_t reserved2Placeholder; if ((error = VnUartPacket_genReadSynchronizationControl(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseSynchronizationControl_raw(responseBuffer, sizeof(responseBuffer), &syncInModePlaceholder, &syncInEdgePlaceholder, &reg->syncInSkipFactor, &reserved1Placeholder, &syncOutModePlaceholder, &syncOutPolarityPlaceholder, &reg->syncOutSkipFactor, &reg->syncOutPulseWidth, &reserved2Placeholder); if (error != E_NONE) return error; reg->syncInMode = (enum VnSyncInMode) syncInModePlaceholder; reg->syncInEdge = (enum VnSyncInEdge) syncInEdgePlaceholder; reg->syncOutMode = (enum VnSyncOutMode) syncOutModePlaceholder; reg->syncOutPolarity = (enum VnSyncOutPolarity) syncOutPolarityPlaceholder; return E_NONE; } enum VnError VnSensor_writeSynchronizationControl( struct VnSensor *s, struct SynchronizationControlRegister fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteSynchronizationControl( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.syncInMode, fields.syncInEdge, fields.syncInSkipFactor, 0, fields.syncOutMode, fields.syncOutPolarity, fields.syncOutSkipFactor, fields.syncOutPulseWidth, 0)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readSynchronizationStatus( struct VnSensor *s, struct SynchronizationStatusRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadSynchronizationStatus(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseSynchronizationStatus_raw(responseBuffer, sizeof(responseBuffer), &reg->syncInCount, &reg->syncInTime, &reg->syncOutCount); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_writeSynchronizationStatus( struct VnSensor *s, struct SynchronizationStatusRegister fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteSynchronizationStatus( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.syncInCount, fields.syncInTime, fields.syncOutCount)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readVpeBasicControl( struct VnSensor *s, struct VpeBasicControlRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint8_t enablePlaceholder; uint8_t headingModePlaceholder; uint8_t filteringModePlaceholder; uint8_t tuningModePlaceholder; if ((error = VnUartPacket_genReadVpeBasicControl(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseVpeBasicControl_raw(responseBuffer, sizeof(responseBuffer), &enablePlaceholder, &headingModePlaceholder, &filteringModePlaceholder, &tuningModePlaceholder); if (error != E_NONE) return error; reg->enable = (enum VnVpeEnable) enablePlaceholder; reg->headingMode = (enum VnHeadingMode) headingModePlaceholder; reg->filteringMode = (enum VnVpeMode) filteringModePlaceholder; reg->tuningMode = (enum VnVpeMode) tuningModePlaceholder; return E_NONE; } enum VnError VnSensor_writeVpeBasicControl( struct VnSensor *s, struct VpeBasicControlRegister fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteVpeBasicControl( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.enable, fields.headingMode, fields.filteringMode, fields.tuningMode)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readVpeMagnetometerBasicTuning( struct VnSensor *s, struct VpeMagnetometerBasicTuningRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadVpeMagnetometerBasicTuning(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseVpeMagnetometerBasicTuning_raw(responseBuffer, sizeof(responseBuffer), &reg->baseTuning, &reg->adaptiveTuning, &reg->adaptiveFiltering); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_writeVpeMagnetometerBasicTuning( struct VnSensor *s, struct VpeMagnetometerBasicTuningRegister fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteVpeMagnetometerBasicTuning( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.baseTuning, fields.adaptiveTuning, fields.adaptiveFiltering)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readVpeAccelerometerBasicTuning( struct VnSensor *s, struct VpeAccelerometerBasicTuningRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadVpeAccelerometerBasicTuning(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseVpeAccelerometerBasicTuning_raw(responseBuffer, sizeof(responseBuffer), &reg->baseTuning, &reg->adaptiveTuning, &reg->adaptiveFiltering); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_writeVpeAccelerometerBasicTuning( struct VnSensor *s, struct VpeAccelerometerBasicTuningRegister fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteVpeAccelerometerBasicTuning( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.baseTuning, fields.adaptiveTuning, fields.adaptiveFiltering)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readMagnetometerCalibrationControl( struct VnSensor *s, struct MagnetometerCalibrationControlRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint8_t hsiModePlaceholder; uint8_t hsiOutputPlaceholder; if ((error = VnUartPacket_genReadMagnetometerCalibrationControl(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseMagnetometerCalibrationControl_raw(responseBuffer, sizeof(responseBuffer), &hsiModePlaceholder, &hsiOutputPlaceholder, &reg->convergeRate); if (error != E_NONE) return error; reg->hsiMode = (enum VnHsiMode) hsiModePlaceholder; reg->hsiOutput = (enum VnHsiOutput) hsiOutputPlaceholder; return E_NONE; } enum VnError VnSensor_writeMagnetometerCalibrationControl( struct VnSensor *s, struct MagnetometerCalibrationControlRegister fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteMagnetometerCalibrationControl( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.hsiMode, fields.hsiOutput, fields.convergeRate)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readCalculatedMagnetometerCalibration( struct VnSensor *s, struct CalculatedMagnetometerCalibrationRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadCalculatedMagnetometerCalibration(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseCalculatedMagnetometerCalibration_raw(responseBuffer, sizeof(responseBuffer), &reg->c, &reg->b); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readVelocityCompensationMeasurement( struct VnSensor *s, union vn_vec3f *velocity) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadVelocityCompensationMeasurement(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseVelocityCompensationMeasurement_raw(responseBuffer, sizeof(responseBuffer), velocity); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_writeVelocityCompensationMeasurement( struct VnSensor *s, union vn_vec3f velocity, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteVelocityCompensationMeasurement( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, velocity)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readVelocityCompensationControl( struct VnSensor *s, struct VelocityCompensationControlRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint8_t modePlaceholder; if ((error = VnUartPacket_genReadVelocityCompensationControl(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseVelocityCompensationControl_raw(responseBuffer, sizeof(responseBuffer), &modePlaceholder, &reg->velocityTuning, &reg->rateTuning); if (error != E_NONE) return error; reg->mode = (enum VnVelocityCompensationMode) modePlaceholder; return E_NONE; } enum VnError VnSensor_writeVelocityCompensationControl( struct VnSensor *s, struct VelocityCompensationControlRegister fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteVelocityCompensationControl( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.mode, fields.velocityTuning, fields.rateTuning)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readImuMeasurements( struct VnSensor *s, struct ImuMeasurementsRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadImuMeasurements(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseImuMeasurements_raw(responseBuffer, sizeof(responseBuffer), &reg->mag, &reg->accel, &reg->gyro, &reg->temp, &reg->pressure); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readGpsConfiguration( struct VnSensor *s, struct GpsConfigurationRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint8_t modePlaceholder; uint8_t ppsSourcePlaceholder; uint8_t reserved1Placeholder; uint8_t reserved2Placeholder; uint8_t reserved3Placeholder; if ((error = VnUartPacket_genReadGpsConfiguration(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseGpsConfiguration_raw(responseBuffer, sizeof(responseBuffer), &modePlaceholder, &ppsSourcePlaceholder, &reserved1Placeholder, &reserved2Placeholder, &reserved3Placeholder); if (error != E_NONE) return error; reg->mode = (enum VnGpsMode) modePlaceholder; reg->ppsSource = (enum VnPpsSource) ppsSourcePlaceholder; return E_NONE; } enum VnError VnSensor_writeGpsConfiguration( struct VnSensor *s, struct GpsConfigurationRegister fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteGpsConfiguration( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.mode, fields.ppsSource, 5, 0, 0)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readGpsAntennaOffset( struct VnSensor *s, union vn_vec3f *position) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadGpsAntennaOffset(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseGpsAntennaOffset_raw(responseBuffer, sizeof(responseBuffer), position); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_writeGpsAntennaOffset( struct VnSensor *s, union vn_vec3f position, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteGpsAntennaOffset( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, position)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readGpsSolutionLla( struct VnSensor *s, struct GpsSolutionLlaRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint8_t gpsFixPlaceholder; if ((error = VnUartPacket_genReadGpsSolutionLla(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseGpsSolutionLla_raw(responseBuffer, sizeof(responseBuffer), &reg->time, &reg->week, &gpsFixPlaceholder, &reg->numSats, &reg->lla, &reg->nedVel, &reg->nedAcc, &reg->speedAcc, &reg->timeAcc); if (error != E_NONE) return error; reg->gpsFix = (enum VnGpsFix) gpsFixPlaceholder; return E_NONE; } enum VnError VnSensor_readGpsSolutionEcef( struct VnSensor *s, struct GpsSolutionEcefRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint8_t gpsFixPlaceholder; if ((error = VnUartPacket_genReadGpsSolutionEcef(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseGpsSolutionEcef_raw(responseBuffer, sizeof(responseBuffer), &reg->tow, &reg->week, &gpsFixPlaceholder, &reg->numSats, &reg->position, &reg->velocity, &reg->posAcc, &reg->speedAcc, &reg->timeAcc); if (error != E_NONE) return error; reg->gpsFix = (enum VnGpsFix) gpsFixPlaceholder; return E_NONE; } enum VnError VnSensor_readInsSolutionLla( struct VnSensor *s, struct InsSolutionLlaRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadInsSolutionLla(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseInsSolutionLla_raw(responseBuffer, sizeof(responseBuffer), &reg->time, &reg->week, &reg->status, &reg->yawPitchRoll, &reg->position, &reg->nedVel, &reg->attUncertainty, &reg->posUncertainty, &reg->velUncertainty); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readInsSolutionEcef( struct VnSensor *s, struct InsSolutionEcefRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadInsSolutionEcef(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseInsSolutionEcef_raw(responseBuffer, sizeof(responseBuffer), &reg->time, &reg->week, &reg->status, &reg->yawPitchRoll, &reg->position, &reg->velocity, &reg->attUncertainty, &reg->posUncertainty, &reg->velUncertainty); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readInsBasicConfigurationVn200( struct VnSensor *s, struct InsBasicConfigurationRegisterVn200 *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint8_t scenarioPlaceholder; uint8_t resv1Placeholder; uint8_t resv2Placeholder; if ((error = VnUartPacket_genReadInsBasicConfiguration(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseInsBasicConfiguration_raw(responseBuffer, sizeof(responseBuffer), &scenarioPlaceholder, &reg->ahrsAiding, &resv1Placeholder, &resv2Placeholder); if (error != E_NONE) return error; reg->scenario = (enum VnScenario) scenarioPlaceholder; return E_NONE; } enum VnError VnSensor_writeInsBasicConfigurationVn200( struct VnSensor *s, struct InsBasicConfigurationRegisterVn200 fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteInsBasicConfiguration( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.scenario, fields.ahrsAiding, 0, 0)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readInsBasicConfigurationVn300( struct VnSensor *s, struct InsBasicConfigurationRegisterVn300 *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint8_t scenarioPlaceholder; uint8_t resv2Placeholder; if ((error = VnUartPacket_genReadInsBasicConfiguration(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseInsBasicConfiguration_raw(responseBuffer, sizeof(responseBuffer), &scenarioPlaceholder, &reg->ahrsAiding, &reg->estBaseline, &resv2Placeholder); if (error != E_NONE) return error; reg->scenario = (enum VnScenario) scenarioPlaceholder; return E_NONE; } enum VnError VnSensor_writeInsBasicConfigurationVn300( struct VnSensor *s, struct InsBasicConfigurationRegisterVn300 fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteInsBasicConfiguration( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.scenario, fields.ahrsAiding, fields.estBaseline, 0)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readInsStateLla( struct VnSensor *s, struct InsStateLlaRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadInsStateLla(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseInsStateLla_raw(responseBuffer, sizeof(responseBuffer), &reg->yawPitchRoll, &reg->position, &reg->velocity, &reg->accel, &reg->angularRate); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readInsStateEcef( struct VnSensor *s, struct InsStateEcefRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadInsStateEcef(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseInsStateEcef_raw(responseBuffer, sizeof(responseBuffer), &reg->yawPitchRoll, &reg->position, &reg->velocity, &reg->accel, &reg->angularRate); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readStartupFilterBiasEstimate( struct VnSensor *s, struct StartupFilterBiasEstimateRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadStartupFilterBiasEstimate(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseStartupFilterBiasEstimate_raw(responseBuffer, sizeof(responseBuffer), &reg->gyroBias, &reg->accelBias, &reg->pressureBias); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_writeStartupFilterBiasEstimate( struct VnSensor *s, struct StartupFilterBiasEstimateRegister fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteStartupFilterBiasEstimate( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.gyroBias, fields.accelBias, fields.pressureBias)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readDeltaThetaAndDeltaVelocity( struct VnSensor *s, struct DeltaThetaAndDeltaVelocityRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadDeltaThetaAndDeltaVelocity(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseDeltaThetaAndDeltaVelocity_raw(responseBuffer, sizeof(responseBuffer), &reg->deltaTime, &reg->deltaTheta, &reg->deltaVelocity); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readDeltaThetaAndDeltaVelocityConfiguration( struct VnSensor *s, struct DeltaThetaAndDeltaVelocityConfigurationRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint8_t integrationFramePlaceholder; uint8_t gyroCompensationPlaceholder; uint8_t accelCompensationPlaceholder; uint8_t reserved1Placeholder; uint16_t reserved2Placeholder; if ((error = VnUartPacket_genReadDeltaThetaAndDeltaVelocityConfiguration(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseDeltaThetaAndDeltaVelocityConfiguration_raw(responseBuffer, sizeof(responseBuffer), &integrationFramePlaceholder, &gyroCompensationPlaceholder, &accelCompensationPlaceholder, &reserved1Placeholder, &reserved2Placeholder); if (error != E_NONE) return error; reg->integrationFrame = (enum VnIntegrationFrame) integrationFramePlaceholder; reg->gyroCompensation = (enum VnCompensationMode) gyroCompensationPlaceholder; reg->accelCompensation = (enum VnCompensationMode) accelCompensationPlaceholder; return E_NONE; } enum VnError VnSensor_writeDeltaThetaAndDeltaVelocityConfiguration( struct VnSensor *s, struct DeltaThetaAndDeltaVelocityConfigurationRegister fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteDeltaThetaAndDeltaVelocityConfiguration( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.integrationFrame, fields.gyroCompensation, fields.accelCompensation, 0, 0)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readReferenceVectorConfiguration( struct VnSensor *s, struct ReferenceVectorConfigurationRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint8_t resv1Placeholder; uint8_t resv2Placeholder; if ((error = VnUartPacket_genReadReferenceVectorConfiguration(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseReferenceVectorConfiguration_raw(responseBuffer, sizeof(responseBuffer), &reg->useMagModel, &reg->useGravityModel, &resv1Placeholder, &resv2Placeholder, &reg->recalcThreshold, &reg->year, &reg->position); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_writeReferenceVectorConfiguration( struct VnSensor *s, struct ReferenceVectorConfigurationRegister fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteReferenceVectorConfiguration( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.useMagModel, fields.useGravityModel, 0, 0, fields.recalcThreshold, fields.year, fields.position)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readGyroCompensation( struct VnSensor *s, struct GyroCompensationRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadGyroCompensation(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseGyroCompensation_raw(responseBuffer, sizeof(responseBuffer), &reg->c, &reg->b); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_writeGyroCompensation( struct VnSensor *s, struct GyroCompensationRegister fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteGyroCompensation( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.c, fields.b)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readImuFilteringConfiguration( struct VnSensor *s, struct ImuFilteringConfigurationRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint8_t magFilterModePlaceholder; uint8_t accelFilterModePlaceholder; uint8_t gyroFilterModePlaceholder; uint8_t tempFilterModePlaceholder; uint8_t presFilterModePlaceholder; if ((error = VnUartPacket_genReadImuFilteringConfiguration(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseImuFilteringConfiguration_raw(responseBuffer, sizeof(responseBuffer), &reg->magWindowSize, &reg->accelWindowSize, &reg->gyroWindowSize, &reg->tempWindowSize, &reg->presWindowSize, &magFilterModePlaceholder, &accelFilterModePlaceholder, &gyroFilterModePlaceholder, &tempFilterModePlaceholder, &presFilterModePlaceholder); if (error != E_NONE) return error; reg->magFilterMode = (enum VnFilterMode) magFilterModePlaceholder; reg->accelFilterMode = (enum VnFilterMode) accelFilterModePlaceholder; reg->gyroFilterMode = (enum VnFilterMode) gyroFilterModePlaceholder; reg->tempFilterMode = (enum VnFilterMode) tempFilterModePlaceholder; reg->presFilterMode = (enum VnFilterMode) presFilterModePlaceholder; return E_NONE; } enum VnError VnSensor_writeImuFilteringConfiguration( struct VnSensor *s, struct ImuFilteringConfigurationRegister fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteImuFilteringConfiguration( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.magWindowSize, fields.accelWindowSize, fields.gyroWindowSize, fields.tempWindowSize, fields.presWindowSize, fields.magFilterMode, fields.accelFilterMode, fields.gyroFilterMode, fields.tempFilterMode, fields.presFilterMode)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readGpsCompassBaseline( struct VnSensor *s, struct GpsCompassBaselineRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadGpsCompassBaseline(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseGpsCompassBaseline_raw(responseBuffer, sizeof(responseBuffer), &reg->position, &reg->uncertainty); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_writeGpsCompassBaseline( struct VnSensor *s, struct GpsCompassBaselineRegister fields, bool waitForReply) { enum VnError error; char toSend[256]; size_t toSendLength; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genWriteGpsCompassBaseline( toSend, sizeof(toSend), s->sendErrorDetectionMode, &toSendLength, fields.position, fields.uncertainty)) != E_NONE) return error; return VnSensor_transactionNoFinalize(s, toSend, toSendLength, waitForReply, (char*) responseBuffer, &responseLength); } enum VnError VnSensor_readGpsCompassEstimatedBaseline( struct VnSensor *s, struct GpsCompassEstimatedBaselineRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); uint8_t resvPlaceholder; if ((error = VnUartPacket_genReadGpsCompassEstimatedBaseline(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseGpsCompassEstimatedBaseline_raw(responseBuffer, sizeof(responseBuffer), &reg->estBaselineUsed, &resvPlaceholder, &reg->numMeas, &reg->position, &reg->uncertainty); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readYawPitchRollTrueBodyAccelerationAndAngularRates( struct VnSensor *s, struct YawPitchRollTrueBodyAccelerationAndAngularRatesRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadYawPitchRollTrueBodyAccelerationAndAngularRates(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseYawPitchRollTrueBodyAccelerationAndAngularRates_raw(responseBuffer, sizeof(responseBuffer), &reg->yawPitchRoll, &reg->bodyAccel, &reg->gyro); if (error != E_NONE) return error; return E_NONE; } enum VnError VnSensor_readYawPitchRollTrueInertialAccelerationAndAngularRates( struct VnSensor *s, struct YawPitchRollTrueInertialAccelerationAndAngularRatesRegister *reg) { char toSend[17]; size_t length; enum VnError error; uint8_t responseBuffer[0x100]; size_t responseLength = sizeof(responseBuffer); if ((error = VnUartPacket_genReadYawPitchRollTrueInertialAccelerationAndAngularRates(toSend, sizeof(toSend), s->sendErrorDetectionMode, &length)) != E_NONE) return error; if ((error = VnSensor_transactionNoFinalize(s, toSend, length, true, (char*) responseBuffer, &responseLength)) != E_NONE) return error; error = VnUartPacket_parseYawPitchRollTrueInertialAccelerationAndAngularRates_raw(responseBuffer, sizeof(responseBuffer), &reg->yawPitchRoll, &reg->inertialAccel, &reg->gyro); if (error != E_NONE) return error; return E_NONE; } enum VnError to_string_VnSyncInMode( char *out, size_t outSize, enum VnSyncInMode val); enum VnError to_string_VnSyncInMode( char *out, size_t outSize, enum VnSyncInMode v) { switch (v) { #ifdef EXTRA case VNSYNCINMODE_COUNT2: return strcpy_x(out, outSize, "Count2"); case VNSYNCINMODE_ADC2: return strcpy_x(out, outSize, "Adc2"); case VNSYNCINMODE_ASYNC2: return strcpy_x(out, outSize, "Async2"); #endif case VNSYNCINMODE_COUNT: return strcpy_x(out, outSize, "Count"); case VNSYNCINMODE_IMU: return strcpy_x(out, outSize, "Imu"); case VNSYNCINMODE_ASYNC: return strcpy_x(out, outSize, "Async"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnSyncInEdge( char *out, size_t outSize, enum VnSyncInEdge v) { switch (v) { case VNSYNCINEDGE_RISING: return strcpy_x(out, outSize, "Rising"); case VNSYNCINEDGE_FALLING: return strcpy_x(out, outSize, "Falling"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnSyncOutMode( char *out, size_t outSize, enum VnSyncOutMode v) { switch (v) { case VNSYNCOUTMODE_NONE: return strcpy_x(out, outSize, "None"); case VNSYNCOUTMODE_ITEMSTART: return strcpy_x(out, outSize, "ItemStart"); case VNSYNCOUTMODE_IMUREADY: return strcpy_x(out, outSize, "ImuReady"); case VNSYNCOUTMODE_INS: return strcpy_x(out, outSize, "Ins"); case VNSYNCOUTMODE_GPSPPS: return strcpy_x(out, outSize, "GpsPps"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnSyncOutPolarity( char *out, size_t outSize, enum VnSyncOutPolarity v) { switch (v) { case VNSYNCOUTPOLARITY_NEGATIVE: return strcpy_x(out, outSize, "Negative"); case VNSYNCOUTPOLARITY_POSITIVE: return strcpy_x(out, outSize, "Positive"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnCountMode( char *out, size_t outSize, enum VnCountMode v) { switch (v) { case VNCOUNTMODE_NONE: return strcpy_x(out, outSize, "None"); case VNCOUNTMODE_SYNCINCOUNT: return strcpy_x(out, outSize, "SyncInCount"); case VNCOUNTMODE_SYNCINTIME: return strcpy_x(out, outSize, "SyncInTime"); case VNCOUNTMODE_SYNCOUTCOUNTER: return strcpy_x(out, outSize, "SyncOutCounter"); case VNCOUNTMODE_GPSPPS: return strcpy_x(out, outSize, "GpsPps"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnStatusMode( char *out, size_t outSize, enum VnStatusMode v) { switch (v) { case VNSTATUSMODE_OFF: return strcpy_x(out, outSize, "Off"); case VNSTATUSMODE_VPESTATUS: return strcpy_x(out, outSize, "VpeStatus"); case VNSTATUSMODE_INSSTATUS: return strcpy_x(out, outSize, "InsStatus"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnChecksumMode( char *out, size_t outSize, enum VnChecksumMode v) { switch (v) { case VNCHECKSUMMODE_OFF: return strcpy_x(out, outSize, "Off"); case VNCHECKSUMMODE_CHECKSUM: return strcpy_x(out, outSize, "Checksum"); case VNCHECKSUMMODE_CRC: return strcpy_x(out, outSize, "Crc"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnErrorMode( char *out, size_t outSize, enum VnErrorMode v) { switch (v) { case VNERRORMODE_IGNORE: return strcpy_x(out, outSize, "Ignore"); case VNERRORMODE_SEND: return strcpy_x(out, outSize, "Send"); case VNERRORMODE_SENDANDOFF: return strcpy_x(out, outSize, "SendAndOff"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnFilterMode( char *out, size_t outSize, enum VnFilterMode v) { switch (v) { case VNFILTERMODE_NOFILTERING: return strcpy_x(out, outSize, "NoFiltering"); case VNFILTERMODE_ONLYRAW: return strcpy_x(out, outSize, "OnlyRaw"); case VNFILTERMODE_ONLYCOMPENSATED: return strcpy_x(out, outSize, "OnlyCompensated"); case VNFILTERMODE_BOTH: return strcpy_x(out, outSize, "Both"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnIntegrationFrame( char *out, size_t outSize, enum VnIntegrationFrame v) { switch (v) { case VNINTEGRATIONFRAME_BODY: return strcpy_x(out, outSize, "Body"); case VNINTEGRATIONFRAME_NED: return strcpy_x(out, outSize, "Ned"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnCompensationMode( char *out, size_t outSize, enum VnCompensationMode v) { switch (v) { case VNCOMPENSATIONMODE_NONE: return strcpy_x(out, outSize, "None"); case VNCOMPENSATIONMODE_BIAS: return strcpy_x(out, outSize, "Bias"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnGpsFix( char *out, size_t outSize, enum VnGpsFix v) { switch (v) { case VNGPSFIX_NOFIX: return strcpy_x(out, outSize, "NoFix"); case VNGPSFIX_TIMEONLY: return strcpy_x(out, outSize, "TimeOnly"); case VNGPSFIX_2D: return strcpy_x(out, outSize, "2D"); case VNGPSFIX_3D: return strcpy_x(out, outSize, "3D"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnGpsMode( char *out, size_t outSize, enum VnGpsMode v) { switch (v) { case VNGPSMODE_ONBOARDGPS: return strcpy_x(out, outSize, "OnBoardGps"); case VNGPSMODE_EXTERNALGPS: return strcpy_x(out, outSize, "ExternalGps"); case VNGPSMODE_EXTERNALVN200GPS: return strcpy_x(out, outSize, "ExternalVn200Gps"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnPpsSource( char *out, size_t outSize, enum VnPpsSource v) { switch (v) { case VNPPSSOURCE_GPSPPSRISING: return strcpy_x(out, outSize, "GpsPpsRising"); case VNPPSSOURCE_GPSPPSFALLING: return strcpy_x(out, outSize, "GpsPpsFalling"); case VNPPSSOURCE_SYNCINRISING: return strcpy_x(out, outSize, "SyncInRising"); case VNPPSSOURCE_SYNCINFALLING: return strcpy_x(out, outSize, "SyncInFalling"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnVpeEnable( char *out, size_t outSize, enum VnVpeEnable v) { switch (v) { case VNVPEENABLE_DISABLE: return strcpy_x(out, outSize, "Disable"); case VNVPEENABLE_ENABLE: return strcpy_x(out, outSize, "Enable"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnHeadingMode( char *out, size_t outSize, enum VnHeadingMode v) { switch (v) { case VNHEADINGMODE_ABSOLUTE: return strcpy_x(out, outSize, "Absolute"); case VNHEADINGMODE_RELATIVE: return strcpy_x(out, outSize, "Relative"); case VNHEADINGMODE_INDOOR: return strcpy_x(out, outSize, "Indoor"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnVpeMode( char *out, size_t outSize, enum VnVpeMode v) { switch (v) { case VNVPEMODE_OFF: return strcpy_x(out, outSize, "Off"); case VNVPEMODE_MODE1: return strcpy_x(out, outSize, "Mode1"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnScenario( char *out, size_t outSize, enum VnScenario v) { switch (v) { case VNSCENARIO_AHRS: return strcpy_x(out, outSize, "Ahrs"); case VNSCENARIO_INSWITHPRESSURE: return strcpy_x(out, outSize, "InsWithPressure"); case VNSCENARIO_INSWITHOUTPRESSURE: return strcpy_x(out, outSize, "InsWithoutPressure"); case VNSCENARIO_GPSMOVINGBASELINEDYNAMIC: return strcpy_x(out, outSize, "GpsMovingBaselineDynamic"); case VNSCENARIO_GPSMOVINGBASELINESTATIC: return strcpy_x(out, outSize, "GpsMovingBaselineStatic"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnHsiMode( char *out, size_t outSize, enum VnHsiMode v) { switch (v) { case VNHSIMODE_OFF: return strcpy_x(out, outSize, "Off"); case VNHSIMODE_RUN: return strcpy_x(out, outSize, "Run"); case VNHSIMODE_RESET: return strcpy_x(out, outSize, "Reset"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnHsiOutput( char *out, size_t outSize, enum VnHsiOutput v) { switch (v) { case VNHSIOUTPUT_NOONBOARD: return strcpy_x(out, outSize, "NoOnboard"); case VNHSIOUTPUT_USEONBOARD: return strcpy_x(out, outSize, "UseOnboard"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnVelocityCompensationMode( char *out, size_t outSize, enum VnVelocityCompensationMode v) { switch (v) { case VNVELOCITYCOMPENSATIONMODE_DISABLED: return strcpy_x(out, outSize, "Disabled"); case VNVELOCITYCOMPENSATIONMODE_BODYMEASUREMENT: return strcpy_x(out, outSize, "BodyMeasurement"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnMagneticMode( char *out, size_t outSize, enum VnMagneticMode v) { switch (v) { case VNMAGNETICMODE_2D: return strcpy_x(out, outSize, "2D"); case VNMAGNETICMODE_3D: return strcpy_x(out, outSize, "3D"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnExternalSensorMode( char *out, size_t outSize, enum VnExternalSensorMode v) { switch (v) { case VNEXTERNALSENSORMODE_INTERNAL: return strcpy_x(out, outSize, "Internal"); case VNEXTERNALSENSORMODE_EXTERNAL200HZ: return strcpy_x(out, outSize, "External200Hz"); case VNEXTERNALSENSORMODE_EXTERNALONUPDATE: return strcpy_x(out, outSize, "ExternalOnUpdate"); default: return strcpy_x(out, outSize, "Unknown"); } } enum VnError to_string_VnFoamInit( char *out, size_t outSize, enum VnFoamInit v) { switch (v) { case VNFOAMINIT_NOFOAMINIT: return strcpy_x(out, outSize, "NoFoamInit"); case VNFOAMINIT_FOAMINITPITCHROLL: return strcpy_x(out, outSize, "FoamInitPitchRoll"); case VNFOAMINIT_FOAMINITHEADINGPITCHROLL: return strcpy_x(out, outSize, "FoamInitHeadingPitchRoll"); case VNFOAMINIT_FOAMINITPITCHROLLCOVARIANCE: return strcpy_x(out, outSize, "FoamInitPitchRollCovariance"); case VNFOAMINIT_FOAMINITHEADINGPITCHROLLCOVARIANCE: return strcpy_x(out, outSize, "FoamInitHeadingPitchRollCovariance"); default: return strcpy_x(out, outSize, "Unknown"); } }
29.647786
349
0.711885
261083c06b31b0e4d98da952610ab05da01a044e
3,098
java
Java
modules/metrics/src/test/java/com/spotify/apollo/metrics/MetricsTest.java
rulle-io/apollo
13eb8daf44cea3f83fa5e2a5fd775266253204f4
[ "Apache-2.0" ]
1,806
2015-11-17T21:24:30.000Z
2022-03-26T06:36:59.000Z
modules/metrics/src/test/java/com/spotify/apollo/metrics/MetricsTest.java
rulle-io/apollo
13eb8daf44cea3f83fa5e2a5fd775266253204f4
[ "Apache-2.0" ]
302
2015-11-18T14:39:19.000Z
2021-09-28T09:15:51.000Z
modules/metrics/src/test/java/com/spotify/apollo/metrics/MetricsTest.java
rulle-io/apollo
13eb8daf44cea3f83fa5e2a5fd775266253204f4
[ "Apache-2.0" ]
287
2015-11-17T19:28:25.000Z
2022-03-18T20:04:22.000Z
/* * -\-\- * Spotify Apollo Metrics Module * -- * Copyright (C) 2013 - 2016 Spotify AB * -- * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * -/-/- */ package com.spotify.apollo.metrics; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.name.Names; import com.spotify.apollo.core.Services; import com.spotify.metrics.core.MetricId; import com.spotify.metrics.core.SemanticMetricFilter; import com.spotify.metrics.core.SemanticMetricRegistry; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.junit.Test; import static org.junit.Assert.assertFalse; public class MetricsTest extends AbstractModule { @Override protected void configure() { bindConstant().annotatedWith(Names.named(Services.INJECT_SERVICE_NAME)).to("test"); bind(Config.class).toInstance(ConfigFactory.empty()); bind(MetricId.class).toInstance(MetricId.EMPTY); } @Test public void testJvmMetricSets() throws Exception { final Injector injector = Guice.createInjector(this, MetricsModule.create()); final SemanticMetricRegistry metricRegistry = injector.getInstance(SemanticMetricRegistry.class); // a little dicey to have to know what tags the MetricSets created metrics with to assert that // the Set itself was registered but there is no other obvious way to test these assertFalse("Expected MemoryUsageGaugeSet metrics to be registered with registry", metricRegistry.getGauges(filterByTag("what", "jvm-memory-usage")).isEmpty()); assertFalse("Expected GarbageCollectorMetricSet metrics to be registered with registry", metricRegistry.getGauges(filterByTag("what", "jvm-gc-collections")).isEmpty()); assertFalse("Expected ThreadStatesMetricSet metrics to be registered with registry", metricRegistry.getGauges(filterByTag("what", "jvm-thread-state")).isEmpty()); assertFalse("Expected CpuGaugeSet metrics to be registered with registry", metricRegistry.getGauges(filterByTag("what", "process-cpu-load-percentage")).isEmpty()); assertFalse("Expected FileDescriptorRatioGaugeSet metrics to be registered with registry", metricRegistry.getGauges(filterByTag("what", "file-descriptor-ratio")).isEmpty()); } private SemanticMetricFilter filterByTag(final String tagName, final String tagValue){ return (name, metric) -> name.getTags().containsKey(tagName) && name.getTags().get(tagName).equals(tagValue); } }
40.763158
104
0.739832
95aa7157bba1f8ae4b5fc053c75cabe6206df814
789
kt
Kotlin
domain/src/test/java/org/watsi/domain/factories/EnrollmentPeriodFactory.kt
liangmicha/meso-clinic
5847b743de479ebd3344cb8fcf8da8659011b1fa
[ "Apache-2.0" ]
5
2020-02-06T03:42:19.000Z
2021-12-30T04:07:43.000Z
domain/src/test/java/org/watsi/domain/factories/EnrollmentPeriodFactory.kt
liangmicha/meso-clinic
5847b743de479ebd3344cb8fcf8da8659011b1fa
[ "Apache-2.0" ]
2
2020-02-09T21:19:47.000Z
2020-04-24T00:57:45.000Z
domain/src/test/java/org/watsi/domain/factories/EnrollmentPeriodFactory.kt
liangmicha/meso-clinic
5847b743de479ebd3344cb8fcf8da8659011b1fa
[ "Apache-2.0" ]
2
2020-01-31T17:26:22.000Z
2020-03-31T09:56:20.000Z
package org.watsi.domain.factories import org.threeten.bp.LocalDate import org.watsi.domain.entities.EnrollmentPeriod object EnrollmentPeriodFactory { fun build( id: Int = 1, startDate: LocalDate = LocalDate.now(), endDate: LocalDate = LocalDate.now().plusYears(1), coverageStartDate: LocalDate = LocalDate.now(), coverageEndDate: LocalDate = LocalDate.now().plusYears(1), administrativeDivisionId: Int = 1 ) : EnrollmentPeriod { return EnrollmentPeriod( id = id, startDate = startDate, endDate = endDate, coverageStartDate = coverageStartDate, coverageEndDate = coverageEndDate, administrativeDivisionId = administrativeDivisionId ) } }
30.346154
66
0.647655
84c1f9345e4e1a501958ba9bff0c96781aebd226
1,105
c
C
software/tcl_auto/ds9tools/ast/sla/caf2r.c
MMTObservatory/SAOguider
e528d35d63876e2db066bef43cfcabd6946bc986
[ "BSD-3-Clause" ]
null
null
null
software/tcl_auto/ds9tools/ast/sla/caf2r.c
MMTObservatory/SAOguider
e528d35d63876e2db066bef43cfcabd6946bc986
[ "BSD-3-Clause" ]
null
null
null
software/tcl_auto/ds9tools/ast/sla/caf2r.c
MMTObservatory/SAOguider
e528d35d63876e2db066bef43cfcabd6946bc986
[ "BSD-3-Clause" ]
null
null
null
#include "slalib.h" #include "slamac.h" void slaCaf2r ( int ideg, int iamin, float asec, float *rad, int *j ) /* ** - - - - - - - - - ** s l a C a f 2 r ** - - - - - - - - - ** ** Convert degrees, arcminutes, arcseconds to radians. ** ** (single precision) ** ** Given: ** ideg int degrees ** iamin int arcminutes ** asec float arcseconds ** ** Returned: ** *rad float angle in radians ** *j int status: 0 = ok ** 1 = ideg outside range 0-359 ** 2 = iamin outside range 0-59 ** 3 = asec outside range 0-59.999... ** ** Notes: ** 1) The result is computed even if any of the range checks fail. ** ** 2) The sign must be dealt with outside this routine. ** ** Called: slaDaf2r ** ** Last revision: 31 October 1993 ** ** Copyright P.T.Wallace. All rights reserved. */ { double w; /* Call double precision version */ slaDaf2r ( ideg, iamin, (double) asec, &w, j ); *rad = (float) w; }
25.697674
72
0.494118
11d161323a2eccc88cfb94b8b6db88d8843c95ce
1,612
html
HTML
data/message_html_fragments/847786770346541097.html
kishikawakatsumi/swift-developers-japan-discussion-archive
7b1c143f0a201f614f1bc0364361836a9df9dc82
[ "MIT" ]
1
2022-02-13T01:21:35.000Z
2022-02-13T01:21:35.000Z
data/message_html_fragments/847786770346541097.html
kishikawakatsumi/swift-developers-japan-discussion-archive
7b1c143f0a201f614f1bc0364361836a9df9dc82
[ "MIT" ]
25
2022-02-12T19:45:00.000Z
2022-03-25T17:53:54.000Z
data/message_html_fragments/847786770346541097.html
kishikawakatsumi/swift-developers-japan-discussion-archive
7b1c143f0a201f614f1bc0364361836a9df9dc82
[ "MIT" ]
null
null
null
<div class="chatlog__message-group"> <div id="chatlog__message-container-847786770346541097" class="chatlog__message-container " data-message-id="847786770346541097"> <div class="chatlog__message"> <div class="chatlog__message-aside"> <img class="chatlog__avatar" src="https://cdn.discordapp.com/avatars/291062140079570944/75d22639a88c37be90cb60118acb7df5.png?size=512" alt="Avatar" loading="lazy"> </div> <div class="chatlog__message-primary"> <div class="chatlog__header"> <span class="chatlog__author" style="color: rgb(241, 196, 15)" title="kateinoigakukun#2184" data-user-id="291062140079570944">kateinoigakukun</span> <a href="/channels/380329942505750529?category=イベント&amp;channel=waiwai-swiftc&amp;message_id=847786770346541097"><span class="chatlog__timestamp">28-May-21 10:41 AM</span></a> </div> <div class="chatlog__content chatlog__markdown"> <span class="chatlog__markdown-preserve"><span class="chatlog__markdown-mention" title="swift54#8732">@swift-5.4.3</span> <span class="chatlog__markdown-mention" title="swift53#5213">@swift-5.3.3</span> <div class="chatlog__markdown-pre chatlog__markdown-pre--multiline language-swift">struct Container&lt;T&gt; { func map&lt;T, U&gt;(_ transformer: (T) -&gt; U) -&gt; Container&lt;U&gt; { return .init() } } let n = Container&lt;Never&gt;() let u: Container&lt;Int&gt; = n.map { _ in }</div> </span> <span class="chatlog__edited-timestamp" title="28-May-21 10:43 AM">(edited)</span> </div> </div> </div> </div> </div>
76.761905
301
0.692308
9c23457474c2c9a3fda8a49d3124aed9cd548748
34
js
JavaScript
public/assets/lib/jwplayer-master/src/js/view/constants.js
hoangnhonline/study-2017
67368b68f64b9316f68fad0a5748072c5cefde33
[ "MIT" ]
null
null
null
public/assets/lib/jwplayer-master/src/js/view/constants.js
hoangnhonline/study-2017
67368b68f64b9316f68fad0a5748072c5cefde33
[ "MIT" ]
null
null
null
public/assets/lib/jwplayer-master/src/js/view/constants.js
hoangnhonline/study-2017
67368b68f64b9316f68fad0a5748072c5cefde33
[ "MIT" ]
null
null
null
export const dvrSeekLimit = -25;
11.333333
32
0.735294
03978e9c35acde973f27c890e65c1106b73fd430
8,032
swift
Swift
Acme/Acme/Views/TabCollectionViewCell.swift
alvare52/Mobile-Web-Browser
6709f26711b0b9eac2b6095f48da8f568c264812
[ "Apache-2.0" ]
2
2021-09-04T11:19:24.000Z
2022-01-16T03:57:33.000Z
Acme/Acme/Views/TabCollectionViewCell.swift
alvare52/Mobile-Web-Browser
6709f26711b0b9eac2b6095f48da8f568c264812
[ "Apache-2.0" ]
null
null
null
Acme/Acme/Views/TabCollectionViewCell.swift
alvare52/Mobile-Web-Browser
6709f26711b0b9eac2b6095f48da8f568c264812
[ "Apache-2.0" ]
null
null
null
// // TabCollectionViewCell.swift // Acme // // Created by Jorge Alvarez on 4/18/21. // import UIKit protocol CellDeletionDelegate { /// Tells TabCollectionViewController to delete cell at given tab func deleteTabForCell(cell: TabCollectionViewCell, bookmark: Bookmark) } class TabCollectionViewCell: UICollectionViewCell { // MARK: - Properties /// Used to tell TabCollectionViewController to delete cell var cellDeletionDelegate: CellDeletionDelegate? /// Acts as "container" so imageView doesn't can fill up whole cell var customView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = .white return view }() var deleteButton: UIButton = { let button = UIButton() button.translatesAutoresizingMaskIntoConstraints = false button.setImage(UIImage(systemName: "xmark"), for: .normal) button.tintColor = .black button.backgroundColor = .white return button }() var deleteButtonContainerView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = .white return view }() var faviconContainerView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = .white return view }() var faviconImageView: UIImageView = { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.contentMode = .scaleAspectFill imageView.layer.masksToBounds = false imageView.clipsToBounds = true imageView.image = UIImage(systemName: "safari") imageView.backgroundColor = .white return imageView }() /// Holds tab object that's passed in var tab: Bookmark? { didSet { updateViews() } } /// UIImageView that displays a screenshot of tab var tabScreenShotImageView: UIImageView = { let imageView = UIImageView() imageView.translatesAutoresizingMaskIntoConstraints = false imageView.backgroundColor = .white imageView.contentMode = .scaleAspectFill imageView.layer.masksToBounds = false imageView.clipsToBounds = true return imageView }() /// UILabel that displays tab title var tabTitleLabel: UILabel = { let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "Tab" label.backgroundColor = .white label.textAlignment = .center label.font = .systemFont(ofSize: 12, weight: .medium) return label }() // MARK: - View Life Cycle override init(frame: CGRect) { super.init(frame: frame) setupSubviews() } required init?(coder: NSCoder) { super.init(coder: coder) setupSubviews() } /// Layouts UI private func setupSubviews() { clipsToBounds = true layer.cornerRadius = 5 // Custom View addSubview(customView) customView.topAnchor.constraint(equalTo: topAnchor).isActive = true customView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true customView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true customView.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true // Favicon Container customView.addSubview(faviconContainerView) faviconContainerView.topAnchor.constraint(equalTo: customView.topAnchor).isActive = true faviconContainerView.leadingAnchor.constraint(equalTo: customView.leadingAnchor).isActive = true faviconContainerView.heightAnchor.constraint(equalTo: customView.heightAnchor, multiplier: 0.1).isActive = true faviconContainerView.widthAnchor.constraint(equalTo: faviconContainerView.heightAnchor).isActive = true // Tab Title Label customView.addSubview(tabTitleLabel) tabTitleLabel.topAnchor.constraint(equalTo: customView.topAnchor).isActive = true tabTitleLabel.leadingAnchor.constraint(equalTo: faviconContainerView.trailingAnchor).isActive = true tabTitleLabel.heightAnchor.constraint(equalTo: customView.heightAnchor, multiplier: 0.1).isActive = true tabTitleLabel.widthAnchor.constraint(equalTo: customView.widthAnchor, multiplier: 0.8).isActive = true // Delete Button Container customView.addSubview(deleteButtonContainerView) deleteButtonContainerView.topAnchor.constraint(equalTo: customView.topAnchor).isActive = true deleteButtonContainerView.leadingAnchor.constraint(equalTo: tabTitleLabel.trailingAnchor).isActive = true deleteButtonContainerView.heightAnchor.constraint(equalTo: customView.heightAnchor, multiplier: 0.1).isActive = true deleteButtonContainerView.widthAnchor.constraint(equalTo: deleteButtonContainerView.heightAnchor).isActive = true // Favicon Image View customView.addSubview(faviconImageView) faviconImageView.centerYAnchor.constraint(equalTo: faviconContainerView.centerYAnchor).isActive = true faviconImageView.centerXAnchor.constraint(equalTo: faviconContainerView.centerXAnchor).isActive = true faviconImageView.heightAnchor.constraint(equalTo: faviconContainerView.heightAnchor, multiplier: 0.6).isActive = true faviconImageView.widthAnchor.constraint(equalTo: faviconImageView.heightAnchor).isActive = true // Delete Button customView.addSubview(deleteButton) deleteButton.heightAnchor.constraint(equalTo: deleteButtonContainerView.heightAnchor, multiplier: 0.6).isActive = true deleteButton.centerYAnchor.constraint(equalTo: deleteButtonContainerView.centerYAnchor).isActive = true deleteButton.centerXAnchor.constraint(equalTo: deleteButtonContainerView.centerXAnchor).isActive = true deleteButton.widthAnchor.constraint(equalTo: deleteButton.heightAnchor).isActive = true deleteButton.addTarget(self, action: #selector(deleteTapped), for: .touchUpInside) // Tab Screenshot Image View customView.addSubview(tabScreenShotImageView) tabScreenShotImageView.topAnchor.constraint(equalTo: tabTitleLabel.bottomAnchor).isActive = true tabScreenShotImageView.bottomAnchor.constraint(equalTo: customView.bottomAnchor).isActive = true tabScreenShotImageView.leadingAnchor.constraint(equalTo: customView.leadingAnchor).isActive = true tabScreenShotImageView.trailingAnchor.constraint(equalTo: customView.trailingAnchor).isActive = true } /// Updates the cell to display correct label, favicon, and snapshot private func updateViews() { guard let tab = tab else { return } // Tab Label tabTitleLabel.text = tab.urlTitle // Tab Snapshot let image = UIImage.loadImageFromDiskWith(fileName: "\(tab.urlTitle)") tabScreenShotImageView.image = image // Tab Icon let name = "favicon-" + tab.url.absoluteString.replacingOccurrences(of: "/", with: "-") let favicon = UIImage.loadImageFromDiskWith(fileName: name) ?? UIImage(systemName: "safari") faviconImageView.image = favicon } // MARK: - Actions /// Tells TabsCollectionViewController to delete cell that matches tab @objc private func deleteTapped() { guard let tab = tab else { return } cellDeletionDelegate?.deleteTabForCell(cell: self, bookmark: tab) } // MARK: - Helpers /// Highlights cell to show that it's the currently selected tab func highLight() { layer.borderWidth = 2 layer.borderColor = UIColor.customTintColor.cgColor } }
40.565657
126
0.692231
58e82fbd12037bb8487bbe1760e7b48f84a69357
1,010
rs
Rust
src/server/src/node/replica/eval/cmd_get.rs
zojw/engula
2e6852ff40bc104baf9eb42097a9d4f48aa6dfd6
[ "Apache-2.0" ]
null
null
null
src/server/src/node/replica/eval/cmd_get.rs
zojw/engula
2e6852ff40bc104baf9eb42097a9d4f48aa6dfd6
[ "Apache-2.0" ]
null
null
null
src/server/src/node/replica/eval/cmd_get.rs
zojw/engula
2e6852ff40bc104baf9eb42097a9d4f48aa6dfd6
[ "Apache-2.0" ]
null
null
null
// Copyright 2022 The Engula Authors. // // 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. use engula_api::server::v1::ShardGetRequest; use crate::{node::engine::GroupEngine, Error, Result}; /// Get the value of the specified key. pub async fn get(engine: &GroupEngine, req: &ShardGetRequest) -> Result<Option<Vec<u8>>> { let get = req .get .as_ref() .ok_or_else(|| Error::InvalidArgument("ShardGetRequest::get is None".into()))?; engine.get(req.shard_id, &get.key).await }
37.407407
90
0.713861
fb940195cee9e008e78b5f838784700015f00f42
4,218
java
Java
app/src/main/java/com/kidozh/discuzhub/adapter/ForumCategoryAdapter.java
dora-world/DiscuzHub
49187c52f39edee1d5436932c39aacd3474da9f6
[ "MIT" ]
56
2020-01-15T09:29:27.000Z
2022-02-24T08:00:50.000Z
app/src/main/java/com/kidozh/discuzhub/adapter/ForumCategoryAdapter.java
dora-world/DiscuzHub
49187c52f39edee1d5436932c39aacd3474da9f6
[ "MIT" ]
32
2020-07-18T04:07:10.000Z
2022-02-11T11:53:12.000Z
app/src/main/java/com/kidozh/discuzhub/adapter/ForumCategoryAdapter.java
dora-world/DiscuzHub
49187c52f39edee1d5436932c39aacd3474da9f6
[ "MIT" ]
22
2020-07-18T08:09:54.000Z
2022-03-20T15:08:37.000Z
package com.kidozh.discuzhub.adapter; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.kidozh.discuzhub.R; import com.kidozh.discuzhub.entities.Discuz; import com.kidozh.discuzhub.entities.Forum; import com.kidozh.discuzhub.entities.User; import com.kidozh.discuzhub.results.DiscuzIndexResult; import com.kidozh.discuzhub.utilities.AnimationUtils; import com.kidozh.discuzhub.utilities.UserPreferenceUtils; import java.util.ArrayList; import java.util.List; public class ForumCategoryAdapter extends RecyclerView.Adapter<ForumCategoryAdapter.bbsShowPortalViewHolder> { private final static String TAG = ForumCategoryAdapter.class.getSimpleName(); Context mContext; List<DiscuzIndexResult.ForumCategory> forumCategoryList = new ArrayList<>(); Discuz bbsInfo; User curUser; List<Forum> allForum; ForumCategoryAdapter(Context context){ this.mContext = context; } public ForumCategoryAdapter(Discuz Discuz, User userBriefInfo){ this.bbsInfo = Discuz; this.curUser = userBriefInfo; } public void setForumCategoryList(@NonNull List<DiscuzIndexResult.ForumCategory> forumCategoryList, List<Forum> allForum) { int oldSize = this.forumCategoryList.size(); this.forumCategoryList.clear(); notifyItemRangeRemoved(0,oldSize); this.forumCategoryList.addAll(forumCategoryList); this.allForum = allForum; //notifyDataSetChanged(); notifyItemRangeInserted(0,forumCategoryList.size()); Log.d(TAG,"insert number "+getItemCount()+" "+this.forumCategoryList); } @NonNull @Override public bbsShowPortalViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { Context context = parent.getContext(); mContext = context; int layoutIdForListItem = R.layout.item_forum_category; LayoutInflater inflater = LayoutInflater.from(context); boolean shouldAttachToParentImmediately = false; View view = inflater.inflate(layoutIdForListItem, parent, shouldAttachToParentImmediately); return new bbsShowPortalViewHolder(view); } @Override public void onBindViewHolder(@NonNull bbsShowPortalViewHolder holder, int position) { DiscuzIndexResult.ForumCategory category = forumCategoryList.get(position); holder.mPortalCatagoryName.setText(category.name); if(UserPreferenceUtils.conciseRecyclerView(mContext)){ holder.mRecyclerView.setLayoutManager(new GridLayoutManager(mContext,4)); } else { holder.mRecyclerView.setLayoutManager(new GridLayoutManager(mContext,2)); //holder.mRecyclerView.addItemDecoration(new DividerItemDecoration(mContext,DividerItemDecoration.VERTICAL)); } ForumAdapter adapter = new ForumAdapter(bbsInfo,curUser); holder.mRecyclerView.setItemAnimator(AnimationUtils.INSTANCE.getRecyclerviewAnimation(mContext)); holder.mRecyclerView.setAdapter(adapter); List<Forum> forumListInTheCategory = category.getForumListInTheCategory(allForum); adapter.setForumList(forumListInTheCategory); } @Override public int getItemCount() { if(forumCategoryList == null){ return 0; } else { return forumCategoryList.size(); } } public class bbsShowPortalViewHolder extends RecyclerView.ViewHolder{ TextView mPortalCatagoryName; RecyclerView mRecyclerView; ImageView mPortalCategoryIcon; public bbsShowPortalViewHolder(@NonNull View itemView) { super(itemView); mPortalCatagoryName = itemView.findViewById(R.id.portal_catagory_name); mRecyclerView = itemView.findViewById(R.id.portal_catagory_recyclerview); mPortalCategoryIcon = itemView.findViewById(R.id.portal_category_icon); } } }
35.745763
126
0.734471
1e81f4a51815ce2e0a043abd9fd23d88ec47550f
703
swift
Swift
Sources/TranslationCatalog/Project.swift
richardpiazza/TranslationCatalog
737f966b331b20b4844dc8a15807c82098d4efc3
[ "MIT" ]
null
null
null
Sources/TranslationCatalog/Project.swift
richardpiazza/TranslationCatalog
737f966b331b20b4844dc8a15807c82098d4efc3
[ "MIT" ]
null
null
null
Sources/TranslationCatalog/Project.swift
richardpiazza/TranslationCatalog
737f966b331b20b4844dc8a15807c82098d4efc3
[ "MIT" ]
null
null
null
import Foundation /// A grouping of `Expression`s used for a common purpose, such as an application or service. public struct Project { /// Identifier that universally identifies this `Project` public var uuid: UUID /// A custom description public var name: String /// The `Expression`s associated with this `Project` public var expressions: [Expression] public init(uuid: UUID = .zero, name: String = "", expressions: [Expression] = []) { self.uuid = uuid self.name = name self.expressions = expressions } } extension Project: Codable {} extension Project: Equatable {} extension Project: Identifiable { public var id: UUID { uuid } }
29.291667
93
0.672831
284e12171b4c9511dc4d794608386b63dbb5b043
2,247
swift
Swift
Bilhete Unico/ViewController.swift
matheusmpedrosa/saldo-bilhete-unico
289cceb8de9f45f15b920d674bd6e549ab99e32f
[ "MIT" ]
null
null
null
Bilhete Unico/ViewController.swift
matheusmpedrosa/saldo-bilhete-unico
289cceb8de9f45f15b920d674bd6e549ab99e32f
[ "MIT" ]
null
null
null
Bilhete Unico/ViewController.swift
matheusmpedrosa/saldo-bilhete-unico
289cceb8de9f45f15b920d674bd6e549ab99e32f
[ "MIT" ]
null
null
null
// // ViewController.swift // Bilhete Unico // // Created by Matheus Pedrosa on 8/3/19. // Copyright © 2019 M2P. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var saldoLabel: UILabel! @IBOutlet weak var tarifaComumButton: UIButton! @IBOutlet weak var tarifaValeTransporteButton: UIButton! @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.title = "Bilhete Único" self.tableView.dataSource = self self.tableView.delegate = self let cornerRadius: CGFloat = 4 let borderWidth: CGFloat = 1.5 let borderColor: CGColor = self.view.tintColor.cgColor self.tarifaComumButton.layer.cornerRadius = cornerRadius self.tarifaComumButton.layer.borderWidth = borderWidth self.tarifaComumButton.layer.borderColor = borderColor self.tarifaValeTransporteButton.layer.cornerRadius = cornerRadius self.tarifaValeTransporteButton.layer.borderWidth = borderWidth self.tarifaValeTransporteButton.layer.borderColor = borderColor } @IBAction func adicionarTarifaComum(_ sender: Any) { print("+ R$ 4,30") } @IBAction func adicionarTarifaValeTransporte(_ sender: Any) { print("+ R$ 3,76") } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { let today: Date = Date() let formater: DateFormatter = DateFormatter() formater.dateFormat = "dd/MM" let result = formater.string(from: today) return result } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! LogTableViewCell cell.setup(with: "Tarifa Comum", valor: "R$ 4,30") return cell } }
29.565789
109
0.661326
38e23a41aea030cafc19de20a0799c5079768037
3,716
h
C
src/mongo/db/exec/shard_filter.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/exec/shard_filter.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/mongo/db/exec/shard_filter.h
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2018-present MongoDB, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc. * * 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 * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License * along with this program. If not, see * <http://www.mongodb.com/licensing/server-side-public-license>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the Server Side Public License in all respects for * all of the code used other than as permitted herein. If you modify file(s) * with this exception, you may extend this exception to your version of the * file(s), but you are not obligated to do so. If you do not wish to do so, * delete this exception statement from your version. If you delete this * exception statement from all source files in the program, then also delete * it in the license file. */ #pragma once #include "mongo/db/exec/plan_stage.h" #include "mongo/db/exec/shard_filterer_impl.h" namespace mongo { /** * This stage drops documents (called "orphans") that don't logically belong to this shard according * to the the provided 'collectionFilter'. No data should be returned from a query in ranges of * migrations that committed after the query started, or from ranges not owned when the query began. * * A related system will ensure that the data migrated away from a shard will not be deleted as long * as there are active queries from before the migration. By holding onto a copy of the provided * 'collectionFilter', this stage signals to the sharding subsystem that the data required at the * associated shard version cannot yet be deleted. In other words, no migrated data should be * removed from a shard while there are queries that were active before the migration. * * Preconditions: Child must be fetched. */ class ShardFilterStage final : public PlanStage { public: ShardFilterStage(ExpressionContext* expCtx, ScopedCollectionFilter collectionFilter, WorkingSet* ws, std::unique_ptr<PlanStage> child); ~ShardFilterStage(); bool isEOF() final; StageState doWork(WorkingSetID* out) final; StageType stageType() const final { return STAGE_SHARDING_FILTER; } std::unique_ptr<PlanStageStats> getStats() final; const SpecificStats* getSpecificStats() const final; static const char* kStageType; private: WorkingSet* _ws; ShardingFilterStats _specificStats; // Note: it is important that this owns the ScopedCollectionFilter from the time this stage // is constructed. See ScopedCollectionFilter class comment and MetadataManager comment for // details. The existence of the ScopedCollectionFilter prevents data which may have been // migrated from being deleted while the query is still active. If we didn't hold one // ScopedCollectionFilter for the entire query, it'd be possible for data which the query // needs to read to be deleted while it's still running. ShardFiltererImpl _shardFilterer; }; } // namespace mongo
43.209302
100
0.731163
18b11813a1ab7973c194bcdc53b83bdb333051cf
2,165
kt
Kotlin
core/src/main/java/com/jn/kikukt/mvp/Mvp.kt
JerrNeon/Kiku-kotlin
e411310b23578168212ae48773f0f77934e3d52c
[ "Apache-2.0" ]
1
2021-01-11T06:09:33.000Z
2021-01-11T06:09:33.000Z
core/src/main/java/com/jn/kikukt/mvp/Mvp.kt
JerrNeon/Kiku-kotlin
e411310b23578168212ae48773f0f77934e3d52c
[ "Apache-2.0" ]
null
null
null
core/src/main/java/com/jn/kikukt/mvp/Mvp.kt
JerrNeon/Kiku-kotlin
e411310b23578168212ae48773f0f77934e3d52c
[ "Apache-2.0" ]
1
2021-01-11T06:09:35.000Z
2021-01-11T06:09:35.000Z
package com.jn.kikukt.mvp import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import com.jn.kikukt.common.utils.Clazz import com.jn.kikukt.net.retrofit.BaseHttpResult import com.jn.kikukt.net.rxjava.RxBaseObserver import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.disposables.Disposable /** * Author:Stevie.Chen Time:2020/7/15 * Class Comment:MVP */ interface IBModel interface IBView interface IBPresenter : IDisposableView, DefaultLifecycleObserver { fun attachView(view: IBView?) fun detachView() override fun onDestroy(owner: LifecycleOwner) { dispose() detachView() } } open class BaseModel : IBModel abstract class BasePresenter<V : IBView, M : IBModel> : IBPresenter { private var view: V? = null protected val mView: V get() = view!! protected val mModel: M by lazy { Clazz.getClass<M>(this, argumentsPosition = 1).newInstance() } override var mCompositeDisposable: CompositeDisposable? = null @Suppress("UNCHECKED_CAST") override fun attachView(view: IBView?) { this.view = view as? V } override fun detachView() { view = null } } open class RxBasePresenterObserver<T : BaseHttpResult<V>, V>( private val iBPresenter: IBPresenter, errorType: Int, onSubscribe: ((d: Disposable) -> Unit)? = null, onSuccess: (v: V) -> Unit, onResponse: ((t: T) -> Unit)? = null, onFailure: ((e: Throwable, errorMsg: String) -> Unit)? = null ) : RxBaseObserver<T, V>(errorType, onSubscribe, onSuccess, onResponse, onFailure) { override fun onSubscribe(d: Disposable) { super.onSubscribe(d) iBPresenter.addDisposable(d) } } interface IDisposableView { var mCompositeDisposable: CompositeDisposable? fun addDisposable(disposable: Disposable) { if (mCompositeDisposable == null) mCompositeDisposable = CompositeDisposable() mCompositeDisposable?.add(disposable) } fun dispose() { mCompositeDisposable?.let { if (!it.isDisposed) it.dispose() } } }
26.728395
100
0.684065
e55d523ff249e499c656268ada6003704dcea468
665
asm
Assembly
oeis/053/A053149.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/053/A053149.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/053/A053149.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A053149: Smallest cube divisible by n. ; Submitted by Christian Krause ; 1,8,27,8,125,216,343,8,27,1000,1331,216,2197,2744,3375,64,4913,216,6859,1000,9261,10648,12167,216,125,17576,27,2744,24389,27000,29791,64,35937,39304,42875,216,50653,54872,59319,1000,68921,74088,79507,10648,3375,97336,103823,1728,343,1000,132651,17576,148877,216,166375,2744,185193,195112,205379,27000,226981,238328,9261,64,274625,287496,300763,39304,328509,343000,357911,216,389017,405224,3375,54872,456533,474552,493039,8000,729,551368,571787,74088,614125,636056,658503,10648,704969,27000,753571 mov $1,$0 add $0,1 seq $1,48798 ; Smallest k > 0 such that n*k is a perfect cube. mul $0,$1
73.888889
498
0.783459
74665dd51fc32ca1a6922dceeda7a4201dda232b
4,960
kt
Kotlin
native/native.tests/tests/org/jetbrains/kotlin/konan/blackboxtest/support/util/TestListing.kt
andreyfomenkov/kotlin-relaxed
0f3f251454e49d20d4c7242beeac5d4bda021c28
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
native/native.tests/tests/org/jetbrains/kotlin/konan/blackboxtest/support/util/TestListing.kt
andreyfomenkov/kotlin-relaxed
0f3f251454e49d20d4c7242beeac5d4bda021c28
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
native/native.tests/tests/org/jetbrains/kotlin/konan/blackboxtest/support/util/TestListing.kt
andreyfomenkov/kotlin-relaxed
0f3f251454e49d20d4c7242beeac5d4bda021c28
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * 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.konan.blackboxtest.support.util import org.jetbrains.kotlin.konan.blackboxtest.support.TestName import org.jetbrains.kotlin.test.services.JUnit5Assertions.fail import org.jetbrains.kotlin.utils.addToStdlib.cast import org.jetbrains.kotlin.utils.addToStdlib.safeAs /** * Extracts [TestName]s from the test listing produced immediately during the compilation (turned on with * "-Xdump-tests-to=" compiler flag). * * Example: * sample/test/SampleTestKt:one * sample/test/SampleTestKt:two * * yields TestName(packageName = "sample.test", packagePartClassName = "SampleTestKt", functionName = "one") * and TestName(packageName = "sample.test", packagePartClassName = "SampleTestKt", functionName = "two") */ internal object DumpedTestListing { fun parse(listing: String): Collection<TestName> { val lines = listing.lines() var emptyLineEncountered = false return lines.mapIndexedNotNull { index: Int, line: String -> fun parseError(message: String): Nothing = parseError(message, index, line, listing) when { line.isBlank() -> { emptyLineEncountered = true null } emptyLineEncountered -> parseError("Unexpected empty line") else -> { val (packageAndClass, functionName) = line.trim() .split(':') .takeIf { items -> items.size == 2 && items.none(String::isBlank) } ?: parseError("Malformed test name") with(packageAndClass.split('/')) { val classNames = last().split('.') val packageSegments = dropLast(1) TestName(packageSegments, classNames, functionName) } } } } } } /** * Extracts [TestName]s from GTest listing. * * Example: * sample.test.SampleTestKt. * one * two * * yields TestName(packageName = "sample.test", packagePartClassName = "SampleTestKt", functionName = "one") * and TestName(packageName = "sample.test", packagePartClassName = "SampleTestKt", functionName = "two") */ internal object GTestListing { fun parse(listing: String): Collection<TestName> = buildList { var state: ParseState = ParseState.Begin val lines = listing.lines() lines.forEachIndexed { index, line -> fun parseError(message: String): Nothing = parseError(message, index, line, listing) state = when { line.startsWith(STDLIB_TESTS_IGNORED_LINE_PREFIX) && state is ParseState.Begin -> ParseState.Begin line.isBlank() -> when (state) { is ParseState.NewTest, is ParseState.End -> ParseState.End else -> parseError("Unexpected empty line") } line[0].isWhitespace() -> when (state) { is ParseState.NewTestSuite, is ParseState.NewTest -> { val testSuite = state.testSuite this += TestName(testSuite.testSuiteNameWithDotSuffix + line.trim()) ParseState.NewTest(testSuite) } else -> parseError("Test name encountered before test suite name") } else -> when (state) { is ParseState.Begin, is ParseState.NewTest -> { ParseState.NewTestSuite(line.trimEnd()) } else -> parseError("Unexpected test suite name") } } } if (state is ParseState.NewTestSuite) parseError("Test name expected before test suite name", lines.lastIndex, lines.last(), listing) } private sealed interface ParseState { object Begin : ParseState object End : ParseState class NewTestSuite(val testSuiteNameWithDotSuffix: String) : ParseState class NewTest(val testSuite: NewTestSuite) : ParseState } private inline val ParseState.testSuite: ParseState.NewTestSuite get() = safeAs<ParseState.NewTestSuite>() ?: cast<ParseState.NewTest>().testSuite // The very first line of stdlib test output may contain seed of Random. Such line should be ignored. private const val STDLIB_TESTS_IGNORED_LINE_PREFIX = "Seed: " } private fun parseError(message: String, index: Int, line: String, listing: String): Nothing = fail { buildString { appendLine("$message at line #$index: \"$line\"") appendLine() appendLine("Full listing:") appendLine(listing) } }
39.68
115
0.602218
ddeda22f4e5eb798e5a185ee28d6478d40301306
5,733
h
C
OpenSim/Common/TableUtilities.h
tnamayeshi/opensim-core
acbedd604909980293776da3d54b9611732964bf
[ "Apache-2.0" ]
null
null
null
OpenSim/Common/TableUtilities.h
tnamayeshi/opensim-core
acbedd604909980293776da3d54b9611732964bf
[ "Apache-2.0" ]
null
null
null
OpenSim/Common/TableUtilities.h
tnamayeshi/opensim-core
acbedd604909980293776da3d54b9611732964bf
[ "Apache-2.0" ]
null
null
null
#ifndef OPENSIM_TABLEUTILITIES_H_ #define OPENSIM_TABLEUTILITIES_H_ /* -------------------------------------------------------------------------- * * OpenSim: TableUtilities.h * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2020 Stanford University and the Authors * * Author(s): Christopher Dembia * * * * 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 "Array.h" #include "GCVSpline.h" #include "TableUtilities.h" #include "TimeSeriesTable.h" #include "osimCommonDLL.h" namespace OpenSim { class OSIMCOMMON_API TableUtilities { public: /// Throws an exception if the same label appears more than once in the list /// of labels. /// @throws NonUniqueLabels static void checkNonUniqueLabels(std::vector<std::string> labels); /// Returns true if the table contains 'inDegrees' metadata set to 'yes', /// and returns false if the table contains 'inDegrees' metadata set to /// 'no'. /// @throws Exception if table does not have 'inDegrees' table metadata. /// @throws Exception if the 'inDegrees' metadata is neither 'yes' or 'no'. static bool isInDegrees(const TimeSeriesTable& table); /// Get the index in the provided array of labels that corresponds to the /// desired label. This function attempts to handle the change in /// state variable names that occurred in OpenSim version 4.0; for example, /// if you search for `<coord-name>/speed` and it is not found, then this /// function looks for `<coord-name>_u`. If you search for /// `<muscle>/activation` and it is not found, then this function looks for /// `<muscle>.activation`. This function returns -1 if the desired label is /// not found. static int findStateLabelIndex( const Array<std::string>& labels, const std::string& desired); /// @copydoc findStateLabelIndex() static int findStateLabelIndex( const std::vector<std::string>& labels, const std::string& desired); /// Lowpass filter the data in a TimeSeriesTable at a provided cutoff /// frequency. If padData is true, then the data is first padded with pad() /// using numRowsToPrependAndAppend = table.getNumRows() / 2. /// The filtering is performed with Signal::LowpassIIR() static void filterLowpass(TimeSeriesTable& table, double cutoffFreq, bool padData = false); /// Pad each column by the number of rows specified. The padded data is /// obtained by reflecting and negating the data in the table. /// Postcondition: the number of rows is table.getNumRows() + 2 * /// numRowsToPrependAndAppend. static void pad(TimeSeriesTable& table, int numRowsToPrependAndAppend); /// Resample (interpolate) the table at the provided times. In general, a /// 5th-order GCVSpline is used as the interpolant; a lower order is used if /// the table has too few points for a 5th-order spline. Alternatively, you /// can provide a different function type as a template argument; currently, /// the only other supported function is PiecewiseLinearFunction. /// @throws Exception if new times are /// not within existing initial and final times, if the new times are /// decreasing, or if getNumTimes() < 2. template <typename TimeVector, typename FunctionType = GCVSpline> static TimeSeriesTable resample( const TimeSeriesTable& in, const TimeVector& newTime); /// Resample the table using the given time interval (using resample()). /// The new final time is not guaranteed to match the original final /// time. template <typename FunctionType = GCVSpline> static TimeSeriesTable resampleWithInterval( const TimeSeriesTable& in, double interval); /// Same as resampleWithInterval() but the interval may be reduced /// to ensure the number of sampling points does not exceed /// Storage::MAX_RESAMPLE_SIZE. template <typename FunctionType = GCVSpline> static TimeSeriesTable resampleWithIntervalBounded( const TimeSeriesTable& in, double interval); private: static int findStateLabelIndexInternal(const std::string* begin, const std::string* end, const std::string& desired); }; } // namespace OpenSim #endif // OPENSIM_TABLEUTILITIES_H_
52.118182
80
0.626025
75fc575ca77bab29d7c0fda21a231939d742b495
1,448
php
PHP
templates/list/read.php
pendi/financial_monitoring
8b83aaafcc47c6037c2207f8601c34a24cb47a97
[ "MIT" ]
null
null
null
templates/list/read.php
pendi/financial_monitoring
8b83aaafcc47c6037c2207f8601c34a24cb47a97
[ "MIT" ]
null
null
null
templates/list/read.php
pendi/financial_monitoring
8b83aaafcc47c6037c2207f8601c34a24cb47a97
[ "MIT" ]
null
null
null
<?php use \App\Component\Form; use \Norm\Schema\String; $form = Form::create()->of($entry); ?> <h2><?php echo preg_replace('/\B([A-Z])/', ' $1', f('controller.name')); ?></h2> <form method="post" role="form"> <p> <a href="<?php echo f('controller.url') ?>" class="button round">List</a> <a href="<?php echo f('controller.url', '/:id/update') ?>" class="button round">Update</a> <a href="<?php echo f('controller.url', '/:id/delete') ?>" class="button round alert">Delete</a> </p> <fieldset> <div class="row"> <div class="span-12"> <label>Note</label> <textarea readonly><?php echo $entry['keterangan'] ?></textarea> </div> </div> <div class="row"> <div class="span-12"> <label>Income</label> <input type="text" value="<?php echo $entry['pemasukan'] ?>" readonly> </div> </div> <div class="row"> <div class="span-12"> <label>Expense</label> <input type="text" value="<?php echo $entry['pengeluaran'] ?>" readonly> </div> </div> <div class="row"> <div class="span-12"> <label>Date</label> <input type="text" id="datepicker" size="15" value="<?php echo $entry['tanggal'] ?>" readonly> </div> </div> </fieldset> </form>
32.909091
110
0.486188
40a6876acc7ec1992c99b83aa02ec406ba2239a1
9,644
py
Python
api/radiam-osf/radiam_api.py
usask-rc/radiam
bfa38fd33e211b66e30e453a717c5f216e848cb2
[ "MIT" ]
2
2020-02-01T20:41:28.000Z
2020-02-03T20:57:59.000Z
api/radiam-osf/radiam_api.py
usask-rc/radiam
bfa38fd33e211b66e30e453a717c5f216e848cb2
[ "MIT" ]
10
2020-04-20T15:52:49.000Z
2020-04-30T18:03:09.000Z
api/radiam-osf/radiam_api.py
usask-rc/radiam
bfa38fd33e211b66e30e453a717c5f216e848cb2
[ "MIT" ]
null
null
null
import requests import json import time import os import urllib import logging class RadiamAPI(object): def __init__(self, **kwargs): self.logger = None self.osf = False self.baseurl = "http://radiamapi:8000" # Docker API container self.headers = { "Content-Type": "application/json", "Accept": "application/json" } self.authtokens = {} for key, value in kwargs.items(): setattr(self, key, value) if self.baseurl: if not self.baseurl.startswith('http'): self.baseurl = "http://" + self.baseurl self.endpoints = { "osfconfigs": self.baseurl + "/api/useragents/osf_configs/", "projects": self.baseurl + "/api/projects/", "locations": self.baseurl + "/api/locations/", "locationtypes": self.baseurl + "/api/locationtypes/", "useragents": self.baseurl + "/api/useragents/" } self.refresh_token() def setLogger(self, logger): self.logger = logger def log(self, message): # The API class will only log error messages if self.logger: self.logger.error(message) def refresh_token(self): if self.osf: resp = requests.get(self.endpoints.get("useragents") + self.useragent + '/tokens/new/') if resp.status_code != 200: self.log("Unable to refresh auth tokens {}:\n{}\n".format(resp.status_code, resp.text)) else: resp_obj = json.loads(resp.text) if resp_obj.get("access_token", None) != None: self.log("New access token: {}".format(resp_obj["access_token"])) self.authtokens["access"] = resp_obj["access_token"] else: self.log("Unable to obtain access token {}:\n{}\n".format(resp.status_code, resp.text)) if resp_obj.get("refresh_token", None) != None: self.log("New refresh token: {}".format(resp_obj["refresh_token"])) self.authtokens["refresh"] = resp_obj["refresh_token"] else: self.log("Unable to obtain refresh token {}:\n{}\n".format(resp.status_code, resp.text)) def get_bearer_token(self): if self.authtokens.get("access", None) and self.authtokens.get("access") != "": return self.authtokens.get("access") return "novalidtoken" def get_osf_useragents(self): """ Get the OSF endpoint data from the Radiam API """ resp = requests.get(self.endpoints.get("osfconfigs")) if resp.status_code != 200: self.log("Unable to get list of OSF user agents {}:\n{}\n".format(resp.status_code, resp.text)) return None else: return json.loads(resp.text) def api_get(self, url, retries=1): if retries <= 0: self.log("Ran out of retries to connect to Radiam API") return None get_headers = self.headers get_headers["Authorization"] = "Bearer " + self.get_bearer_token() try: resp = requests.get(url, headers=get_headers) except: resp = { "status_code": 0 } if resp.status_code == 403: response_json = json.loads(resp.text) if response_json["code"] == "token_not_valid": self.refresh_token() return self.api_get(url=url, retries=retries - 1) else: self.log("Unauthorized request {}:\n{}\n".format(resp.status_code, resp.text)) elif resp.status_code == 200: return json.loads(resp.text) elif resp.status_code == 429: # untested until ADM-562 is resolved response_json = json.loads(resp.text) time.sleep(int(response_json.get("retry-after", "3")) + 1) self.api_get(url, retries=1) else: self.log("Radiam API error while getting from: {} with code {} and error {} \n".format(url, resp.status_code, resp.text)) return None def api_post(self, url, body, retries=1): if retries <= 0: self.log("Ran out of retries to connect to Radiam API") return None post_headers = self.headers post_headers["Authorization"] = "Bearer " + self.get_bearer_token() try: resp = requests.post(url, headers=post_headers, data=body) except: resp = { "status_code": 0 } if resp.status_code == 403: response_json = json.loads(resp.text) if response_json["code"] == "token_not_valid": self.refresh_token() return self.api_post(url=url, body=body, retries=retries - 1) else: self.log("Unauthorized request {}:\n{}\n".format(resp.status_code, resp.text)) elif resp.status_code == 200 or resp.status_code == 201: # Indicates the post was successful and there is content to return return json.loads(resp.text) elif resp.status_code == 429: # untested until ADM-562 is resolved response_json = json.loads(resp.text) time.sleep(int(response_json.get("retry-after", "3")) + 1) self.api_post(url, body, retries=1) else: self.log("Radiam API error {}:\n{}\n".format(resp.status_code, resp.text)) return None def api_post_bulk(self, url, body, retries=1): if retries <= 0: self.log("Ran out of retries to connect to Radiam API") return None, False post_headers = self.headers post_headers["Authorization"] = "Bearer " + self.get_bearer_token() try: resp = requests.post(url, headers=post_headers, json=body) except: resp = { "status_code": 0 } if resp.status_code == 403: response_json = json.loads(resp.text) if response_json["code"] == "token_not_valid": self.refresh_token() return self.api_post_bulk(url=url, body=body, retries=retries - 1) else: self.log("Unauthorized request {}:\n{}\n".format(resp.status_code, resp.text)) elif resp.status_code == 200 or resp.status_code == 201: # Indicates the post was successful and there is content to return return json.loads(resp.text), True else: self.log("Radiam API error {}:\n{}\n".format(resp.status_code, resp.text)) return resp.text, False def api_delete(self, url, retries=1): if retries <= 0: self.log("Ran out of retries to connect to Radiam API") return None delete_headers = self.headers delete_headers["Authorization"] = "Bearer " + self.get_bearer_token() try: resp = requests.delete(url, headers=delete_headers) except: resp = { "status_code": 0 } if resp.status_code == 403: response_json = json.loads(resp.text) if response_json["code"] == "token_not_valid": self.refresh_token() return self.api_delete(url=url, retries=retries - 1) else: self.log("Unauthorized request {}:\n{}\n".format(resp.status_code, resp.text)) elif resp.status_code == 200 or resp.status_code == 204: # 200 = delete OK # 204 = delete OK, no content to deliver return True else: self.log("Radiam API error {}:\n{}\n".format(resp.status_code, resp.text)) return None def agent_checkin(self, body, checkin_url): if body is None: return None if isinstance(body, dict): body = json.dumps(body) return self.api_post(checkin_url, body) def create_document(self, index_url, body): if body is None: return None if isinstance(body, dict): body = json.dumps(body) index_url += "docs/" return self.api_post(index_url, body) def create_document_bulk(self, index_url, body): if body is None: return None, False if isinstance(body, dict): body = json.dumps(body) index_url += "docs/" return self.api_post_bulk(index_url, body) def delete_document(self, index_url, id): if id is None: return None index_url += "docs/" + urllib.parse.quote(id) return self.api_delete(index_url) def get_project_endpoint(self, project_id): return self.endpoints.get("projects") + project_id + "/" def search_endpoint_by_path(self, index_url, path): return self.search_endpoint_by_fieldname(index_url, path, "path.keyword") def search_endpoint_by_fieldname(self, index_url, target, fieldname): if fieldname is None: self.log(target + " field name is missing for endpoint search") return None if target is None: self.log(fieldname + " argument is missing for endpoint search") return None index_url = index_url + "search/" body = { "query" : { "bool" : { "filter" : { "term" : { fieldname : target } } } } } return self.api_post(index_url, json.dumps(body))
40.864407
133
0.560037
8aadf28902891575c066cbb2aad039d5d94414eb
1,169
swift
Swift
ProjectIOS/ProjectIOS/CauHoi.swift
CANSA-team/IOS
5c0d2da74d4d72fe7eed6e24bf402e667c728d09
[ "Apache-2.0" ]
null
null
null
ProjectIOS/ProjectIOS/CauHoi.swift
CANSA-team/IOS
5c0d2da74d4d72fe7eed6e24bf402e667c728d09
[ "Apache-2.0" ]
null
null
null
ProjectIOS/ProjectIOS/CauHoi.swift
CANSA-team/IOS
5c0d2da74d4d72fe7eed6e24bf402e667c728d09
[ "Apache-2.0" ]
null
null
null
//. đối tượng câu hỏi // CauHoi.swift // ProjectIOS // // Created by Vu Minh Chuan on 4/16/21. // import Foundation class CauHoi { var hinhAnh:String = "hinhAnh" var cauHoi:String = "cauHoi" var cauTraLoi:[String] = ["cauTraLoi"] var dapAn:Int = 0 init() { } init(_ hinhAnh:String,_ cauHoi:String,_ cauTraLoi:[String],_ dapAn:Int){ self.hinhAnh = hinhAnh; self.cauHoi = cauHoi; self.cauTraLoi = cauTraLoi; self.dapAn = dapAn; } func getHinhAnh() -> String { return self.hinhAnh; } func setHinhAnh(_ hinhAnh:String) -> Void { self.hinhAnh = hinhAnh; } func getCauTraLoi() -> [String] { return self.cauTraLoi; } func setCauTraLoi(_ cauTraLoi:[String]) -> Void { self.cauTraLoi = cauTraLoi; } func getCauHoi() -> String { return self.cauHoi; } func setCauHoi(_ cauHoi:String) -> Void { self.cauHoi = cauHoi; } func getDapAn() -> Int { return self.dapAn; } func setDapAn(_ dapAn:Int) -> Void { self.dapAn = dapAn; } }
20.155172
76
0.545766
0bcbf703bb6d39b7d7300ee47950bbee99bccb39
1,256
js
JavaScript
src/main/extension/implant-manual.js
mike10004/chrome-cookie-implant
c82b5da7655084675f13ea58bccba3459e6ceeb0
[ "MIT" ]
null
null
null
src/main/extension/implant-manual.js
mike10004/chrome-cookie-implant
c82b5da7655084675f13ea58bccba3459e6ceeb0
[ "MIT" ]
1
2016-12-14T23:17:03.000Z
2016-12-14T23:17:03.000Z
src/main/extension/implant-manual.js
mike10004/chrome-cookie-implant
c82b5da7655084675f13ea58bccba3459e6ceeb0
[ "MIT" ]
null
null
null
document.addEventListener('DOMContentLoaded', function() { var exampleCookie = { url: 'https://www.example.com/', name: 'foo' }; var cookieJsonTextArea = document.getElementById('cookie-json'); cookieJsonTextArea.innerText = JSON.stringify(exampleCookie); var messageDiv = document.getElementById('message'); var implantButton = document.getElementById('implant'); implantButton.onclick = function() { var cookiesJson = cookieJsonTextArea.value; var cookieOrCookies; try { cookieOrCookies = JSON.parse(cookiesJson); } catch (err) { console.info("json parse error", err); messageDiv.innerText = 'JSON parse error: ' + err.message; } console.debug("implant button onclick", cookieOrCookies); var cookies = cookieOrCookies; if (!Array.isArray(cookieOrCookies)) { cookies = [cookieOrCookies]; } var url = 'manage.html?'; cookies.forEach(cookie => { var cookieJson = JSON.stringify(cookie); var cookieJsonEncoded = encodeURIComponent(cookieJson); url += ('implant=' + cookieJsonEncoded + '&'); }); location.href = url; }; });
39.25
70
0.609873
d4647a0843522636d76edc135cc406f924fbe0c5
2,548
rs
Rust
src/bounded_rand.rs
sortalongo/gas_sim
decc77477631efe552f03baa660036fbeb906e93
[ "MIT" ]
null
null
null
src/bounded_rand.rs
sortalongo/gas_sim
decc77477631efe552f03baa660036fbeb906e93
[ "MIT" ]
null
null
null
src/bounded_rand.rs
sortalongo/gas_sim
decc77477631efe552f03baa660036fbeb906e93
[ "MIT" ]
null
null
null
use rand::{Rng}; use super::{CustomFloat, Particle, Vector}; pub trait BoundedRand { /// pseudo-extends the Rand typeclass with the ability to specify bounds /// for the generated type. Bounds are assumed to be closed. fn rand <R: Rng>(rng: &mut R, lower: &Self, upper: &Self) -> Self; } impl BoundedRand for CustomFloat { fn rand <R: Rng>(rng: &mut R, lower: &CustomFloat, upper: &CustomFloat) -> CustomFloat { if (upper - lower).eq(&0.) { *lower } else { let gen = rng.gen::<CustomFloat>(); gen * (upper-lower) + lower } } } impl BoundedRand for Vector { fn rand <R: Rng>(rng: &mut R, lower: &Vector, upper: &Vector) -> Vector { let &Vector((min1, min2)) = lower; let &Vector((max1, max2)) = upper; Vector(( BoundedRand::rand(rng, &min1, &max1), BoundedRand::rand(rng, &min2, &max2) )) } } impl BoundedRand for Particle { fn rand <R: Rng>(rng: &mut R, lower: &Particle, upper: &Particle) -> Particle { Particle { id: rng.gen(), x: BoundedRand::rand(rng, &lower.x, &upper.x), v: BoundedRand::rand(rng, &lower.v, &upper.v), r: BoundedRand::rand(rng, &lower.r, &upper.r), m: BoundedRand::rand(rng, &lower.m, &upper.m) } } } #[cfg(test)] extern crate quickcheck; #[cfg(test)] mod tests { use rand::thread_rng; use super::quickcheck::quickcheck; use super::*; use ::{CustomFloat, Vector}; #[test] fn custom_float_is_bounded() { fn prop(bound1: CustomFloat, bound2: CustomFloat) -> bool { let mut rng = thread_rng(); let min = bound1.min(bound2); let max = bound1.max(bound2); let mut correct = true; for _ in 1..50 { let gen = BoundedRand::rand(&mut rng, &min, &max); correct |= gen <= max; correct |= gen >= min; } correct } quickcheck(prop as fn(CustomFloat, CustomFloat) -> bool); } #[test] fn custom_float_can_be_constant() { let mut rng = thread_rng(); let min = 1.; let max = 1.; for _ in 1..50 { let gen = BoundedRand::rand(&mut rng, &min, &max); assert!(gen <= max); assert!(gen >= min); } } #[test] fn vector_is_bounded() { let mut rng = thread_rng(); let min = Vector((-2e4, -8.77e7)); let max = Vector((5.6e8, 3.2e3)); for _ in 1..50 { let Vector(gen) = BoundedRand::rand(&mut rng, &min, &max); assert!(gen.0 <= (max.0).0); assert!(gen.1 <= (max.0).1); assert!(gen.0 >= (min.0).0); assert!(gen.1 >= (min.0).1); } } }
24.266667
90
0.571036
81e889ed319956912ece21dcbb395a0e33e52779
257
asm
Assembly
programs/oeis/140/A140504.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/140/A140504.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/140/A140504.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A140504: a(n) = 2^n + 4. ; 5,6,8,12,20,36,68,132,260,516,1028,2052,4100,8196,16388,32772,65540,131076,262148,524292,1048580,2097156,4194308,8388612,16777220,33554436,67108868,134217732,268435460,536870916,1073741828 mov $1,2 pow $1,$0 add $1,4 mov $0,$1
32.125
190
0.7393
c733aa032e00c14521fab69e99399c01a990dfb7
7,839
kt
Kotlin
src/app/src/main/java/com/huawei/faceoffdresstrial/kotlin/repo/RoomRepo.kt
huaweicodelabs/FaceOffDressTrial
6d02c5569a9f95d22115e95555761b9be95d44a4
[ "Apache-2.0" ]
null
null
null
src/app/src/main/java/com/huawei/faceoffdresstrial/kotlin/repo/RoomRepo.kt
huaweicodelabs/FaceOffDressTrial
6d02c5569a9f95d22115e95555761b9be95d44a4
[ "Apache-2.0" ]
null
null
null
src/app/src/main/java/com/huawei/faceoffdresstrial/kotlin/repo/RoomRepo.kt
huaweicodelabs/FaceOffDressTrial
6d02c5569a9f95d22115e95555761b9be95d44a4
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020. Huawei Technologies Co., Ltd. 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. */ package com.huawei.faceoffdresstrial.kotlin.repo import android.content.Context import com.huawei.faceoffdresstrial.kotlin.common.Constants import com.huawei.faceoffdresstrial.kotlin.common.Util import com.huawei.faceoffdresstrial.kotlin.model.DressData import java.util.* class RoomRepo { private val DRESS_TYPE_1_DRESS_DATA_1_SETX_1 = 333 private val DRESS_TYPE_1_DRESS_DATA_1_SETY_1 = 0 private val DRESS_TYPE_1_DRESS_DATA_1_SETX_2 = 695 private val DRESS_TYPE_1_DRESS_DATA_1_SETY_2 = 550 private val DRESS_TYPE_1_DRESS_DATA_2_SETX_1 = 333 private val DRESS_TYPE_1_DRESS_DATA_2_SETY_1 = 0 private val DRESS_TYPE_1_DRESS_DATA_2_SETX_2 = 682 private val DRESS_TYPE_1_DRESS_DATA_2_SETY_2 = 533 private val DRESS_TYPE_2_DRESS_DATA_1_SETX_1 = 321 private val DRESS_TYPE_2_DRESS_DATA_1_SETY_1 = 290 private val DRESS_TYPE_2_DRESS_DATA_1_SETX_2 = 742 private val DRESS_TYPE_2_DRESS_DATA_1_SETY_2 = 752 private val DRESS_TYPE_2_DRESS_DATA_2_SETX_1 = 379 private val DRESS_TYPE_2_DRESS_DATA_2_SETY_1 = 290 private val DRESS_TYPE_2_DRESS_DATA_2_SETX_2 = 717 private val DRESS_TYPE_2_DRESS_DATA_2_SETY_2 = 779 private val DRESS_TYPE_3_DRESS_DATA_6_SETX_1 = 333 private val DRESS_TYPE_3_DRESS_DATA_6_SETY_1 = 0 private val DRESS_TYPE_3_DRESS_DATA_6_SETX_2 = 679 private val DRESS_TYPE_3_DRESS_DATA_6_SETY_2 = 550 private val DRESS_TYPE_3_DRESS_DATA_8_SETX_1 = 333 private val DRESS_TYPE_3_DRESS_DATA_8_SETY_1 = 0 private val DRESS_TYPE_3_DRESS_DATA_8_SETX_2 = 695 private val DRESS_TYPE_3_DRESS_DATA_8_SETY_2 = 550 private val DRESS_TYPE_4_DRESS_DATA_1_SETX_1 = 363 private val DRESS_TYPE_4_DRESS_DATA_1_SETY_1 = 55 private val DRESS_TYPE_4_DRESS_DATA_1_SETX_2 = 705 private val DRESS_TYPE_4_DRESS_DATA_1_SETY_2 = 615 private val DRESS_TYPE_4_DRESS_DATA_2_SETX_1 = 320 private val DRESS_TYPE_4_DRESS_DATA_2_SETY_1 = 60 private val DRESS_TYPE_4_DRESS_DATA_2_SETX_2 = 770 private val DRESS_TYPE_4_DRESS_DATA_2_SETY_2 = 633 fun addDressDataList(dressType: Int, context: Context): List<DressData> { val dressDataList: MutableList<DressData> = ArrayList() dressDataList.clear() if (dressType == Constants.TYPE_ONE) { val dressData1 = DressData() dressData1.id = Constants.ID_ONE dressData1.dressType = Constants.TYPE_ONE dressData1.dressDataX1 = DRESS_TYPE_1_DRESS_DATA_1_SETX_1 dressData1.dressDataY1 = DRESS_TYPE_1_DRESS_DATA_1_SETY_1 dressData1.dressDataX2 = DRESS_TYPE_1_DRESS_DATA_1_SETX_2 dressData1.dressDataY2 = DRESS_TYPE_1_DRESS_DATA_1_SETY_2 dressData1.bitmap = Util.Companion.getImageFromAssetsFile(context, mShirt_One) dressDataList.add(dressData1) val dressData2 = DressData() dressData2.id = Constants.ID_TWO dressData2.dressType = Constants.TYPE_ONE dressData2.dressDataX1 = DRESS_TYPE_1_DRESS_DATA_2_SETX_1 dressData2.dressDataY1 = DRESS_TYPE_1_DRESS_DATA_2_SETY_1 dressData2.dressDataX2 = DRESS_TYPE_1_DRESS_DATA_2_SETX_2 dressData2.dressDataY2 = DRESS_TYPE_1_DRESS_DATA_2_SETY_2 dressData2.bitmap = Util.Companion.getImageFromAssetsFile(context, mShirt_Two) dressDataList.add(dressData2) } else if (dressType == Constants.TYPE_TWO) { val dressData1 = DressData() dressData1.id = Constants.ID_ONE dressData1.dressType = Constants.TYPE_TWO dressData1.dressDataX1 = DRESS_TYPE_2_DRESS_DATA_1_SETX_1 dressData1.dressDataY1 = DRESS_TYPE_2_DRESS_DATA_1_SETY_1 dressData1.dressDataX2 = DRESS_TYPE_2_DRESS_DATA_1_SETX_2 dressData1.dressDataY2 = DRESS_TYPE_2_DRESS_DATA_1_SETY_2 dressData1.bitmap = Util.Companion.getImageFromAssetsFile(context, mKids_1) dressDataList.add(dressData1) val dressData2 = DressData() dressData2.id = Constants.ID_TWO dressData2.dressType = Constants.TYPE_TWO dressData2.dressDataX1 = DRESS_TYPE_2_DRESS_DATA_2_SETX_1 dressData2.dressDataY1 = DRESS_TYPE_2_DRESS_DATA_2_SETY_1 dressData2.dressDataX2 = DRESS_TYPE_2_DRESS_DATA_2_SETX_2 dressData2.dressDataY2 = DRESS_TYPE_2_DRESS_DATA_2_SETY_2 dressData2.bitmap = Util.Companion.getImageFromAssetsFile(context, mKids_2) dressDataList.add(dressData2) } else if (dressType == Constants.TYPE_THREE) { val dressData6 = DressData() dressData6.id = Constants.ID_TWO dressData6.dressType = Constants.TYPE_THREE dressData6.dressDataX1 = DRESS_TYPE_3_DRESS_DATA_6_SETX_1 dressData6.dressDataY1 = DRESS_TYPE_3_DRESS_DATA_6_SETY_1 dressData6.dressDataX2 = DRESS_TYPE_3_DRESS_DATA_6_SETX_2 dressData6.dressDataY2 = DRESS_TYPE_3_DRESS_DATA_6_SETY_2 dressData6.bitmap = Util.Companion.getImageFromAssetsFile(context, mImage_One) dressDataList.add(dressData6) val dressData8 = DressData() dressData8.id = Constants.ID_EIGHT dressData8.dressType = Constants.TYPE_THREE dressData8.dressDataX1 = DRESS_TYPE_3_DRESS_DATA_8_SETX_1 dressData8.dressDataY1 = DRESS_TYPE_3_DRESS_DATA_8_SETY_1 dressData8.dressDataX2 = DRESS_TYPE_3_DRESS_DATA_8_SETX_2 dressData8.dressDataY2 = DRESS_TYPE_3_DRESS_DATA_8_SETY_2 dressData8.bitmap = Util.Companion.getImageFromAssetsFile(context, mImage_Two) dressDataList.add(dressData8) } else if (dressType == Constants.TYPE_FOUR) { val dressData1 = DressData() dressData1.id = Constants.ID_ONE dressData1.dressDataX1 = DRESS_TYPE_4_DRESS_DATA_1_SETX_1 dressData1.dressDataY1 = DRESS_TYPE_4_DRESS_DATA_1_SETY_1 dressData1.dressDataX2 = DRESS_TYPE_4_DRESS_DATA_1_SETX_2 dressData1.dressDataY2 = DRESS_TYPE_4_DRESS_DATA_1_SETY_2 dressData1.bitmap = Util.Companion.getImageFromAssetsFile(context, mTShirt_One) dressDataList.add(dressData1) val dressData2 = DressData() dressData2.id = Constants.ID_TWO dressData2.dressDataX1 = DRESS_TYPE_4_DRESS_DATA_2_SETX_1 dressData2.dressDataY1 = DRESS_TYPE_4_DRESS_DATA_2_SETY_1 dressData2.dressDataX2 = DRESS_TYPE_4_DRESS_DATA_2_SETX_2 dressData2.dressDataY2 = DRESS_TYPE_4_DRESS_DATA_2_SETY_2 dressData2.bitmap = Util.Companion.getImageFromAssetsFile(context, mTShirt_Two) dressDataList.add(dressData2) } return dressDataList } companion object { private const val mShirt_One = "shirt_1.png" private const val mShirt_Two = "shirt_2.png" private const val mTShirt_Two = "tshirt_2.png" private const val mTShirt_One = "tshirt_1.png" private const val mKids_1 = "kids_1.PNG" private const val mKids_2 = "kids_2.PNG" private const val mImage_One = "suits_2.png" private const val mImage_Two = "suits_1.png" } }
51.572368
91
0.735425
72f9daf24cf9aba4c1ff3fda5ac2c5792e5b22d3
411
html
HTML
tmpl/discord.html
epictaco302/hidens-website
5f36ab3784aad9e2c343acfb26532d27acee7258
[ "BSD-3-Clause" ]
6
2022-01-18T13:34:37.000Z
2022-03-25T14:06:51.000Z
tmpl/discord.html
epictaco302/hidens-website
5f36ab3784aad9e2c343acfb26532d27acee7258
[ "BSD-3-Clause" ]
2
2022-01-27T16:43:15.000Z
2022-03-24T11:28:09.000Z
tmpl/discord.html
HIDEN64/hidens-website
5f36ab3784aad9e2c343acfb26532d27acee7258
[ "BSD-3-Clause" ]
null
null
null
{%- extends 'base.html' -%} {%- block meta -%} <meta name=description content="HIDEN64's Discord server."/> <meta http-equiv=refresh content="5; url='https://discord.gg/zH9kMEzEYM" /> {%- endblock -%} {%- block content -%} <p>You should be redirected to my Discord server in 5 seconds.</p> <p>If you aren't redirected, click <a href=https://discord.gg/zH9kMEzEYM>here</a>.</p> {%- endblock -%}
31.615385
87
0.644769
5d187b856a1f6bbec529d5a6a53b14810b2b866a
2,605
sql
SQL
projects/data-core/src/test/resources/com/lbibera/tradebutler/datacore/corporation/repository/CorporationRepositoryTest.findByIdShouldReturnCorrectCorporation.sql
hack-of-all-codes/project-tradebutler
fd50a08ccfef25d631eab3482e365964ecffe668
[ "Apache-2.0" ]
1
2017-05-20T23:07:42.000Z
2017-05-20T23:07:42.000Z
projects/data-core/src/test/resources/com/lbibera/tradebutler/datacore/corporation/repository/CorporationRepositoryTest.findByIdShouldReturnCorrectCorporation.sql
hack-of-all-codes/project-tradebutler
fd50a08ccfef25d631eab3482e365964ecffe668
[ "Apache-2.0" ]
21
2017-03-26T02:59:16.000Z
2017-04-15T04:25:17.000Z
projects/data-core/src/test/resources/com/lbibera/tradebutler/datacore/corporation/repository/CorporationRepositoryTest.findByIdShouldReturnCorrectCorporation.sql
hack-of-all-codes/project-tradebutler
fd50a08ccfef25d631eab3482e365964ecffe668
[ "Apache-2.0" ]
null
null
null
DELETE FROM historical_price; DELETE FROM stock; DELETE FROM corporation; INSERT INTO corporation(id, name, description, incorporation_date, sector, sub_sector) VALUES (1, 'San Miguel Corporation', 'San Miguel Corporation (SMC) was originally founded in 1890 as a single-product brewery in the Philippines. The Company has since then transformed itself from a beverage, food and packaging business into fuel and oil, energy, power, infrastructure, telecommunications and banking industries. The Company''s extensive product portfolio includes beer; liquor; non-alcoholic beverages; poultry; animal feeds; flour, fresh and processed meats; dairy products; coffee; various packaging products; and full range of refined petroleum products. SMC has strategic partnerships with international companies, among them are Kirin Holdings Company, Limited for beer; Hormel Foods International Corporation for processed meats; Nihon Yamamura Glass Company, Ltd. for packaging products; Padma Fund L.P. for toll roads; and Super Coffee Corporation Pte Ltd for coffee. The Company''s subsidiaries include San Miguel Brewery, Inc.; Ginebra San Miguel, Inc.; San Miguel Pure Foods Company, Inc.; and Petron Corporation. Source: SEC Form 17-A (2015)', '1913-08-21','HOLDING_FIRMS', 'HOLDING_FIRMS'), (2, 'BDO Unibank, Inc.', 'BDO Unibank Inc. (BDO), originally known as Acme Savings Bank, was acquired by the SM Group in 1976. BDO listed its shares on the Philippine Stock Exchange on May 21, 2002. The Company merged with Equitable PCI Bank in May 2007. BDO offers a complete array of products and services, i.e. retail banking; lending (corporate, commercial, consumer, and SME); treasury; trust; credit cards; corporate cash management; and remittances. Through its subsidiaries, the Company offers leasing and financing; investment banking; private banking; bancassurance; insurance brokerage; and stock brokerage services. The Company''s local subsidiaries include BDO Private Bank, Inc.; BDO Leasing and Finance, Inc.; BDO Elite Savings Bank, Inc.; BDO Capital & Investment Corporation; PCIB Securities, Inc.; and BDO Insurance Brokers, Inc. The Company also has foreign subsidiaries in Hong Kong; USA; Europe; Japan; and Canada. The Company''s associates are Manila North Tollways Corporation; SM Keppel Land, Inc.; Generali Pilipinas Holdings, Inc.; Northpine Land Incorporated; and Taal Land, Inc. As of December 31, 2015, BDO has 1,028 operating domestic branches, one branch in Hong Kong and 3,195 ATMs and 191 cash accept machines. Source: SEC Form 17-A (2015)', '1968-01-02', 'FINANCIALS','BANKS');
173.666667
478
0.789635
ad14d27fd642716330628de241dac49269d06ebe
667
swift
Swift
DemoApp/DemoArcade/DemoArcade/LoadingViewController.swift
psaitu/swift-arcade
fa77cfb1b41a48ec3dbb84010d71e2b8bd8c50cb
[ "MIT" ]
492
2020-03-15T20:42:55.000Z
2022-03-31T04:40:12.000Z
DemoApp/DemoArcade/DemoArcade/LoadingViewController.swift
dlsolution/swift-arcade
35474e8b37052d310af8c193d7d4ebb473caa9ee
[ "MIT" ]
2
2021-01-14T08:05:06.000Z
2021-04-02T20:42:40.000Z
DemoApp/DemoArcade/DemoArcade/LoadingViewController.swift
dlsolution/swift-arcade
35474e8b37052d310af8c193d7d4ebb473caa9ee
[ "MIT" ]
98
2020-05-21T12:04:15.000Z
2022-03-29T10:37:13.000Z
// // LoadingViewController.swift // DemoArcade // // Created by Jonathan Rasmusson Work Pro on 2020-04-03. // Copyright © 2020 Rasmusson Software Consulting. All rights reserved. // import UIKit class LoadingViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() layout() } func layout() { view.backgroundColor = .systemYellow let label = makeLabel(withTitle: "Loading...") view.addSubview(label) label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true } }
23
83
0.682159
2e119f99172f7f89fbe4d6ff5dd06610152574ca
559
kt
Kotlin
app/src/main/java/nawrot/mateusz/timesup/di/ViewModelModule.kt
mateusz-nawrot/TimesUp
3110e0649ee63e0c9d43d6092030d19d74acdee7
[ "MIT" ]
1
2020-04-20T21:36:21.000Z
2020-04-20T21:36:21.000Z
app/src/main/java/nawrot/mateusz/timesup/di/ViewModelModule.kt
mateusz-nawrot/TimesUp
3110e0649ee63e0c9d43d6092030d19d74acdee7
[ "MIT" ]
null
null
null
app/src/main/java/nawrot/mateusz/timesup/di/ViewModelModule.kt
mateusz-nawrot/TimesUp
3110e0649ee63e0c9d43d6092030d19d74acdee7
[ "MIT" ]
null
null
null
package nawrot.mateusz.timesup.di import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import dagger.Binds import dagger.Module import dagger.multibindings.IntoMap import nawrot.mateusz.timesup.app.home.HomeViewModel @Module abstract class ViewModelModule { @Binds abstract fun bindViewModelFactory(westwingViewModelFactory: TimesUpViewModelFactory): ViewModelProvider.Factory @Binds @IntoMap @ViewModelKey(HomeViewModel::class) abstract fun bindHomeViewModel(homeViewModel: HomeViewModel): ViewModel }
25.409091
115
0.822898
db562cd5d36b60dc1e32144a3bb9399b39a4cc45
568
swift
Swift
Example/Pods/MFL-Common/MFL-Common/Classes/Session.swift
FWAlex/MFLToxicMessages
03de4aacc15c269014d28da8226d6165c73091c7
[ "MIT" ]
null
null
null
Example/Pods/MFL-Common/MFL-Common/Classes/Session.swift
FWAlex/MFLToxicMessages
03de4aacc15c269014d28da8226d6165c73091c7
[ "MIT" ]
null
null
null
Example/Pods/MFL-Common/MFL-Common/Classes/Session.swift
FWAlex/MFLToxicMessages
03de4aacc15c269014d28da8226d6165c73091c7
[ "MIT" ]
null
null
null
// // Session.swift // MFLHalsa // // Created by Alex Miculescu on 07/07/2017. // Copyright © 2017 Future Workshops. All rights reserved. // import Foundation public protocol Session { var id : String { get } var title : String { get } var startDate : Date { get } var endDate : Date { get } var teamMemberId : String { get } var teamMemberFirstName : String { get } var teamMemberLastName : String { get } var teamMemberImageUrlString : String { get } var isCancelled : Bool { get } var messageGroupId : String { get } }
24.695652
59
0.649648
04ae2ad0db218fdbd1ccf057878f82b444c4cb89
3,551
html
HTML
projects/go-style-guide/src/app/features/ui-kit/components/table-docs/components/table-pagination/table-pagination.component.html
AlexOverbeck/goponents
e34f312225041544d928eb152da84b40d08c2a52
[ "MIT" ]
null
null
null
projects/go-style-guide/src/app/features/ui-kit/components/table-docs/components/table-pagination/table-pagination.component.html
AlexOverbeck/goponents
e34f312225041544d928eb152da84b40d08c2a52
[ "MIT" ]
null
null
null
projects/go-style-guide/src/app/features/ui-kit/components/table-docs/components/table-pagination/table-pagination.component.html
AlexOverbeck/goponents
e34f312225041544d928eb152da84b40d08c2a52
[ "MIT" ]
null
null
null
<section class="go-container"> <go-card class="go-column go-column--100"> <ng-container go-card-header> <h2 class="go-heading-2">Implementing Paging</h2> </ng-container> <div class="go-container" go-card-content> <div class="go-column go-column--100"> <p class="go-body-copy"> By default, pagination is enabled. To configure the paging setup, you can pass a <code class="code-block--inline">GoTablePageConfig</code> class to <code class="code-block--inline">pageConfig</code> on the <code class="code-block--inline">GoTableConfig</code> class. </p> <code [highlight]="pageConfig"></code> </div> <div class="go-column go-column--100"> <h4 class="go-heading-4">offset</h4> <p class="go-body-copy"> This property represents the number of records to offset the paging by. This is set and updated internally by the table component, but it may need updated externally if you're implementing server-side paging. <br/> <caption>See <a [routerLink]="['../server-integration']">Server Integration</a> for more details.</caption> </p> </div> <div class="go-column go-column--100"> <h4 class="go-heading-4">pageSizes</h4> <p class="go-body-copy go-body-copy--no-margin"> This property determines what page sizes are available to the user. It takes an array of numbers, but has defaults. It is recommended to stick with the predefined options, but if needed, pass whole numbers in increments of 5 for more options. </p> </div> <div class="go-column go-column--100"> <h4 class="go-heading-4">perPage</h4> <p class="go-body-copy go-body-copy--no-margin"> This property represents the current items per page. It is set and updated internally by the table component. <br/> <caption>If you're implementing server-side paging, this is important. See <a [routerLink]="['../server-integration']">Server Integration</a> for more details.</caption> </p> </div> </div> </go-card> <go-card class="go-column go-column--100"> <ng-container go-card-header> <h2 class="go-heading-2">Simple Paging</h2> </ng-container> <ng-container go-card-content> <div class="go-container"> <div class="go-column go-column--100"> <p class="go-body-copy go-body-copy--no-margin"> Nothing extra for client-side paging is required, it just works. To set different page sizes, the following is requried. </p> </div> <div class="go-column go-column--100"> <h4 class="go-heading-4">example.html</h4> <code [highlight]="tableConfig_html"></code> <h4 class="go-heading-4">example.ts</h4> <code [highlight]="tableConfig_ts" class="code-block--no-bottom-margin"></code> </div> </div> </ng-container> </go-card> <go-table class="go-column go-column--100" [tableConfig]="tableConfig" tableTitle="Paging Example"> <go-table-column field="id" title="ID"></go-table-column> <go-table-column field="name.first" title="First Name"></go-table-column> <go-table-column field="name.last" title="Last Name"></go-table-column> <go-table-column field="email" title="Email"></go-table-column> <go-table-column field="gender" title="Gender"></go-table-column> <go-table-column field="ip_address" title="IP Address"></go-table-column> </go-table> </section>
44.3875
179
0.633343
363480da33ab4097111a80e8213c2c99995633ed
5,933
rs
Rust
runtime/wasm/src/gas_rules.rs
Fairyswap/graph-node
bbfb72f330f55f229d6cfc9a806e3d992f3919f1
[ "Apache-2.0", "MIT" ]
null
null
null
runtime/wasm/src/gas_rules.rs
Fairyswap/graph-node
bbfb72f330f55f229d6cfc9a806e3d992f3919f1
[ "Apache-2.0", "MIT" ]
null
null
null
runtime/wasm/src/gas_rules.rs
Fairyswap/graph-node
bbfb72f330f55f229d6cfc9a806e3d992f3919f1
[ "Apache-2.0", "MIT" ]
1
2022-01-11T07:01:30.000Z
2022-01-11T07:01:30.000Z
use std::{convert::TryInto, num::NonZeroU32}; use graph::runtime::gas::CONST_MAX_GAS_PER_HANDLER; use parity_wasm::elements::Instruction; use pwasm_utils::rules::{MemoryGrowCost, Rules}; pub const GAS_COST_STORE: u32 = 2263; pub const GAS_COST_LOAD: u32 = 1573; pub struct GasRules; impl Rules for GasRules { fn instruction_cost(&self, instruction: &Instruction) -> Option<u32> { use Instruction::*; let weight = match instruction { // These are taken from this post: https://github.com/paritytech/substrate/pull/7361#issue-506217103 // from the table under the "Schedule" dropdown. Each decimal is multiplied by 10. // Note that those were calculated for wasi, not wasmtime, so they are likely very conservative. I64Const(_) => 16, I64Load(_, _) => GAS_COST_LOAD, I64Store(_, _) => GAS_COST_STORE, Select => 61, Instruction::If(_) => 79, Br(_) => 30, BrIf(_) => 63, BrTable(data) => 146 + data.table.len() as u32, Call(_) => 951, // TODO: To figure out the param cost we need to look up the function CallIndirect(_, _) => 1995, GetLocal(_) => 18, SetLocal(_) => 21, TeeLocal(_) => 21, GetGlobal(_) => 66, SetGlobal(_) => 107, CurrentMemory(_) => 23, GrowMemory(_) => 435000, I64Clz => 23, I64Ctz => 23, I64Popcnt => 29, I64Eqz => 24, I64ExtendSI32 => 22, I64ExtendUI32 => 22, I32WrapI64 => 23, I64Eq => 26, I64Ne => 25, I64LtS => 25, I64LtU => 26, I64GtS => 25, I64GtU => 25, I64LeS => 25, I64LeU => 26, I64GeS => 26, I64GeU => 25, I64Add => 25, I64Sub => 26, I64Mul => 25, I64DivS => 82, I64DivU => 72, I64RemS => 81, I64RemU => 73, I64And => 25, I64Or => 25, I64Xor => 26, I64Shl => 25, I64ShrS => 26, I64ShrU => 26, I64Rotl => 25, I64Rotr => 26, // These are similar enough to something above so just referencing a similar // instruction I32Load(_, _) | F32Load(_, _) | F64Load(_, _) | I32Load8S(_, _) | I32Load8U(_, _) | I32Load16S(_, _) | I32Load16U(_, _) | I64Load8S(_, _) | I64Load8U(_, _) | I64Load16S(_, _) | I64Load16U(_, _) | I64Load32S(_, _) | I64Load32U(_, _) => GAS_COST_LOAD, I32Store(_, _) | F32Store(_, _) | F64Store(_, _) | I32Store8(_, _) | I32Store16(_, _) | I64Store8(_, _) | I64Store16(_, _) | I64Store32(_, _) => GAS_COST_STORE, I32Const(_) | F32Const(_) | F64Const(_) => 16, I32Eqz => 26, I32Eq => 26, I32Ne => 25, I32LtS => 25, I32LtU => 26, I32GtS => 25, I32GtU => 25, I32LeS => 25, I32LeU => 26, I32GeS => 26, I32GeU => 25, I32Add => 25, I32Sub => 26, I32Mul => 25, I32DivS => 82, I32DivU => 72, I32RemS => 81, I32RemU => 73, I32And => 25, I32Or => 25, I32Xor => 26, I32Shl => 25, I32ShrS => 26, I32ShrU => 26, I32Rotl => 25, I32Rotr => 26, I32Clz => 23, I32Popcnt => 29, I32Ctz => 23, // Float weights not calculated by reference source material. Making up // some conservative values. The point here is not to be perfect but just // to have some reasonable upper bound. F64ReinterpretI64 | F32ReinterpretI32 | F64PromoteF32 | F64ConvertUI64 | F64ConvertSI64 | F64ConvertUI32 | F64ConvertSI32 | F32DemoteF64 | F32ConvertUI64 | F32ConvertSI64 | F32ConvertUI32 | F32ConvertSI32 | I64TruncUF64 | I64TruncSF64 | I64TruncUF32 | I64TruncSF32 | I32TruncUF64 | I32TruncSF64 | I32TruncUF32 | I32TruncSF32 | F64Copysign | F64Max | F64Min | F64Mul | F64Sub | F64Add | F64Trunc | F64Floor | F64Ceil | F64Neg | F64Abs | F64Nearest | F32Copysign | F32Max | F32Min | F32Mul | F32Sub | F32Add | F32Nearest | F32Trunc | F32Floor | F32Ceil | F32Neg | F32Abs | F32Eq | F32Ne | F32Lt | F32Gt | F32Le | F32Ge | F64Eq | F64Ne | F64Lt | F64Gt | F64Le | F64Ge | I32ReinterpretF32 | I64ReinterpretF64 => 100, F64Div | F64Sqrt | F32Div | F32Sqrt => 100, // More invented weights Block(_) => 100, Loop(_) => 100, Else => 100, End => 100, Return => 100, Drop => 100, SignExt(_) => 100, Nop => 1, Unreachable => 1, }; Some(weight) } fn memory_grow_cost(&self) -> Option<MemoryGrowCost> { // Each page is 64KiB which is 65536 bytes. const PAGE: u64 = 64 * 1024; // 1 GB const GIB: u64 = 1073741824; // 12GiB to pages for the max memory allocation // In practice this will never be hit unless we also // free pages because this is 32bit WASM. const MAX_PAGES: u64 = 12 * GIB / PAGE; let gas_per_page = NonZeroU32::new((CONST_MAX_GAS_PER_HANDLER / MAX_PAGES).try_into().unwrap()).unwrap(); Some(MemoryGrowCost::Linear(gas_per_page)) } }
35.106509
112
0.489971
0437f2172962ff7df8b47bcb8c7cde801f02ab79
522
java
Java
server/src/main/java/pl/safenet/server/ImageFileFilter.java
precht/safenet
c5d386cbb74ee7a75c84e71d0d7c4ff98c043a95
[ "MIT" ]
null
null
null
server/src/main/java/pl/safenet/server/ImageFileFilter.java
precht/safenet
c5d386cbb74ee7a75c84e71d0d7c4ff98c043a95
[ "MIT" ]
null
null
null
server/src/main/java/pl/safenet/server/ImageFileFilter.java
precht/safenet
c5d386cbb74ee7a75c84e71d0d7c4ff98c043a95
[ "MIT" ]
null
null
null
package pl.safenet.server; import java.io.*; public class ImageFileFilter implements FileFilter { // private final String[] acceptedExtensions = new String[] {".bmp", ".png", ".jpg", ".jpeg"}; private final String[] acceptedExtensions = new String[] {".png"}; @Override public boolean accept(File file) { for (String extension : acceptedExtensions) { if (file.getName().toLowerCase().endsWith(extension)) { return true; } } return false; } }
21.75
96
0.611111
5eb7b59ea92df039ed984f378c3a2bf6b29363ce
748
kt
Kotlin
src/test/kotlin/com/leetcode/P69Test.kt
antop-dev/algorithm
9c8b1c1ecbac97829631b7b8db3666682dc5bf1c
[ "MIT" ]
null
null
null
src/test/kotlin/com/leetcode/P69Test.kt
antop-dev/algorithm
9c8b1c1ecbac97829631b7b8db3666682dc5bf1c
[ "MIT" ]
373
2019-12-22T13:14:14.000Z
2022-03-29T13:22:28.000Z
src/test/kotlin/com/leetcode/P69Test.kt
antop-dev/algorithm
9c8b1c1ecbac97829631b7b8db3666682dc5bf1c
[ "MIT" ]
null
null
null
package com.leetcode import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.Matchers.`is` import org.junit.jupiter.api.Test internal class P69Test { val p = P69() @Test fun `example 1`() { assertThat(p.mySqrt(4), `is`(2)) } @Test fun `example 2`() { assertThat(p.mySqrt(8), `is`(2)) } @Test fun `example 3`() { assertThat(p.mySqrt(1), `is`(1)) } @Test fun `example 4`() { assertThat(p.mySqrt(2147395599), `is`(46339)) } @Test fun `example 5`() { assertThat(p.mySqrt(3), `is`(1)) } @Test fun `example 6`() { assertThat(p.mySqrt(0), `is`(0)) } @Test fun `example 7`() { p.mySqrt(17) } }
16.622222
53
0.525401
626c11a9fbb6e983da981b6d7beca04aafb4aa41
312
asm
Assembly
programs/oeis/156/A156859.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/156/A156859.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/156/A156859.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A156859: The main column of a version of the square spiral. ; 0,3,7,14,22,33,45,60,76,95,115,138,162,189,217,248,280,315,351,390,430,473,517,564,612,663,715,770,826,885,945,1008,1072,1139,1207,1278,1350,1425,1501,1580,1660,1743,1827,1914,2002,2093,2185,2280,2376,2475,2575 mul $0,2 add $0,2 bin $0,2 div $0,2
39
212
0.727564