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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b37c2b98d05a0c307f451acb9b773b4e25846fdd | 539 | asm | Assembly | pass/rt/boot32.asm | virtines/wasp | a8a9ac3b2c1369efc5a4d6ab2a7938747db34eaa | [
"MIT"
] | 4 | 2022-02-03T19:01:27.000Z | 2022-03-29T18:59:56.000Z | pass/rt/boot32.asm | virtines/wasp | a8a9ac3b2c1369efc5a4d6ab2a7938747db34eaa | [
"MIT"
] | 1 | 2022-01-28T19:16:53.000Z | 2022-02-02T21:38:17.000Z | pass/rt/boot32.asm | virtines/wasp | a8a9ac3b2c1369efc5a4d6ab2a7938747db34eaa | [
"MIT"
] | 1 | 2022-03-08T03:05:43.000Z | 2022-03-08T03:05:43.000Z | [bits 16]
[section .text]
extern __virtine_main
global _start
_start:
cli
mov eax, gdtr32
lgdt [eax]
mov eax, cr0
or al, 1
mov cr0, eax
jmp 08h:.trampoline
[bits 32]
.trampoline:
mov esp, 0x1000
mov ebp, esp
push dword 0
call __virtine_main
out 0xFA, ax ;; call the exit hypercall
global hcall
hcall:
push ebp
mov ebp, esp
mov eax, [ebp + 8]
mov ebx, [ebp + 12]
out 0xFF, eax,
pop ebp
ret
[section .data]
gdt32:
dq 0x0000000000000000
dq 0x00cf9a000000ffff
dq 0x00cf92000000ffff
gdtr32:
dw 23
dd gdt32
| 11.977778 | 40 | 0.695733 |
277f5638fdf0a4cdd837439ebc208a2d1ec7a753 | 5,801 | sql | SQL | test/sql/official-suite/boundary1-14.sql | chengwenxin/sqlite-parser | 7489d4b7885b3785c1fdbddf65fed8ea2a7b485e | [
"MIT"
] | 320 | 2015-07-04T17:11:58.000Z | 2022-03-23T04:40:29.000Z | test/sql/official-suite/boundary1-14.sql | chengwenxin/sqlite-parser | 7489d4b7885b3785c1fdbddf65fed8ea2a7b485e | [
"MIT"
] | 53 | 2015-07-09T23:27:58.000Z | 2021-01-29T13:21:45.000Z | test/sql/official-suite/boundary1-14.sql | applandinc/sql-parser | 11acbbea6b269c0bcc8b22627cc3c8572cb7a2fc | [
"MIT"
] | 68 | 2015-08-06T12:45:27.000Z | 2022-03-23T04:40:40.000Z | -- original: boundary1.test
-- credit: http://www.sqlite.org/src/tree?ci=trunk&name=test
SELECT a FROM t1 WHERE rowid < 127 ORDER BY a
;SELECT a FROM t1 WHERE rowid < 127 ORDER BY a DESC
;SELECT a FROM t1 WHERE rowid < 127 ORDER BY rowid
;SELECT a FROM t1 WHERE rowid < 127 ORDER BY rowid DESC
;SELECT a FROM t1 WHERE rowid < 127 ORDER BY x
;SELECT a FROM t1 WHERE rowid <= 127 ORDER BY a
;SELECT a FROM t1 WHERE rowid <= 127 ORDER BY a DESC
;SELECT a FROM t1 WHERE rowid <= 127 ORDER BY rowid
;SELECT a FROM t1 WHERE rowid <= 127 ORDER BY rowid DESC
;SELECT a FROM t1 WHERE rowid <= 127 ORDER BY x
;SELECT * FROM t1 WHERE rowid=36028797018963967
;SELECT rowid, a FROM t1 WHERE x='007fffffffffffff'
;SELECT rowid, x FROM t1 WHERE a=27
;SELECT a FROM t1 WHERE rowid > 36028797018963967 ORDER BY a
;SELECT a FROM t1 WHERE rowid > 36028797018963967 ORDER BY a DESC
;SELECT a FROM t1 WHERE rowid > 36028797018963967 ORDER BY rowid
;SELECT a FROM t1 WHERE rowid > 36028797018963967 ORDER BY rowid DESC
;SELECT a FROM t1 WHERE rowid > 36028797018963967 ORDER BY x
;SELECT a FROM t1 WHERE rowid >= 36028797018963967 ORDER BY a
;SELECT a FROM t1 WHERE rowid >= 36028797018963967 ORDER BY a DESC
;SELECT a FROM t1 WHERE rowid >= 36028797018963967 ORDER BY rowid
;SELECT a FROM t1 WHERE rowid >= 36028797018963967 ORDER BY rowid DESC
;SELECT a FROM t1 WHERE rowid >= 36028797018963967 ORDER BY x
;SELECT a FROM t1 WHERE rowid < 36028797018963967 ORDER BY a
;SELECT a FROM t1 WHERE rowid < 36028797018963967 ORDER BY a DESC
;SELECT a FROM t1 WHERE rowid < 36028797018963967 ORDER BY rowid
;SELECT a FROM t1 WHERE rowid < 36028797018963967 ORDER BY rowid DESC
;SELECT a FROM t1 WHERE rowid < 36028797018963967 ORDER BY x
;SELECT a FROM t1 WHERE rowid <= 36028797018963967 ORDER BY a
;SELECT a FROM t1 WHERE rowid <= 36028797018963967 ORDER BY a DESC
;SELECT a FROM t1 WHERE rowid <= 36028797018963967 ORDER BY rowid
;SELECT a FROM t1 WHERE rowid <= 36028797018963967 ORDER BY rowid DESC
;SELECT a FROM t1 WHERE rowid <= 36028797018963967 ORDER BY x
;SELECT * FROM t1 WHERE rowid=4398046511104
;SELECT rowid, a FROM t1 WHERE x='0000040000000000'
;SELECT rowid, x FROM t1 WHERE a=56
;SELECT a FROM t1 WHERE rowid > 4398046511104 ORDER BY a
;SELECT a FROM t1 WHERE rowid > 4398046511104 ORDER BY a DESC
;SELECT a FROM t1 WHERE rowid > 4398046511104 ORDER BY rowid
;SELECT a FROM t1 WHERE rowid > 4398046511104 ORDER BY rowid DESC
;SELECT a FROM t1 WHERE rowid > 4398046511104 ORDER BY x
;SELECT a FROM t1 WHERE rowid >= 4398046511104 ORDER BY a
;SELECT a FROM t1 WHERE rowid >= 4398046511104 ORDER BY a DESC
;SELECT a FROM t1 WHERE rowid >= 4398046511104 ORDER BY rowid
;SELECT a FROM t1 WHERE rowid >= 4398046511104 ORDER BY rowid DESC
;SELECT a FROM t1 WHERE rowid >= 4398046511104 ORDER BY x
;SELECT a FROM t1 WHERE rowid < 4398046511104 ORDER BY a
;SELECT a FROM t1 WHERE rowid < 4398046511104 ORDER BY a DESC
;SELECT a FROM t1 WHERE rowid < 4398046511104 ORDER BY rowid
;SELECT a FROM t1 WHERE rowid < 4398046511104 ORDER BY rowid DESC
;SELECT a FROM t1 WHERE rowid < 4398046511104 ORDER BY x
;SELECT a FROM t1 WHERE rowid <= 4398046511104 ORDER BY a
;SELECT a FROM t1 WHERE rowid <= 4398046511104 ORDER BY a DESC
;SELECT a FROM t1 WHERE rowid <= 4398046511104 ORDER BY rowid
;SELECT a FROM t1 WHERE rowid <= 4398046511104 ORDER BY rowid DESC
;SELECT a FROM t1 WHERE rowid <= 4398046511104 ORDER BY x
;SELECT * FROM t1 WHERE rowid=1
;SELECT rowid, a FROM t1 WHERE x='0000000000000001'
;SELECT rowid, x FROM t1 WHERE a=60
;SELECT a FROM t1 WHERE rowid > 1 ORDER BY a
;SELECT a FROM t1 WHERE rowid > 1 ORDER BY a DESC
;SELECT a FROM t1 WHERE rowid > 1 ORDER BY rowid
;SELECT a FROM t1 WHERE rowid > 1 ORDER BY rowid DESC
;SELECT a FROM t1 WHERE rowid > 1 ORDER BY x
;SELECT a FROM t1 WHERE rowid >= 1 ORDER BY a
;SELECT a FROM t1 WHERE rowid >= 1 ORDER BY a DESC
;SELECT a FROM t1 WHERE rowid >= 1 ORDER BY rowid
;SELECT a FROM t1 WHERE rowid >= 1 ORDER BY rowid DESC
;SELECT a FROM t1 WHERE rowid >= 1 ORDER BY x
;SELECT a FROM t1 WHERE rowid < 1 ORDER BY a
;SELECT a FROM t1 WHERE rowid < 1 ORDER BY a DESC
;SELECT a FROM t1 WHERE rowid < 1 ORDER BY rowid
;SELECT a FROM t1 WHERE rowid < 1 ORDER BY rowid DESC
;SELECT a FROM t1 WHERE rowid < 1 ORDER BY x
;SELECT a FROM t1 WHERE rowid <= 1 ORDER BY a
;SELECT a FROM t1 WHERE rowid <= 1 ORDER BY a DESC
;SELECT a FROM t1 WHERE rowid <= 1 ORDER BY rowid
;SELECT a FROM t1 WHERE rowid <= 1 ORDER BY rowid DESC
;SELECT a FROM t1 WHERE rowid <= 1 ORDER BY x
;SELECT * FROM t1 WHERE rowid=36028797018963968
;SELECT rowid, a FROM t1 WHERE x='0080000000000000'
;SELECT rowid, x FROM t1 WHERE a=45
;SELECT a FROM t1 WHERE rowid > 36028797018963968 ORDER BY a
;SELECT a FROM t1 WHERE rowid > 36028797018963968 ORDER BY a DESC
;SELECT a FROM t1 WHERE rowid > 36028797018963968 ORDER BY rowid
;SELECT a FROM t1 WHERE rowid > 36028797018963968 ORDER BY rowid DESC
;SELECT a FROM t1 WHERE rowid > 36028797018963968 ORDER BY x
;SELECT a FROM t1 WHERE rowid >= 36028797018963968 ORDER BY a
;SELECT a FROM t1 WHERE rowid >= 36028797018963968 ORDER BY a DESC
;SELECT a FROM t1 WHERE rowid >= 36028797018963968 ORDER BY rowid
;SELECT a FROM t1 WHERE rowid >= 36028797018963968 ORDER BY rowid DESC
;SELECT a FROM t1 WHERE rowid >= 36028797018963968 ORDER BY x
;SELECT a FROM t1 WHERE rowid < 36028797018963968 ORDER BY a
;SELECT a FROM t1 WHERE rowid < 36028797018963968 ORDER BY a DESC
;SELECT a FROM t1 WHERE rowid < 36028797018963968 ORDER BY rowid
;SELECT a FROM t1 WHERE rowid < 36028797018963968 ORDER BY rowid DESC
;SELECT a FROM t1 WHERE rowid < 36028797018963968 ORDER BY x
;SELECT a FROM t1 WHERE rowid <= 36028797018963968 ORDER BY a
;SELECT a FROM t1 WHERE rowid <= 36028797018963968 ORDER BY a DESC
;SELECT a FROM t1 WHERE rowid <= 36028797018963968 ORDER BY rowid; | 56.320388 | 70 | 0.763489 |
165ead3a33b4beaf1ba6e12d46493049508d771f | 1,126 | ts | TypeScript | test/template/app-context.test.ts | ivorycirrus/aws-cdk-project-template-for-devops | 4c4d7aa0948ec4e2e83f22e00ae42d17f2ff5433 | [
"MIT-0"
] | 37 | 2021-09-25T03:20:11.000Z | 2022-03-31T13:52:38.000Z | test/template/app-context.test.ts | ivorycirrus/aws-cdk-project-template-for-devops | 4c4d7aa0948ec4e2e83f22e00ae42d17f2ff5433 | [
"MIT-0"
] | 2 | 2022-01-18T07:17:28.000Z | 2022-03-25T13:15:33.000Z | test/template/app-context.test.ts | ivorycirrus/aws-cdk-project-template-for-devops | 4c4d7aa0948ec4e2e83f22e00ae42d17f2ff5433 | [
"MIT-0"
] | 10 | 2021-09-25T03:42:50.000Z | 2022-03-04T09:41:59.000Z | import * as cdk from '@aws-cdk/core';
import { assert } from 'console';
import { AppContext } from '../../lib/template/app-context';
let cdkApp = new cdk.App();
test('[TESTCase01] updateContextArgs: HappyCase', () => {
// SETUP
cdkApp.node.tryGetContext = jest.fn()
.mockReturnValueOnce('test/template/app-config-test.json')
.mockReturnValueOnce('there');
// WHEN
const context = new AppContext({
appConfigFileKey: 'APP_CONFIG',
contextArgs: [
'aa.bb.cc'
]
}, cdkApp);
// THEN
expect(context.ready()).toBe(true);
});
test('[TESTCase02] updateContextArgs: BadCase', () => {
// SETUP
cdkApp.node.tryGetContext = jest.fn()
.mockReturnValueOnce('test/template/app-config-test.json')
.mockReturnValueOnce('there');
// WHEN
let context = undefined;
try {
context = new AppContext({
appConfigFileKey: 'APP_CONFIG',
contextArgs: [
'aa.bb1.cc'
]
}, cdkApp);
} catch(e) {
}
// THEN
expect(context).toBe(undefined);
});
| 22.979592 | 66 | 0.565719 |
b9c6e07253bd6f046d129d03a07fd05f903d4f2f | 1,790 | h | C | PrivateFrameworks/CalendarUIKit/CUIKUserOperation.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 17 | 2018-11-13T04:02:58.000Z | 2022-01-20T09:27:13.000Z | PrivateFrameworks/CalendarUIKit/CUIKUserOperation.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 3 | 2018-04-06T02:02:27.000Z | 2018-10-02T01:12:10.000Z | PrivateFrameworks/CalendarUIKit/CUIKUserOperation.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 1 | 2018-09-28T13:54:23.000Z | 2018-09-28T13:54:23.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "NSObject.h"
@class NSArray, NSError, NSString;
@interface CUIKUserOperation : NSObject
{
BOOL _inverseOperationPrecomputed;
NSError *_error;
NSArray *_objects;
long long _span;
NSArray *_originalObjects;
NSArray *_originalSliceDescriptions;
NSString *_precomputedActionName;
CUIKUserOperation *_precomputedInverseOperation;
}
+ (id)operationWithObjects:(id)arg1 span:(long long)arg2;
+ (id)operationForContext:(id)arg1;
@property BOOL inverseOperationPrecomputed; // @synthesize inverseOperationPrecomputed=_inverseOperationPrecomputed;
@property(retain) CUIKUserOperation *precomputedInverseOperation; // @synthesize precomputedInverseOperation=_precomputedInverseOperation;
@property(retain) NSString *precomputedActionName; // @synthesize precomputedActionName=_precomputedActionName;
@property(retain) NSArray *originalSliceDescriptions; // @synthesize originalSliceDescriptions=_originalSliceDescriptions;
@property(retain) NSArray *originalObjects; // @synthesize originalObjects=_originalObjects;
@property long long span; // @synthesize span=_span;
@property(retain) NSArray *objects; // @synthesize objects=_objects;
@property(retain) NSError *error; // @synthesize error=_error;
- (void).cxx_destruct;
- (id)_objectsForInverse;
- (Class)_inverseOperationClass;
- (id)_inverseOperation;
- (id)inverseOperation;
- (void)_precomputeInverseOperation;
- (void)_storeOriginalSliceDescriptions;
- (BOOL)_execute:(id *)arg1;
- (BOOL)execute;
- (id)_actionName;
- (void)_precomputeActionName;
@property(readonly, nonatomic) NSString *actionName;
- (id)initWithObjects:(id)arg1 span:(long long)arg2;
@end
| 36.530612 | 138 | 0.782123 |
9f086f1dbdfca9a2fa3b07059824bb212baa9d5b | 7,472 | sql | SQL | backend/de.metas.adempiere.adempiere/migration/src/main/sql/postgresql/system/10-de.metas.adempiere/5513850_sys_gh4994_New_I_BPartner_Columns.sql | dram/metasfresh | a1b881a5b7df8b108d4c4ac03082b72c323873eb | [
"RSA-MD"
] | 1,144 | 2016-02-14T10:29:35.000Z | 2022-03-30T09:50:41.000Z | backend/de.metas.adempiere.adempiere/migration/src/main/sql/postgresql/system/10-de.metas.adempiere/5513850_sys_gh4994_New_I_BPartner_Columns.sql | vestigegroup/metasfresh | 4b2d48c091fb2a73e6f186260a06c715f5e2fe96 | [
"RSA-MD"
] | 8,283 | 2016-04-28T17:41:34.000Z | 2022-03-30T13:30:12.000Z | backend/de.metas.adempiere.adempiere/migration/src/main/sql/postgresql/system/10-de.metas.adempiere/5513850_sys_gh4994_New_I_BPartner_Columns.sql | vestigegroup/metasfresh | 4b2d48c091fb2a73e6f186260a06c715f5e2fe96 | [
"RSA-MD"
] | 441 | 2016-04-29T08:06:07.000Z | 2022-03-28T06:09:56.000Z |
-- 2019-02-26T16:28:50.610
-- #298 changing anz. stellen
INSERT INTO AD_Column (AD_Reference_ID,FieldLength,Version,IsKey,IsParent,IsTranslated,IsIdentifier,SeqNo,AD_Client_ID,IsActive,Created,CreatedBy,IsUpdateable,DDL_NoForeignKey,IsSelectionColumn,IsSyncDatabase,IsAlwaysUpdateable,IsAutocomplete,IsAllowLogging,IsEncrypted,Updated,UpdatedBy,IsAdvancedText,IsLazyLoading,AD_Table_ID,AD_Column_ID,IsDimension,IsMandatory,IsStaleable,IsUseDocSequence,IsDLMPartitionBoundary,IsGenericZoomKeyColumn,SelectionColumnSeqNo,AD_Org_ID,Name,IsCalculated,IsRangeFilter,IsShowFilterIncrementButtons,AD_Element_ID,IsForceIncludeInGeneratedModel,IsGenericZoomOrigin,EntityType,ColumnName,Description,IsAutoApplyValidationRule) VALUES (14,2000,0,'N','N','N','N',0,0,'Y',TO_TIMESTAMP('2019-02-26 16:28:50','YYYY-MM-DD HH24:MI:SS'),100,'Y','N','N','N','N','N','Y','N',TO_TIMESTAMP('2019-02-26 16:28:50','YYYY-MM-DD HH24:MI:SS'),100,'N','N',533,564256,'N','N','N','N','N','N',0,0,'Memo_Delivery','N','N','N',542819,'N','N','de.metas.swat','Memo_Delivery','Memo Lieferung','N')
;
-- 2019-02-26T16:28:50.615
-- #298 changing anz. stellen
INSERT INTO AD_Column_Trl (AD_Language,AD_Column_ID, Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language, t.AD_Column_ID, t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Column t WHERE l.IsActive='Y'AND (l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N') AND t.AD_Column_ID=564256 AND NOT EXISTS (SELECT 1 FROM AD_Column_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Column_ID=t.AD_Column_ID)
;
-- 2019-02-26T13:44:27.590
-- #298 changing anz. stellen
INSERT INTO AD_Column (AD_Reference_ID,FieldLength,Version,IsKey,IsParent,IsTranslated,IsIdentifier,SeqNo,AD_Client_ID,IsActive,Created,CreatedBy,IsUpdateable,DDL_NoForeignKey,IsSelectionColumn,IsSyncDatabase,IsAlwaysUpdateable,IsAutocomplete,IsAllowLogging,IsEncrypted,Updated,UpdatedBy,IsAdvancedText,IsLazyLoading,AD_Table_ID,AD_Column_ID,IsDimension,IsMandatory,IsStaleable,IsUseDocSequence,IsDLMPartitionBoundary,IsGenericZoomKeyColumn,SelectionColumnSeqNo,AD_Org_ID,Name,IsCalculated,IsRangeFilter,IsShowFilterIncrementButtons,AD_Element_ID,IsForceIncludeInGeneratedModel,IsGenericZoomOrigin,EntityType,ColumnName,Description,IsAutoApplyValidationRule) VALUES (10,250,0,'N','N','N','N',0,0,'Y',TO_TIMESTAMP('2019-02-26 13:44:27','YYYY-MM-DD HH24:MI:SS'),100,'Y','N','N','N','N','N','Y','N',TO_TIMESTAMP('2019-02-26 13:44:27','YYYY-MM-DD HH24:MI:SS'),100,'N','N',533,564250,'N','N','N','N','N','N',0,0,'Memo_Invoicing','N','N','N',542820,'N','N','de.metas.swat','Memo_Invoicing','Memo Abrechnung','N')
;
-- 2019-02-26T13:44:27.606
-- #298 changing anz. stellen
INSERT INTO AD_Column_Trl (AD_Language,AD_Column_ID, Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language, t.AD_Column_ID, t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Column t WHERE l.IsActive='Y'AND (l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N') AND t.AD_Column_ID=564250 AND NOT EXISTS (SELECT 1 FROM AD_Column_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Column_ID=t.AD_Column_ID)
;
-- 2019-02-26T16:23:12.996
-- #298 changing anz. stellen
INSERT INTO AD_Column (AD_Reference_ID,FieldLength,Version,IsKey,IsParent,IsTranslated,IsIdentifier,SeqNo,AD_Client_ID,IsActive,Created,CreatedBy,IsUpdateable,DDL_NoForeignKey,IsSelectionColumn,IsSyncDatabase,IsAlwaysUpdateable,IsAutocomplete,IsAllowLogging,IsEncrypted,Updated,UpdatedBy,IsAdvancedText,IsLazyLoading,AD_Table_ID,AD_Column_ID,IsDimension,IsMandatory,IsStaleable,IsUseDocSequence,IsDLMPartitionBoundary,IsGenericZoomKeyColumn,SelectionColumnSeqNo,AD_Org_ID,Name,IsCalculated,IsRangeFilter,IsShowFilterIncrementButtons,AD_Element_ID,IsForceIncludeInGeneratedModel,IsGenericZoomOrigin,EntityType,ColumnName,IsAutoApplyValidationRule) VALUES (10,250,0,'N','N','N','N',0,0,'Y',TO_TIMESTAMP('2019-02-26 16:23:12','YYYY-MM-DD HH24:MI:SS'),100,'Y','N','N','N','N','N','Y','N',TO_TIMESTAMP('2019-02-26 16:23:12','YYYY-MM-DD HH24:MI:SS'),100,'N','N',533,564252,'N','N','N','N','N','N',0,0,'Postfach','N','N','N',55445,'N','N','D','POBox','N')
;
-- 2019-02-26T16:23:12.999
-- #298 changing anz. stellen
INSERT INTO AD_Column_Trl (AD_Language,AD_Column_ID, Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language, t.AD_Column_ID, t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Column t WHERE l.IsActive='Y'AND (l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N') AND t.AD_Column_ID=564252 AND NOT EXISTS (SELECT 1 FROM AD_Column_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Column_ID=t.AD_Column_ID)
;
-- 2019-02-26T16:24:43.416
-- #298 changing anz. stellen
INSERT INTO AD_Column (AD_Reference_ID,FieldLength,Version,IsKey,IsParent,IsTranslated,IsIdentifier,SeqNo,AD_Client_ID,IsActive,Created,CreatedBy,IsUpdateable,DDL_NoForeignKey,IsSelectionColumn,IsSyncDatabase,IsAlwaysUpdateable,IsAutocomplete,IsAllowLogging,IsEncrypted,Updated,UpdatedBy,IsAdvancedText,IsLazyLoading,AD_Table_ID,AD_Column_ID,IsDimension,IsMandatory,IsStaleable,IsUseDocSequence,IsDLMPartitionBoundary,IsGenericZoomKeyColumn,SelectionColumnSeqNo,AD_Org_ID,Name,IsCalculated,IsRangeFilter,IsShowFilterIncrementButtons,AD_Element_ID,IsForceIncludeInGeneratedModel,IsGenericZoomOrigin,EntityType,ColumnName,Description,IsAutoApplyValidationRule) VALUES (10,250,0,'N','N','N','N',0,0,'Y',TO_TIMESTAMP('2019-02-26 16:24:43','YYYY-MM-DD HH24:MI:SS'),100,'Y','N','N','N','N','N','Y','N',TO_TIMESTAMP('2019-02-26 16:24:43','YYYY-MM-DD HH24:MI:SS'),100,'N','N',533,564253,'N','N','N','N','N','N',0,0,'Land','N','N','N',2585,'N','N','D','CountryName','Land','N')
;
-- 2019-02-26T16:24:43.420
-- #298 changing anz. stellen
INSERT INTO AD_Column_Trl (AD_Language,AD_Column_ID, Name, IsTranslated,AD_Client_ID,AD_Org_ID,Created,Createdby,Updated,UpdatedBy) SELECT l.AD_Language, t.AD_Column_ID, t.Name, 'N',t.AD_Client_ID,t.AD_Org_ID,t.Created,t.Createdby,t.Updated,t.UpdatedBy FROM AD_Language l, AD_Column t WHERE l.IsActive='Y'AND (l.IsSystemLanguage='Y' AND l.IsBaseLanguage='N') AND t.AD_Column_ID=564253 AND NOT EXISTS (SELECT 1 FROM AD_Column_Trl tt WHERE tt.AD_Language=l.AD_Language AND tt.AD_Column_ID=t.AD_Column_ID)
;
-- 2019-02-26T17:36:44.938
-- #298 changing anz. stellen
UPDATE AD_Column SET EntityType='D',Updated=TO_TIMESTAMP('2019-02-26 17:36:44','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Column_ID=564256
;
-- 2019-02-26T17:36:53.128
-- #298 changing anz. stellen
UPDATE AD_Column SET EntityType='D',Updated=TO_TIMESTAMP('2019-02-26 17:36:53','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Column_ID=564250
;
-- 2019-02-27T13:36:12.829
-- #298 changing anz. stellen
UPDATE AD_Column SET EntityType='D',Updated=TO_TIMESTAMP('2019-02-27 13:36:12','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Column_ID=552452
;
-- 2019-03-01T11:42:02.080
-- #298 changing anz. stellen
UPDATE AD_Column SET EntityType='D',Updated=TO_TIMESTAMP('2019-03-01 11:42:02','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Column_ID=552451
;
-- 2019-03-01T11:49:42.324
-- #298 changing anz. stellen
UPDATE AD_Column SET EntityType='D',Updated=TO_TIMESTAMP('2019-03-01 11:49:42','YYYY-MM-DD HH24:MI:SS'),UpdatedBy=100 WHERE AD_Column_ID=558551
;
| 77.833333 | 1,006 | 0.785867 |
5661dd981c977057cb92406bb49c6123d9d881f7 | 1,468 | swift | Swift | Tests/LexerTests/Rules/Function/FuncCallArgsRuleTests.swift | LastSprint/T-Lang | 5346866e9d507b69e560ff57e67bb6c1a0c2eb27 | [
"MIT"
] | null | null | null | Tests/LexerTests/Rules/Function/FuncCallArgsRuleTests.swift | LastSprint/T-Lang | 5346866e9d507b69e560ff57e67bb6c1a0c2eb27 | [
"MIT"
] | null | null | null | Tests/LexerTests/Rules/Function/FuncCallArgsRuleTests.swift | LastSprint/T-Lang | 5346866e9d507b69e560ff57e67bb6c1a0c2eb27 | [
"MIT"
] | null | null | null | //
// FuncCallArgsRuleTests.swift
//
//
// Created by Александр Кравченков on 07.01.2022.
//
import Foundation
import XCTest
@testable import Lexer
// Test Cases:
// 1. Empty args will return empty array
// 2. Single arg will be parsed
// 3. Two args will be parsed
// 4. Extra coma won't be parsed
final class FuncCallArgsRuleTests: XCTestCase {
func testEmptyArgsWillReturnEmptyArray() throws {
// Arrange
let stream = try StringStream(rawString: ")")
let rule = FuncCallArgsRule(expressionRule: StubRule(runCommand: { .init(value: nil, stream: $0) }).erase())
// Act
let res = try rule.run(with: stream)
// Assert
XCTAssertTrue(res.value.isEmpty)
XCTAssertEqual(res.stream.current(), ")")
}
func testSingleArgWillBeParsed() throws {
// Arrange
let stream = try StringStream(rawString: "arg1)")
let rule = FuncCallArgsRule(expressionRule: StubRule(runCommand: {
.init(value: nil, stream: $0)
}).erase())
// Act
let res = try rule.run(with: stream)
// Assert
XCTAssertEqual(res.value.count, 1)
XCTAssertEqual(res.stream.current(), ")")
guard ExpressionNode.anyName(let name) = res.value else {
XCTFail("Result should be expression not but got \(res)")
}
}
}
| 24.881356 | 116 | 0.578338 |
c9e98e756745f39a29ebda68ae773150eda88abb | 1,062 | kt | Kotlin | libs/ui/src/main/kotlin/com/illiarb/tmdbclient/libs/ui/base/viewmodel/BaseViewModel.kt | ilya-rb/Tmdb-Client | 6b160dbdbf5b81aa7dfec467a682cdeb14bebe28 | [
"MIT"
] | 4 | 2020-06-25T17:43:09.000Z | 2021-03-01T06:38:10.000Z | libs/ui/src/main/kotlin/com/illiarb/tmdbclient/libs/ui/base/viewmodel/BaseViewModel.kt | ilya-rb/Tmdb-Client | 6b160dbdbf5b81aa7dfec467a682cdeb14bebe28 | [
"MIT"
] | 27 | 2020-04-10T08:29:04.000Z | 2020-11-02T20:35:25.000Z | libs/ui/src/main/kotlin/com/illiarb/tmdbclient/libs/ui/base/viewmodel/BaseViewModel.kt | ilya-rb/Tmdb-Client | 6b160dbdbf5b81aa7dfec467a682cdeb14bebe28 | [
"MIT"
] | 2 | 2020-02-13T22:32:42.000Z | 2020-06-25T17:43:09.000Z | package com.illiarb.tmdbclient.libs.ui.base.viewmodel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import androidx.lifecycle.ViewModel as AndroidViewModel
abstract class BaseViewModel<State, Event>(initialState: State) : AndroidViewModel(),
ViewModel<State, Event> {
private val _state = MutableStateFlow(initialState)
private val _events = Channel<Event>(Channel.RENDEZVOUS)
override val events: SendChannel<Event>
get() = _events
override val state: StateFlow<State>
get() = _state
protected val currentState: State
get() = _state.value
protected fun setState(block: State.() -> State) {
_state.value = block(_state.value)
}
init {
viewModelScope.launch {
_events.consumeEach(::onUiEvent)
}
}
protected open fun onUiEvent(event: Event) = Unit
} | 27.947368 | 85 | 0.770245 |
b26eca736db6ba0b8a4bec4a8b5c3b398bc615c5 | 324 | swift | Swift | validation-test/compiler_crashers_fixed/02111-swift-declcontext-lookupqualified.swift | ghostbar/swift-lang.deb | b1a887edd9178a0049a0ef839c4419142781f7a0 | [
"Apache-2.0"
] | 10 | 2015-12-25T02:19:46.000Z | 2021-11-14T15:37:57.000Z | validation-test/compiler_crashers_fixed/02111-swift-declcontext-lookupqualified.swift | ghostbar/swift-lang.deb | b1a887edd9178a0049a0ef839c4419142781f7a0 | [
"Apache-2.0"
] | 2 | 2016-02-01T08:51:00.000Z | 2017-04-07T09:04:30.000Z | validation-test/compiler_crashers_fixed/02111-swift-declcontext-lookupqualified.swift | ghostbar/swift-lang.deb | b1a887edd9178a0049a0ef839c4419142781f7a0 | [
"Apache-2.0"
] | 3 | 2016-04-02T15:05:27.000Z | 2019-08-19T15:25:02.000Z | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
enum B : T
let g : a {
class C<h : d where B == Swift.h = 0)() { c<Int>) -> {
class func compose(e(")
func c
| 27 | 87 | 0.679012 |
8ae3fdebf5ab941d641a5a225b5dff1b29abd8c9 | 37,495 | rs | Rust | src/diagnostics/archivist/src/archive/mod.rs | zarelaky/fuchsia | 858cc1914de722b13afc2aaaee8a6bd491cd8d9a | [
"BSD-3-Clause"
] | null | null | null | src/diagnostics/archivist/src/archive/mod.rs | zarelaky/fuchsia | 858cc1914de722b13afc2aaaee8a6bd491cd8d9a | [
"BSD-3-Clause"
] | null | null | null | src/diagnostics/archivist/src/archive/mod.rs | zarelaky/fuchsia | 858cc1914de722b13afc2aaaee8a6bd491cd8d9a | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::{
component_events::{
ComponentEvent, ComponentEventData, ComponentEventStream, Data, InspectReaderData,
RealmPath,
},
configs, diagnostics, inspect,
},
anyhow::{format_err, Error},
chrono::prelude::*,
fuchsia_inspect_contrib::{inspect_log, nodes::BoundedListNode},
futures::StreamExt,
itertools::Itertools,
lazy_static::lazy_static,
parking_lot::{Mutex, RwLock},
regex::Regex,
serde_derive::{Deserialize, Serialize},
serde_json::Deserializer,
std::collections::BTreeMap,
std::ffi::{OsStr, OsString},
std::fs,
std::io::Write,
std::path::{Path, PathBuf},
std::sync::Arc,
};
// Keep only the 50 most recent events.
static INSPECT_LOG_WINDOW_SIZE: usize = 50;
/// Archive represents the top-level directory tree for the Archivist's storage.
pub struct Archive {
/// The path to the Archive on disk.
path: PathBuf,
}
/// Stats for a particular event group of files.
#[derive(Debug, Eq, PartialEq)]
pub struct EventFileGroupStats {
/// The number of files associated with this group.
pub file_count: usize,
/// The size of those files on disk.
pub size: u64,
}
const DATED_DIRECTORY_REGEX: &str = r"^(\d{4}-\d{2}-\d{2})$";
const EVENT_PREFIX_REGEX: &str = r"^(\d{2}:\d{2}:\d{2}.\d{3})-";
const EVENT_LOG_SUFFIX_REGEX: &str = r"event.log$";
pub type EventFileGroupStatsMap = BTreeMap<String, EventFileGroupStats>;
impl Archive {
/// Opens an Archive at the given path, returning an error if it does not exist.
pub fn open(path: impl Into<PathBuf>) -> Result<Self, Error> {
let path: PathBuf = path.into();
if path.is_dir() {
Ok(Archive { path })
} else {
Err(format_err!("{} is not a directory", path.display()))
}
}
/// Returns a vector of EventFileGroups and their associated stats from all dates covered by
/// this archive.
pub fn get_event_group_stats(&self) -> Result<EventFileGroupStatsMap, Error> {
let mut output = EventFileGroupStatsMap::new();
for date in self.get_dates()? {
for group in self.get_event_file_groups(&date)? {
let file_count = 1 + group.event_files.len();
let size = group.size()?;
output.insert(group.log_file_path(), EventFileGroupStats { file_count, size });
}
}
Ok(output)
}
/// Returns a vector of the dated directory names in the archive, in sorted order.
pub fn get_dates(&self) -> Result<Vec<String>, Error> {
lazy_static! {
static ref RE: Regex = Regex::new(DATED_DIRECTORY_REGEX).unwrap();
}
Ok(self
.path
.read_dir()?
.filter_map(|file| file.ok())
.filter_map(|entry| {
let name = entry.file_name().into_string().unwrap_or_default();
let is_dir = entry.file_type().and_then(|t| Ok(t.is_dir())).unwrap_or(false);
if RE.is_match(&name) && is_dir {
Some(name)
} else {
None
}
})
.sorted()
.collect())
}
/// Returns a vector of file groups in the given dated directory, in sorted order.
pub fn get_event_file_groups(&self, date: &str) -> Result<Vec<EventFileGroup>, Error> {
lazy_static! {
static ref GROUP_RE: Regex = Regex::new(EVENT_PREFIX_REGEX).unwrap();
static ref LOG_FILE_RE: Regex =
Regex::new(&(EVENT_PREFIX_REGEX.to_owned() + EVENT_LOG_SUFFIX_REGEX)).unwrap();
}
Ok(self
.path
.join(date)
.read_dir()?
.filter_map(|dir_entry| dir_entry.ok())
.filter_map(|entry| {
let is_file = entry.metadata().and_then(|meta| Ok(meta.is_file())).unwrap_or(false);
if !is_file {
return None;
}
let name = entry.file_name().into_string().unwrap_or_default();
let captures = if let Some(captures) = GROUP_RE.captures(&name) {
captures
} else {
return None;
};
if LOG_FILE_RE.is_match(&name) {
Some((captures[1].to_owned(), EventFileGroup::new(Some(entry.path()), vec![])))
} else {
Some((captures[1].to_owned(), EventFileGroup::new(None, vec![entry.path()])))
}
})
.sorted_by(|a, b| Ord::cmp(&a.0, &b.0))
.group_by(|x| x.0.clone())
.into_iter()
.filter_map(|(_, entries)| {
let ret = entries.map(|(_, entry)| entry).fold(
EventFileGroup::new(None, vec![]),
|mut acc, next| {
acc.accumulate(next);
acc
},
);
match ret.log_file {
Some(_) => Some(ret),
_ => None,
}
})
.collect())
}
/// Get the path to the Archive directory.
pub fn get_path(&self) -> &Path {
return &self.path;
}
}
/// Represents information about a group of event files.
#[derive(Debug, PartialEq, Eq)]
pub struct EventFileGroup {
/// The file containing a log of events for the group.
log_file: Option<PathBuf>,
/// The event files referenced in the log.
event_files: Vec<PathBuf>,
}
pub type EventError = serde_json::error::Error;
impl EventFileGroup {
/// Constructs a new wrapper for a group of event files.
fn new(log_file: Option<PathBuf>, event_files: Vec<PathBuf>) -> Self {
EventFileGroup { log_file, event_files }
}
/// Supports folding multiple partially filled out groups together.
fn accumulate(&mut self, other: EventFileGroup) {
match self.log_file {
None => {
self.log_file = other.log_file;
}
_ => (),
};
self.event_files.extend(other.event_files.into_iter());
}
/// Deletes this group from disk.
///
/// Returns stats on the files removed on success.
pub fn delete(self) -> Result<EventFileGroupStats, Error> {
let size = self.size()?;
// There is 1 log file + each event file removed by this operation.
let file_count = 1 + self.event_files.len();
vec![self.log_file.unwrap()]
.into_iter()
.chain(self.event_files.into_iter())
.map(|path| -> Result<(), Error> {
fs::remove_file(&path)?;
Ok(())
})
.collect::<Result<(), Error>>()?;
Ok(EventFileGroupStats { file_count, size })
}
/// Gets the path to the log file for this group.
pub fn log_file_path(&self) -> String {
self.log_file.as_ref().expect("missing log file path").to_string_lossy().to_string()
}
/// Returns the size of all event files from this group on disk.
pub fn size(&self) -> Result<u64, Error> {
let log_file = match &self.log_file {
None => {
return Err(format_err!("Log file is not specified"));
}
Some(log_file) => log_file.clone(),
};
itertools::chain(&[log_file], self.event_files.iter())
.map(|path| {
fs::metadata(&path)
.or_else(|_| Err(format_err!("Failed to get size for {:?}", path)))
})
.map(|meta| {
meta.and_then(|value| {
if value.is_file() {
Ok(value.len())
} else {
Err(format_err!("Path is not a file"))
}
})
})
.fold_results(0, std::ops::Add::add)
}
/// Returns an iterator over the events stored in the log file.
pub fn events(&self) -> Result<impl Iterator<Item = Result<Event, EventError>>, Error> {
let file =
fs::File::open(&self.log_file.as_ref().ok_or(format_err!("Log file not specified"))?)?;
Ok(Deserializer::from_reader(file).into_iter::<Event>())
}
/// Returns the path to the parent directory containing this group.
pub fn parent_directory(&self) -> Result<&Path, Error> {
self.log_file
.as_ref()
.ok_or(format_err!("Log file not specified"))?
.parent()
.ok_or(format_err!("Log file has no parent directory"))
}
}
/// Represents a single event in the log.
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)]
pub struct Event {
timestamp_nanos: u64,
event_type: String,
component_name: String,
component_instance: String,
realm_path: String,
event_files: Vec<String>,
}
fn datetime_to_timestamp<T: TimeZone>(t: &DateTime<T>) -> u64 {
(t.timestamp() * 1_000_000_000 + t.timestamp_subsec_nanos() as i64) as u64
}
impl Event {
/// Create a new Event at the current time.
pub fn new(
event_type: impl ToString,
component_name: impl ToString,
component_instance: impl ToString,
realm_path: RealmPath,
) -> Self {
Self::new_with_time(Utc::now(), event_type, component_name, component_instance, realm_path)
}
/// Create a new Event at the given time.
pub fn new_with_time<T: TimeZone>(
time: DateTime<T>,
event_type: impl ToString,
component_name: impl ToString,
component_instance: impl ToString,
realm_path: RealmPath,
) -> Self {
Event {
timestamp_nanos: datetime_to_timestamp(&time),
event_type: event_type.to_string(),
component_name: component_name.to_string(),
component_instance: component_instance.to_string(),
realm_path: realm_path.into(),
event_files: vec![],
}
}
/// Get the timestamp of this event in the given timezone.
pub fn get_timestamp<T: TimeZone>(&self, time_zone: T) -> DateTime<T> {
let seconds = self.timestamp_nanos / 1_000_000_000;
let nanos = self.timestamp_nanos % 1_000_000_000;
time_zone.timestamp(seconds as i64, nanos as u32)
}
/// Get the vector of event files for this event.
pub fn get_event_files(&self) -> &Vec<String> {
&self.event_files
}
/// Add an event file to this event.
pub fn add_event_file(&mut self, file: impl AsRef<OsStr>) {
self.event_files.push(file.as_ref().to_string_lossy().to_string());
}
}
/// Structure that wraps an Archive and supports writing to it.
pub struct ArchiveWriter {
/// The opened Archive to write to.
archive: Archive,
/// A writer for the currently opened event file group.
open_log: EventFileGroupWriter,
group_stats: EventFileGroupStatsMap,
}
impl ArchiveWriter {
/// Open a directory as an archive.
///
/// If the directory does not exist, it will be created.
pub fn open(path: impl Into<PathBuf>) -> Result<Self, Error> {
let path: PathBuf = path.into();
if !path.exists() {
fs::create_dir_all(&path)?;
}
let archive = Archive::open(&path)?;
let open_log = EventFileGroupWriter::new(path)?;
let mut group_stats = archive.get_event_group_stats()?;
group_stats.remove(&open_log.get_log_file_path().to_string_lossy().to_string());
diagnostics::set_group_stats(&group_stats);
Ok(ArchiveWriter { archive, open_log, group_stats })
}
/// Get the readable Archive from this writer.
pub fn get_archive(&self) -> &Archive {
&self.archive
}
/// Get the currently opened log writer for this Archive.
pub fn get_log(&mut self) -> &mut EventFileGroupWriter {
&mut self.open_log
}
/// Rotates the log by closing the current EventFileGroup and opening a new one.
///
/// Returns the name and stats for the just-closed EventFileGroup.
pub fn rotate_log(&mut self) -> Result<(PathBuf, EventFileGroupStats), Error> {
let mut temp_log = EventFileGroupWriter::new(self.archive.get_path())?;
std::mem::swap(&mut self.open_log, &mut temp_log);
temp_log.close()
}
fn add_group_stat(&mut self, log_file_path: &Path, stat: EventFileGroupStats) {
self.group_stats.insert(log_file_path.to_string_lossy().to_string(), stat);
diagnostics::set_group_stats(&self.group_stats);
}
fn remove_group_stat(&mut self, log_file_path: &Path) {
self.group_stats.remove(&log_file_path.to_string_lossy().to_string());
diagnostics::set_group_stats(&self.group_stats);
}
fn archived_size(&self) -> u64 {
let mut ret = 0;
for (_, v) in &self.group_stats {
ret += v.size;
}
ret
}
}
/// A writer that wraps a particular group of event files.
///
/// This struct supports writing events to the log file with associated event files through
/// |EventBuilder|.
pub struct EventFileGroupWriter {
/// An opened file to write log events to.
log_file: fs::File,
/// The path to the log file.
log_file_path: PathBuf,
/// The path to the directory containing this file group.
directory_path: PathBuf,
/// The prefix for files related to this file group.
file_prefix: String,
/// The number of records written to the log file.
records_written: usize,
/// The number of bytes written for this group, including event files.
bytes_stored: usize,
/// The number of files written for this group, including event files.
files_stored: usize,
}
impl EventFileGroupWriter {
/// Create a new writable event file group.
///
/// This opens or creates a dated directory in the archive and initializes a log file for the
/// event file group.
pub fn new(archive_path: impl AsRef<Path>) -> Result<Self, Error> {
EventFileGroupWriter::new_with_time(Utc::now(), archive_path)
}
/// Creates a new writable event file group using the given time for dating the directories and
/// files.
fn new_with_time(time: DateTime<Utc>, archive_path: impl AsRef<Path>) -> Result<Self, Error> {
let directory_path = archive_path.as_ref().join(time.format("%Y-%m-%d").to_string());
fs::create_dir_all(&directory_path)?;
let file_prefix = time.format("%H:%M:%S%.3f-").to_string();
let log_file_path = directory_path.join(file_prefix.clone() + "event.log");
let log_file = fs::File::create(&log_file_path)?;
Ok(EventFileGroupWriter {
log_file,
log_file_path,
directory_path,
file_prefix,
records_written: 0,
bytes_stored: 0,
files_stored: 1,
})
}
/// Create a new event builder for adding an event to this group.
pub fn new_event(
&mut self,
event_type: impl ToString,
component_name: impl ToString,
component_instance: impl ToString,
realm_path: RealmPath,
) -> EventBuilder<'_> {
EventBuilder {
writer: self,
event: Event::new(event_type, component_name, component_instance, realm_path),
event_files: Ok(vec![]),
event_file_size: 0,
}
}
/// Gets the path to the log file for this group.
pub fn get_log_file_path(&self) -> &Path {
&self.log_file_path
}
/// Gets the stats for the event file group.
pub fn get_stats(&self) -> EventFileGroupStats {
EventFileGroupStats { file_count: self.files_stored, size: self.bytes_stored as u64 }
}
/// Write an event to the log.
///
/// Returns the number of bytes written on success.
fn write_event(&mut self, event: &Event, extra_files_size: usize) -> Result<usize, Error> {
let value = serde_json::to_string(&event)? + "\n";
self.log_file.write_all(value.as_ref())?;
self.bytes_stored += value.len() + extra_files_size;
self.records_written += 1;
self.files_stored += event.event_files.len();
Ok(value.len())
}
/// Synchronize the log with underlying storage.
fn sync(&mut self) -> Result<(), Error> {
Ok(self.log_file.sync_all()?)
}
/// Close this EventFileGroup, returning stats of what was written.
fn close(mut self) -> Result<(PathBuf, EventFileGroupStats), Error> {
self.sync()?;
Ok((
self.log_file_path,
EventFileGroupStats { file_count: self.files_stored, size: self.bytes_stored as u64 },
))
}
}
/// This struct provides a builder interface for adding event information to an individual log
/// entry before adding it to the log.
pub struct EventBuilder<'a> {
/// The writer this is building an event for.
writer: &'a mut EventFileGroupWriter,
/// The partial event being built.
event: Event,
/// The list of event files that were created so far. If this contains Error, writing
/// event files failed. Building will return the error.
event_files: Result<Vec<PathBuf>, Error>,
/// The total number of bytes written into event files.
event_file_size: usize,
}
fn delete_files(files: &Vec<PathBuf>) -> Result<(), Error> {
files
.iter()
.map(|file| -> Result<(), Error> { Ok(fs::remove_file(&file)?) })
.fold_results((), |_, _| ())
}
impl<'a> EventBuilder<'a> {
/// Build the event and write it to the log.
///
/// Returns stats on success or the Error on failure.
/// If this method return an error, all event files on disk will be cleaned up.
pub fn build(mut self) -> Result<EventFileGroupStats, Error> {
let file_count;
if let Ok(event_files) = self.event_files.as_ref() {
file_count = event_files.len();
for path in event_files.iter() {
self.event.add_event_file(
path.file_name().ok_or_else(|| format_err!("missing file name"))?,
);
}
} else {
return Err(self.event_files.unwrap_err());
}
match self.writer.write_event(&self.event, self.event_file_size) {
Ok(bytes) => {
Ok(EventFileGroupStats { file_count, size: (self.event_file_size + bytes) as u64 })
}
Err(e) => {
self.invalidate(e);
Err(self.event_files.unwrap_err())
}
}
}
/// Add an event file to the event.
///
/// This method takes the name of a file and its contents and writes them into the archive.
pub fn add_event_file(mut self, name: impl AsRef<OsStr>, contents: &[u8]) -> Self {
if let Ok(file_vector) = self.event_files.as_mut() {
let mut file_name = OsString::from(format!(
"{}{}-",
self.writer.file_prefix, self.writer.records_written
));
file_name.push(name);
let path = self.writer.directory_path.join(file_name);
if let Err(e) = fs::write(&path, contents) {
self.invalidate(Error::from(e));
} else {
self.event_file_size += contents.len();
file_vector.push(path);
}
}
self
}
/// Invalidates this EventBuilder, meaning the value will not be written to the log.
fn invalidate(&mut self, error: Error) {
delete_files(&self.event_files.as_ref().unwrap_or(&vec![]))
.expect("Failed to delete files");
self.event_files = Err(error)
}
}
/// ArchivistState owns the tools needed to persist data
/// to the archive, as well as the service-specific repositories
/// that are populated by the archivist server and exposed in the
/// service sessions.
pub struct ArchivistState {
/// Writer for the archive. If a path was not configured it will be `None`.
writer: Option<ArchiveWriter>,
log_node: BoundedListNode,
configuration: configs::Config,
inspect_repository: Arc<RwLock<inspect::InspectDataRepository>>,
}
impl ArchivistState {
pub fn new(
configuration: configs::Config,
inspect_repository: Arc<RwLock<inspect::InspectDataRepository>>,
writer: Option<ArchiveWriter>,
) -> Result<Self, Error> {
let mut log_node = BoundedListNode::new(
diagnostics::root().create_child("events"),
INSPECT_LOG_WINDOW_SIZE,
);
inspect_log!(log_node, event: "Archivist started");
Ok(ArchivistState { writer, log_node, configuration, inspect_repository })
}
}
fn populate_inspect_repo(
state: &Arc<Mutex<ArchivistState>>,
inspect_reader_data: InspectReaderData,
) -> Result<(), Error> {
// The InspectReaderData should always contain a directory_proxy. Its existence
// as an Option is only to support mock objects for equality in tests.
let inspect_directory_proxy = inspect_reader_data.data_directory_proxy.unwrap();
let mut relative_moniker = inspect_reader_data.realm_path;
relative_moniker.push(inspect_reader_data.component_name.clone());
state.lock().inspect_repository.write().add(
inspect_reader_data.component_name,
inspect_reader_data.component_id,
relative_moniker,
inspect_directory_proxy,
)
}
fn remove_from_inspect_repo(
state: &Arc<Mutex<ArchivistState>>,
component_name: &str,
component_id: &str,
) {
state.lock().inspect_repository.write().remove(component_name, component_id);
}
async fn process_event(
state: Arc<Mutex<ArchivistState>>,
event: ComponentEvent,
) -> Result<(), Error> {
match event {
ComponentEvent::Start(data) => archive_event(&state, "START", data).await,
ComponentEvent::Stop(data) => {
remove_from_inspect_repo(&state, &data.component_name, &data.component_id);
archive_event(&state, "STOP", data).await
}
ComponentEvent::OutDirectoryAppeared(data) => populate_inspect_repo(&state, data),
}
}
async fn archive_event(
state: &Arc<Mutex<ArchivistState>>,
event_name: &str,
event_data: ComponentEventData,
) -> Result<(), Error> {
let mut state = state.lock();
let ArchivistState { writer, log_node, configuration, .. } = &mut *state;
let writer = if let Some(w) = writer.as_mut() {
w
} else {
return Ok(());
};
let max_archive_size_bytes = configuration.max_archive_size_bytes;
let max_event_group_size_bytes = configuration.max_event_group_size_bytes;
let mut log = writer.get_log().new_event(
event_name,
event_data.component_name,
event_data.component_id,
event_data.realm_path,
);
if let Some(data_map) = event_data.component_data_map {
for (path, object) in data_map {
match object {
Data::Empty | Data::DeprecatedFidl(_) | Data::Tree(_, None) => {}
Data::Vmo(vmo) | Data::Tree(_, Some(vmo)) => {
let mut contents = vec![0u8; vmo.get_size()? as usize];
vmo.read(&mut contents[..], 0)?;
// Truncate the bytes down to the last non-zero 4096-byte page of data.
// TODO(CF-830): Handle truncation of VMOs without reading the whole thing.
let mut last_nonzero = 0;
for (i, v) in contents.iter().enumerate() {
if *v != 0 {
last_nonzero = i;
}
}
if last_nonzero % 4096 != 0 {
last_nonzero = last_nonzero + 4096 - last_nonzero % 4096;
}
contents.resize(last_nonzero, 0);
log = log.add_event_file(path, &contents);
}
Data::File(contents) => {
log = log.add_event_file(path, &contents);
}
}
}
}
let current_group_stats = writer.get_log().get_stats();
if current_group_stats.size >= max_event_group_size_bytes {
let (path, stats) = writer.rotate_log()?;
inspect_log!(log_node, event:"Rotated log",
new_path: path.to_string_lossy().to_string());
writer.add_group_stat(&path, stats);
}
let archived_size = writer.archived_size();
let mut current_archive_size = current_group_stats.size + archived_size;
if current_archive_size > max_archive_size_bytes {
let dates = writer.get_archive().get_dates().unwrap_or_else(|e| {
eprintln!("Garbage collection failure");
inspect_log!(log_node, event: "Failed to get dates for garbage collection",
reason: format!("{:?}", e));
vec![]
});
for date in dates {
let groups = writer.get_archive().get_event_file_groups(&date).unwrap_or_else(|e| {
eprintln!("Garbage collection failure");
inspect_log!(log_node, event: "Failed to get event file",
date: &date,
reason: format!("{:?}", e));
vec![]
});
for group in groups {
let path = group.log_file_path();
match group.delete() {
Err(e) => {
inspect_log!(log_node, event: "Failed to remove group",
path: &path,
reason: format!(
"{:?}", e));
continue;
}
Ok(stat) => {
current_archive_size -= stat.size;
writer.remove_group_stat(&PathBuf::from(&path));
inspect_log!(log_node, event: "Garbage collected group",
path: &path,
removed_files: stat.file_count as u64,
removed_bytes: stat.size as u64);
}
};
if current_archive_size < max_archive_size_bytes {
return Ok(());
}
}
}
}
Ok(())
}
pub async fn run_archivist(
archivist_state: ArchivistState,
mut events: ComponentEventStream,
) -> Result<(), Error> {
let state = Arc::new(Mutex::new(archivist_state));
while let Some(event) = events.next().await {
process_event(state.clone(), event).await.unwrap_or_else(|e| {
let mut state = state.lock();
inspect_log!(state.log_node, event: "Failed to log event", result: format!("{:?}", e));
eprintln!("Failed to log event: {:?}", e);
});
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
use std::iter::FromIterator;
#[test]
fn archive_open() {
let path: PathBuf;
{
let dir = tempfile::tempdir().unwrap();
path = dir.path().to_path_buf();
assert_eq!(true, Archive::open(&path).is_ok());
}
assert_eq!(false, Archive::open(&path).is_ok());
}
#[test]
fn archive_get_dates() {
let dir = tempfile::tempdir().unwrap();
fs::create_dir(dir.path().join("2019-05-08")).unwrap();
fs::create_dir(dir.path().join("2019-04-10")).unwrap();
fs::create_dir(dir.path().join("2019-04-incorrect-format")).unwrap();
// Create a file with the correct format. It will not be included since it is not a
// directory.
fs::File::create(dir.path().join("2019-05-09")).unwrap();
let archive = Archive::open(dir.path()).unwrap();
assert_eq!(
vec!["2019-04-10".to_string(), "2019-05-08".to_string()],
archive.get_dates().unwrap()
);
}
fn write_test_to_file<T: AsRef<Path>>(path: T) {
let mut file = fs::File::create(path).expect("failed to create file");
write!(file, "test").expect("failed to write file");
file.sync_all().expect("failed to sync file");
}
#[test]
fn archive_get_file_groups() {
let dir = tempfile::tempdir().unwrap();
let dated_dir_path = dir.path().join("2019-05-08");
fs::create_dir(&dated_dir_path).unwrap();
// Event group with only log file.
let event_log_file_name = dated_dir_path.join("10:30:00.000-event.log");
write_test_to_file(&event_log_file_name);
// Event group with event files.
let aux_event_log_file_name = dated_dir_path.join("11:30:00.000-event.log");
let aux_file_1 = dated_dir_path.join("11:30:00.000-aux_file_1.info");
let aux_file_2 = dated_dir_path.join("11:30:00.000-aux_file_2.info");
write_test_to_file(&aux_event_log_file_name);
write_test_to_file(&aux_file_1);
write_test_to_file(&aux_file_2);
// Event group missing log file (invalid).
fs::File::create(dated_dir_path.join("12:30:00.000-aux_file_1.info")).unwrap();
fs::File::create(dated_dir_path.join("12:30:00.000-aux_file_2.info")).unwrap();
// Name does not match pattern (invalid).
fs::File::create(dated_dir_path.join("13:30:00-event.log")).unwrap();
// Directory rather than file (invalid).
fs::create_dir(dated_dir_path.join("14:30:00.000-event.log")).unwrap();
let archive = Archive::open(dir.path()).unwrap();
assert_eq!(
vec![
EventFileGroup::new(Some(event_log_file_name.clone()), vec![]),
EventFileGroup::new(
Some(aux_event_log_file_name.clone()),
vec![aux_file_1.clone(), aux_file_2.clone()]
)
],
archive.get_event_file_groups("2019-05-08").unwrap()
);
assert_eq!(
BTreeMap::from_iter(
vec![
(
event_log_file_name.to_string_lossy().to_string(),
EventFileGroupStats { file_count: 1, size: 4 }
),
(
aux_event_log_file_name.to_string_lossy().to_string(),
EventFileGroupStats { file_count: 3, size: 4 * 3 }
)
]
.into_iter()
),
archive.get_event_group_stats().unwrap()
);
for group in archive.get_event_file_groups("2019-05-08").unwrap() {
group.delete().unwrap();
}
assert_eq!(0, archive.get_event_file_groups("2019-05-08").unwrap().len());
// Open an empty directory.
fs::create_dir(dir.path().join("2019-05-07")).unwrap();
assert_eq!(0, archive.get_event_file_groups("2019-05-07").unwrap().len());
// Open a missing directory
assert_eq!(true, archive.get_event_file_groups("2019-05-06").is_err());
}
#[test]
fn event_file_group_size() {
let dir = tempfile::tempdir().unwrap();
write_test_to_file(dir.path().join("a"));
write_test_to_file(dir.path().join("b"));
write_test_to_file(dir.path().join("c"));
assert_eq!(
12,
EventFileGroup::new(
Some(dir.path().join("a")),
vec![dir.path().join("b"), dir.path().join("c")]
)
.size()
.expect("failed to get size")
);
assert_eq!(
4,
EventFileGroup::new(Some(dir.path().join("a")), vec![],)
.size()
.expect("failed to get size")
);
// Absent file "d" causes error.
assert_eq!(
true,
EventFileGroup::new(Some(dir.path().join("a")), vec![dir.path().join("d")],)
.size()
.is_err()
);
// Missing log file.
assert_eq!(true, EventFileGroup::new(None, vec![dir.path().join("b")],).size().is_err());
// Log file is actually a directory.
assert_eq!(
true,
EventFileGroup::new(Some(dir.path().to_path_buf()), vec![dir.path().join("b")],)
.size()
.is_err()
);
}
#[test]
fn event_creation() {
let time = Utc::now();
let realm_path = RealmPath(vec!["a".to_string(), "b".to_string()]);
let event = Event::new_with_time(time, "START", "component", "instance", realm_path);
assert_eq!(time, event.get_timestamp(Utc));
assert_eq!(
Event {
timestamp_nanos: datetime_to_timestamp(&time),
event_type: "START".to_string(),
component_name: "component".to_string(),
component_instance: "instance".to_string(),
realm_path: "a/b".to_string(),
event_files: vec![],
},
event
);
}
#[test]
fn event_ordering() {
let realm_path = RealmPath(vec!["a".to_string(), "b".to_string()]);
let event1 = Event::new("START", "a", "b", realm_path.clone());
let event2 = Event::new("END", "a", "b", realm_path);
assert!(
event1.get_timestamp(Utc) < event2.get_timestamp(Utc),
"Expected {:?} before {:?}",
event1.get_timestamp(Utc),
event2.get_timestamp(Utc)
);
}
#[test]
fn event_event_files() {
let realm_path = RealmPath(vec!["a".to_string(), "b".to_string()]);
let mut event = Event::new("START", "a", "b", realm_path);
event.add_event_file("f1");
assert_eq!(&vec!["f1"], event.get_event_files());
}
#[test]
fn event_file_group_writer() {
let dir = tempfile::tempdir().unwrap();
let mut writer = EventFileGroupWriter::new_with_time(
Utc.ymd(2019, 05, 08).and_hms_milli(12, 30, 14, 31),
dir.path(),
)
.expect("failed to create writer");
assert!(writer.sync().is_ok());
let meta = fs::metadata(dir.path().join("2019-05-08"));
assert!(meta.is_ok());
assert!(meta.unwrap().is_dir());
let meta = fs::metadata(dir.path().join("2019-05-08").join("12:30:14.031-event.log"));
assert!(meta.is_ok());
assert!(meta.unwrap().is_file());
let realm_path = RealmPath(vec!["a".to_string(), "b".to_string()]);
assert!(writer.new_event("START", "test", "0", realm_path.clone()).build().is_ok());
assert!(writer
.new_event("EXIT", "test", "0", realm_path)
.add_event_file("root.inspect", b"INSP TEST")
.build()
.is_ok());
let extra_file_path = dir.path().join("2019-05-08").join("12:30:14.031-1-root.inspect");
let meta = fs::metadata(&extra_file_path);
assert!(meta.is_ok());
assert!(meta.unwrap().is_file());
assert_eq!("INSP TEST", fs::read_to_string(&extra_file_path).unwrap());
}
#[test]
fn archive_writer() {
let dir = tempfile::tempdir().unwrap();
let mut archive =
ArchiveWriter::open(dir.path().join("archive")).expect("failed to create archive");
let realm_path = RealmPath(vec!["a".to_string(), "b".to_string()]);
archive
.get_log()
.new_event("START", "test", "0", realm_path.clone())
.build()
.expect("failed to write log");
archive
.get_log()
.new_event("STOP", "test", "0", realm_path)
.add_event_file("root.inspect", b"test")
.build()
.expect("failed to write log");
let mut events = vec![];
archive.get_archive().get_dates().unwrap().into_iter().for_each(|date| {
archive.get_archive().get_event_file_groups(&date).unwrap().into_iter().for_each(
|group| {
group.events().unwrap().for_each(|event| {
events.push(event.unwrap());
})
},
);
});
assert_eq!(2, events.len());
let (_, stats) = archive.rotate_log().unwrap();
assert_eq!(2, stats.file_count);
assert_ne!(0, stats.size);
let mut group_count = 0;
archive.get_archive().get_dates().unwrap().into_iter().for_each(|date| {
group_count += archive.get_archive().get_event_file_groups(&date).unwrap().len();
});
assert_eq!(2, group_count);
let realm_path = RealmPath(vec!["a".to_string(), "b".to_string()]);
let mut stats = archive
.get_log()
.new_event("STOP", "test", "0", realm_path)
.add_event_file("root.inspect", b"test")
.build()
.expect("failed to write log");
// Check the stats returned by the log; we add one to the file count for the log file
// itself.
stats.file_count += 1;
assert_eq!(stats, archive.get_log().get_stats());
}
}
| 35.272813 | 100 | 0.568529 |
2a4d159108b9e0635a4929498cd5d9411018f8ba | 501 | java | Java | src/main/java/ssll/rsm/pr/PropertyReader.java | 14104chk/ResultSetMapper | 0cc9c033b24d3af7e2bece784775c0cd401ac881 | [
"Apache-2.0"
] | 7 | 2021-07-09T08:14:08.000Z | 2021-11-25T03:24:44.000Z | src/main/java/ssll/rsm/pr/PropertyReader.java | 14104chk/SQL-Mapping | 0cc9c033b24d3af7e2bece784775c0cd401ac881 | [
"Apache-2.0"
] | null | null | null | src/main/java/ssll/rsm/pr/PropertyReader.java | 14104chk/SQL-Mapping | 0cc9c033b24d3af7e2bece784775c0cd401ac881 | [
"Apache-2.0"
] | null | null | null | package ssll.rsm.pr;
import java.sql.ResultSet;
import java.sql.SQLException;
import ssll.rsm.MappingContext;
import ssll.rsm.Property;
public interface PropertyReader {
public static final PropertyReader UNKNOWN_TYPE_READER = (MappingContext context, Property property, Class propertyRawType, ResultSet resultSet) -> resultSet.getObject(property.getColumnIndex());
public Object read(MappingContext context, Property property, Class propertyRawType, ResultSet resultSet) throws SQLException;
}
| 35.785714 | 196 | 0.826347 |
c279ef383713696513ed537fb03756182291f703 | 213 | go | Go | algorithm/sort/001_bubble_sort.go | yangzhengkun/goleetcode | 4b0f612dbf0746d48583c7bf985aec3a6aa11f68 | [
"MIT"
] | null | null | null | algorithm/sort/001_bubble_sort.go | yangzhengkun/goleetcode | 4b0f612dbf0746d48583c7bf985aec3a6aa11f68 | [
"MIT"
] | null | null | null | algorithm/sort/001_bubble_sort.go | yangzhengkun/goleetcode | 4b0f612dbf0746d48583c7bf985aec3a6aa11f68 | [
"MIT"
] | null | null | null | package sort
func BubbleSort(arr []int) []int {
n := len(arr)
for i := 0; i < n; i++ {
for j := 0; j < n-i-1; j++ {
if arr[j] > arr[j+1] {
arr[j+1], arr[j] = arr[j], arr[j+1]
}
}
}
return arr
}
| 15.214286 | 39 | 0.455399 |
7010b5c29a62130924edb19c3a61e86b0029e362 | 29 | lua | Lua | Dread Scripts (v1.0.3)/romfs/packs/maps/s010_cave/subareas/actors/characters/scorpius/scripts/scorpius.lua | MrMendelli/DreadScripts | b9b1d993655ef598ccb7a72027f461f208983b50 | [
"MIT"
] | null | null | null | Dread Scripts (v1.0.3)/romfs/packs/maps/s010_cave/subareas/actors/characters/scorpius/scripts/scorpius.lua | MrMendelli/DreadScripts | b9b1d993655ef598ccb7a72027f461f208983b50 | [
"MIT"
] | null | null | null | Dread Scripts (v1.0.3)/romfs/packs/maps/s010_cave/subareas/actors/characters/scorpius/scripts/scorpius.lua | MrMendelli/DreadScripts | b9b1d993655ef598ccb7a72027f461f208983b50 | [
"MIT"
] | 1 | 2022-02-15T00:18:22.000Z | 2022-02-15T00:18:22.000Z | function Scorpius.main()
end
| 9.666667 | 24 | 0.793103 |
781dcc6305f4bce05c1da202b475164bfa6c2fe1 | 2,075 | kt | Kotlin | app/src/main/java/com/example/androiddevchallenge/util/ImagesHandler.kt | kfurjan/puppy-finder | b5c9aab39902e90593aa51be44208ed72ec2542b | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/androiddevchallenge/util/ImagesHandler.kt | kfurjan/puppy-finder | b5c9aab39902e90593aa51be44208ed72ec2542b | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/androiddevchallenge/util/ImagesHandler.kt | kfurjan/puppy-finder | b5c9aab39902e90593aa51be44208ed72ec2542b | [
"Apache-2.0"
] | null | null | null | package com.example.androiddevchallenge.util
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.net.HttpURLConnection
private const val PICTURE_WIDTH = 750
private const val PICTURE_HEIGHT = 500
private const val QUALITY = 100
private const val TAG = "ImagesHandler"
fun downloadImageAndStore(context: Context, url: String, filename: String): String? {
val extension = url.substring(url.lastIndexOf("."))
var file: File = getFile(context, filename, extension)
try {
val con: HttpURLConnection = createGetHttpUrlConnection(url)
con.inputStream.use { `is` ->
FileOutputStream(file).use { fos ->
val bitmap = BitmapFactory.decodeStream(`is`)
val resizedBitmap: Bitmap =
getResizedBitmap(bitmap, PICTURE_WIDTH, PICTURE_HEIGHT)
val buffer = getBytesFromBitmap(resizedBitmap)
fos.write(buffer)
return file.absolutePath
}
}
} catch (e: Exception) { }
return null
}
private fun getBytesFromBitmap(bitmap: Bitmap): ByteArray {
val bos = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, QUALITY, bos)
return bos.toByteArray()
}
private fun getResizedBitmap(bitmap: Bitmap, newWidth: Int, newHeight: Int): Bitmap {
val scaleWidth = newWidth.toFloat() / bitmap.width
val scaleHeight = newHeight.toFloat() / bitmap.height
val matrix = Matrix()
matrix.postScale(scaleWidth, scaleHeight)
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, false)
}
private fun getFile(context: Context, filename: String, extension: String): File {
val dir: File? = context.applicationContext.getExternalFilesDir(null)
val file = File(dir, File.separator.toString() + filename + extension)
if (file.exists()) {
file.delete()
}
return file
}
| 32.421875 | 88 | 0.699277 |
fc700603045d389b0160a6bcb769a221d54fda4b | 162 | sql | SQL | OrderList.sql | sqljared/One-Bite-at-a-Time | 0a18774eb01ff804422f84f0a12cc43460d45933 | [
"MIT"
] | 1 | 2021-12-17T11:33:03.000Z | 2021-12-17T11:33:03.000Z | OrderList.sql | sqljared/One-Bite-at-a-Time | 0a18774eb01ff804422f84f0a12cc43460d45933 | [
"MIT"
] | null | null | null | OrderList.sql | sqljared/One-Bite-at-a-Time | 0a18774eb01ff804422f84f0a12cc43460d45933 | [
"MIT"
] | null | null | null | USE WideWorldImporters
GO
CREATE TYPE Sales.OrderList
AS TABLE(
OrderID INT NOT NULL,
INDEX IX_OrderList_OrderID (OrderID)
)
WITH (MEMORY_OPTIMIZED = ON);
GO
| 16.2 | 37 | 0.783951 |
869e0b9b26f4b44c2fed50dfcbc6acfa284aeafc | 469 | go | Go | main_test.go | claretnnamocha/peer-calls | aca2d66755fe3ca10e23beed802fa39e2f501fd5 | [
"Apache-2.0"
] | 1 | 2020-05-04T04:36:22.000Z | 2020-05-04T04:36:22.000Z | main_test.go | claretnnamocha/peer-calls | aca2d66755fe3ca10e23beed802fa39e2f501fd5 | [
"Apache-2.0"
] | 2 | 2021-03-10T15:48:08.000Z | 2021-05-11T11:49:48.000Z | main_test.go | pgomez465/20 | a71616e627f5aa71d9660e7e34168003b31bf8e8 | [
"Apache-2.0"
] | null | null | null | package main
import (
"fmt"
"testing"
"github.com/stretchr/testify/require"
)
func TestPanicOnError_panic(t *testing.T) {
defer func() {
err, ok := recover().(error)
require.Equal(t, true, ok)
require.NotNil(t, err)
require.Regexp(t, "an error", err.Error())
}()
panicOnError(fmt.Errorf("test"), "an error")
}
func TestPanicOnError_noerror(t *testing.T) {
defer func() {
err := recover()
require.Nil(t, err)
}()
panicOnError(nil, "an error")
}
| 17.37037 | 45 | 0.656716 |
af283acbbe9322930611b05cea6229303e870007 | 477 | rb | Ruby | bin/dwd_observation.rb | SettRaziel/dwd_observations | 0c397787d007d97777d071c97b9f453b45fef850 | [
"MIT"
] | null | null | null | bin/dwd_observation.rb | SettRaziel/dwd_observations | 0c397787d007d97777d071c97b9f453b45fef850 | [
"MIT"
] | 9 | 2020-12-02T19:41:53.000Z | 2022-03-01T21:21:26.000Z | bin/dwd_observation.rb | SettRaziel/dwd_observations | 0c397787d007d97777d071c97b9f453b45fef850 | [
"MIT"
] | null | null | null | require "ruby_utils/string"
require "dwd_observations"
begin
DwdObservations.initialize(ARGV)
parameter_repository = DwdObservations.parameter_handler.repository
if (parameter_repository.parameters[:help])
DwdObservations.print_help
elsif (parameter_repository.parameters[:version])
DwdObservations.print_version
else
DwdObservations.handle_parameters
end
rescue StandardError, NotImplementedError => e
DwdObservations.print_error(e.message)
end
| 25.105263 | 69 | 0.813417 |
9d347deb11505d3b29deb0f9084e113434581e0e | 20,973 | lua | Lua | Games/60 Second Heist/scripts/game.lua | XeduR/Solar2D-Projects | b3e2087c77d2397ef99d8a4bfd21fd4604f31b3b | [
"MIT"
] | 6 | 2021-08-02T13:47:06.000Z | 2022-03-14T04:07:15.000Z | Games/60 Second Heist/scripts/game.lua | XeduR/Solar2D-Projects | b3e2087c77d2397ef99d8a4bfd21fd4604f31b3b | [
"MIT"
] | null | null | null | Games/60 Second Heist/scripts/game.lua | XeduR/Solar2D-Projects | b3e2087c77d2397ef99d8a4bfd21fd4604f31b3b | [
"MIT"
] | 4 | 2020-12-05T17:45:02.000Z | 2022-03-14T04:07:22.000Z | local composer = require( "composer" )
local scene = composer.newScene()
local physics = require("physics")
physics.start()
physics.setGravity( 0, 0 )
local sfx = require( "scripts.sfx" )
local screen = require( "scripts.screen" )
local levelData = require( "data.levels" )
local clock = require( "scripts.clock" )
-------------------------------
local _cos = math.cos
local _sin = math.sin
local _rad = math.rad
local _max = math.max
local _min = math.min
local _sqrt = math.sqrt
local _floor = math.floor
local _dRemove = display.remove
-------------------------------
local moveSpeed = 2.5
local visionRange = 160
local alertRadius = 20
local playerRadius = 16
local raycastAngles = 60
local raycastAnglesH = raycastAngles*0.5
local caughtDistance = alertRadius+8
local halfW = screen.width*0.5
local halfH = screen.height*0.5
local moveSpeedDiagonal = _sqrt(moveSpeed)
-------------------------------
local groupGround = display.newGroup()
local groupObjects = display.newGroup()
local groupVision = display.newGroup()
local groupWalls = display.newGroup()
local snapshot = display.newSnapshot( groupVision, screen.width, screen.height )
snapshot:translate( halfW, halfH )
local groupUI = display.newGroup()
local overlay = display.newRect(0,0,screen.width, screen.height)
overlay:setFillColor(0)
snapshot.group:insert(overlay)
local whoCaught = display.newImage( groupUI, "images/caught.png", 0, 0 )
whoCaught.alpha = 0
whoCaught.anchorY = 1
local guard = {}
local camera = {}
local action = {}
local object = {}
local player
local lootText
local playerSeen = false
local blockTouch = true
local gotLoot = false
local canMove = false
local lootCount = 0
local totalLoot = 0
local gameClock
local buttonMenu
local visionBlock
local startTimer
local countdown
local gameover
transition.ignoreEmptyReference = true
local currentFrame = 0
local framesUntilSwap = 10
local function updateGuards()
for i = 1, #guard do
local t = guard[i]
t:vision()
-- Check if player is too close to the guard.
if _sqrt((player.x-t.x)^2 + (player.y-t.y)^2) < caughtDistance then
if not playerSeen then
playerSeen = true
whoCaught.x, whoCaught.y = t.x, t.y-10
whoCaught.alpha = 1
gameover("guard")
Runtime:removeEventListener( "enterFrame", updateGuards )
end
end
-- Update the guard's animation.
if t.x ~= t.prevX or t.y ~= t.prevY then
t.currentFrame = t.currentFrame+1
if t.currentFrame == framesUntilSwap then
t.currentFrame = 0
t.usingFrame1 = not t.usingFrame1
if t.usingFrame1 then
t.fill = t.frame1
else
t.fill = t.frame2
end
end
end
t.prevX, t.prevY = t.x, t.y
end
for i = 1, #camera do
local cam = camera[i]
_dRemove(cam.scan)
cam.scan = nil
local angle = _rad(cam.rotation)
local xStart = cam.x
local yStart = cam.y
local xEnd = cam.x+visionRange*_cos(angle)
local yEnd = cam.x-visionRange*_sin(angle)
local hits = physics.rayCast( xStart, yStart, xEnd, yEnd, "closest" )
if ( hits ) then
cam.scan = display.newLine( groupWalls, xStart, yStart, hits[1].position.x, hits[1].position.y )
cam.scan:toBack()
cam.scan.strokeWidth = 2
cam.scan:setStrokeColor( 0.9, 0, 0 )
if hits[1].object.isPlayer then
playerSeen = true
whoCaught.x, whoCaught.y = cam.x, cam.y-10
whoCaught.alpha = 1
gameover("camera")
Runtime:removeEventListener( "enterFrame", updateGuards )
end
else
cam.scan = display.newLine( groupWalls, xStart, yStart, xEnd, yEnd )
cam.scan:toBack()
cam.scan.strokeWidth = 2
cam.scan:setStrokeColor( 0.9, 0, 0 )
end
end
end
local function movePlayer()
if player then
local rotation
if action["a"] or action["left"] then
if action["w"] or action["up"] then
rotation = -135
player:translate( -moveSpeedDiagonal, -moveSpeedDiagonal )
elseif action["s"] or action["down"] then
rotation = 135
player:translate( -moveSpeedDiagonal, moveSpeedDiagonal )
else
rotation = 180
player:translate( -moveSpeed, 0 )
end
elseif action["d"] or action["right"] then
if action["w"] or action["up"] then
rotation = -45
player:translate( moveSpeedDiagonal, -moveSpeedDiagonal )
elseif action["s"] or action["down"] then
rotation = 45
player:translate( moveSpeedDiagonal, moveSpeedDiagonal )
else
rotation = 0
player:translate( moveSpeed, 0 )
end
else
if action["w"] or action["up"] then
rotation = -90
player:translate( 0, -moveSpeed )
elseif action["s"] or action["down"] then
rotation = 90
player:translate( 0, moveSpeed )
end
end
if rotation then
currentFrame = currentFrame+1
if currentFrame == framesUntilSwap then
currentFrame = 0
player.usingFrame1 = not player.usingFrame1
if player.usingFrame1 then
player.fill = player.frame1
else
player.fill = player.frame2
end
end
player.rotation = rotation
end
if gotLoot then
if _sqrt((player.x-player.escapeRadius.x)^2+(player.y-player.escapeRadius.y)^2) <= player.escapeRadius.width*0.5 then
gameover("won")
end
end
end
end
local function onKeyEvent( event )
if event.phase == "down" then
action[event.keyName] = true
else
action[event.keyName] = false
end
end
local function pickupLoot(loot)
_dRemove(loot)
loot = nil
gotLoot = true
lootCount = lootCount+1
lootText.text = "Loot left: "..totalLoot-lootCount
player.escapeRadius.alpha = 1
end
local function onCollision( self, event )
if ( event.phase == "began" ) then
if self.isPlayer and event.other.isLoot and not event.other.taken then
event.other.taken = true
pickupLoot(event.other)
end
end
end
local function newGuard( input )
local object = display.newRect( groupObjects, input.x, input.y, 20, 20 )
object.fov = {}
object.frame1 = {
type = "image",
filename = "images/guard_walk1.png"
}
object.frame2 = {
type = "image",
filename = "images/guard_walk2.png"
}
object.prevX, object.prevY = x or 0, y or 0
object.currentFrame = 0
object.usingFrame1 = true
object.fill = object.frame1
object.aura = display.newCircle( groupVision, object.x-halfW, object.y-halfH, alertRadius )
snapshot.group:insert(object.aura)
object.currentRoute = 0
object.route = {}
for i = 1, #input.route do
local r = input.route[i]
object.route[i] = { x=r.x, y=r.y, r=r.r, delay=r.delay, time=r.time }
end
function object:vision()
if not playerSeen then
self.aura.x, self.aura.y = self.x-halfW, self.y-halfH
for i = 1, #self.fov do
self.fov[i] = nil
end
self.fov[1], self.fov[2] = self.x, self.y
for i = 1, raycastAngles do
local xStart = self.x
local yStart = self.y
local xEnd = _floor(self.x+visionRange*_cos(_rad(self.rotation-raycastAnglesH+i))+0.5)
local yEnd = _floor(self.y+visionRange*_sin(_rad(self.rotation-raycastAnglesH+i))+0.5)
local hits = physics.rayCast( xStart, yStart, xEnd, yEnd, "closest" )
if hits then
if hits[1].object.isPlayer then
if not playerSeen then
playerSeen = true
whoCaught.x, whoCaught.y = self.x, self.y-20
whoCaught.alpha = 1
gameover("guard")
Runtime:removeEventListener( "enterFrame", updateGuards )
end
local hits = physics.rayCast( xStart, yStart, xEnd, yEnd, "sorted" )
if hits and #hits > 1 then
xEnd, yEnd = _floor(hits[2].position.x+0.5), _floor(hits[2].position.y+0.5)
end
else
xEnd, yEnd = _floor(hits[1].position.x+0.5), _floor(hits[1].position.y+0.5)
end
end
if xEnd ~= self.fov[#self.fov-1] or yEnd ~= self.fov[#self.fov] then
self.fov[#self.fov+1], self.fov[#self.fov+2] = xEnd, yEnd
end
end
_dRemove(self.sight)
self.sight = nil
-- TODO: The sight, i.e. field of vision, is a but bumpy. If time, then fix.
self.sight = display.newPolygon( --groupVision,
(_min( self.fov[1], self.fov[3], self.fov[#self.fov-1] )+_max( self.fov[1], self.fov[3], self.fov[#self.fov-1] ))*0.5-halfW,
(_min( self.fov[2], self.fov[4], self.fov[#self.fov] )+_max( self.fov[2], self.fov[4], self.fov[#self.fov] ))*0.5-halfH,
self.fov
)
snapshot.group:insert(self.sight)
end
snapshot:invalidate()
end
guard[#guard+1] = object
end
local function returnToMenu( event )
if event.phase == "ended" then
blockTouch = true
if startTimer then
timer.cancel( startTimer )
startTimer = nil
end
composer.gotoScene( "scripts.menu", {
time=500,
effect="slideRight",
params={}
})
end
return true
end
function gameover( reason )
transition.cancelAll()
local delay = 1500
if reason == "time" then
countdown.text = "Time's up!"
elseif reason == "guard" then
countdown.text = "A guard saw you!"
elseif reason == "camera" then
countdown.text = "A camera saw you!"
elseif reason == "won" then
countdown.text = "Success!"
delay = 0
local temp = display.newText( "You collected "..lootCount.." out of "..totalLoot.." loot!", screen.xCenter, screen.yCenter+120, "fonts/Action_Man.ttf", 28 )
temp.alpha = 0
transition.to( temp, {time=500,alpha=1})
timer.performWithDelay( 4000+delay, function()
_dRemove(temp)
end )
end
transition.to( countdown, {delay=delay,time=250,alpha=1,xScale=1,yScale=1} )
transition.to( visionBlock, {delay=delay,time=250,alpha=1} )
gameClock:stop()
Runtime:removeEventListener( "enterFrame", movePlayer )
Runtime:removeEventListener( "key", onKeyEvent )
if not playerSeen then
playerSeen = true
Runtime:removeEventListener( "enterFrame", updateGuards )
end
startTimer = timer.performWithDelay( 4000+delay, function()
returnToMenu({phase="ended"})
end )
end
local function outOfTime()
gameover("time")
end
local patrolTimePerPixel = 20
local function patrolRoute( guard )
guard.currentRoute = guard.currentRoute+1
if guard.currentRoute > #guard.route then
guard.currentRoute = 1
end
transition.to( guard, {
time = guard.route[guard.currentRoute].time or _sqrt((guard.x-(guard.route[guard.currentRoute].x or guard.x))^2+(guard.y-(guard.route[guard.currentRoute].y or guard.y))^2 )*patrolTimePerPixel,
x = guard.route[guard.currentRoute].x,
y = guard.route[guard.currentRoute].y,
rotation = guard.route[guard.currentRoute].r,
delay = guard.route[guard.currentRoute].delay,
onComplete = function() patrolRoute(guard) end
})
end
local function rotateCamera( cam )
transition.to( cam, {
time = cam.time,
rotation = cam.returning and cam.r or cam.r+cam.angle,
onComplete=function() rotateCamera(cam) end
})
cam.returning = not cam.returning
end
local function newCamera( cam )
camera[#camera+1] = display.newImage( groupWalls,"images/camera.png", cam.x, cam.y )
camera[#camera].rotation = cam.rotation or 0
camera[#camera].r = cam.rotation or 60
camera[#camera].time = cam.time or 1000
camera[#camera].angle = cam.angle or 60
camera[#camera].returning = false
end
local function startGame()
lootCount = 0
playerSeen = false
startTimer = nil
canMove = true
gameClock:start(outOfTime)
Runtime:addEventListener( "enterFrame", updateGuards )
Runtime:addEventListener( "enterFrame", movePlayer )
Runtime:addEventListener( "key", onKeyEvent )
for i = 1, #guard do
patrolRoute( guard[i] )
end
for i = 1, #camera do
rotateCamera( camera[i] )
end
transition.to( player.escapeRadius, {time=750,xScale=1.1,yScale=1.1,transition=easing.continuousLoop,iterations=-1} )
end
local function updateCountdown()
if countdown.value == 4 then
countdown.alpha = 1
end
countdown.value = countdown.value-1
countdown.text = countdown.value
if countdown.value > 0 then
transition.to( countdown, {time=250,xScale=1.5,yScale=1.5,transition=easing.continuousLoop} )
startTimer = timer.performWithDelay( 980, updateCountdown )
else
transition.to( countdown, {time=250,alpha=0,xScale=1.5,yScale=1.5} )
transition.to( visionBlock, {time=250,alpha=0} )
startGame()
end
end
local function resetCountdown()
whoCaught.alpha = 0
countdown.alpha = 0
countdown.value = 4
countdown.xScale, countdown.yScale = 1, 1
visionBlock.alpha = 1
end
-------------------------------
function scene:create( event )
local sceneGroup = self.view
buttonMenu = display.newRect( screen.xMax+20, screen.yMin+20, 32, 32 )
buttonMenu:addEventListener( "touch", returnToMenu )
local background = display.newRect( groupGround, screen.xCenter, screen.yCenter, 960, 640 )
display.setDefault( "textureWrapX", "repeat" )
display.setDefault( "textureWrapY", "repeat" )
background.fill = {
type = "image",
filename = "images/ground.png"
}
background.fill.scaleX = 32 / background.width
background.fill.scaleY = 32 / background.height
display.setDefault( "textureWrapX", "clampToEdge" )
display.setDefault( "textureWrapY", "clampToEdge" )
local clockImg = display.newImage( groupUI, "images/clock.png", screen.xMin+50, screen.yMin+52 )
gameClock = clock.create( groupUI, screen.xMin+50, screen.yMin+61, "game" )
lootText = display.newText( groupUI, "Loot left:", gameClock.x + 60, screen.yMin+30, "fonts/Action_Man.ttf", 28 )
lootText.anchorX = 0
visionBlock = display.newRect( groupUI, screen.xCenter, screen.yCenter, screen.width, screen.height)
visionBlock:setFillColor(0)
visionBlock.alpha = 0.9
visionBlock:addEventListener( "touch", function(event) return true end )
countdown = display.newText( groupUI, "3", screen.xCenter, screen.yCenter, "fonts/Action_Man.ttf", 76 )
countdown.alpha = 0
snapshot.alpha = 0.5
snapshot.blendMode = "multiply"
sceneGroup:insert(groupGround)
sceneGroup:insert(groupObjects)
sceneGroup:insert(groupVision)
sceneGroup:insert(groupWalls)
sceneGroup:insert(groupUI)
end
function scene:show( event )
local sceneGroup = self.view
local phase = event.phase
if phase == "will" then
canMove = false
gotLoot = false
totalLoot = 0
resetCountdown()
transition.to( buttonMenu, {time=400,x=buttonMenu.x-40})
elseif phase == "did" then
-- Code here runs when the scene is first created but has not yet appeared on screen
local data = levelData[event.params.level]
local xStart, yStart = 64, 64
for row = 1, #data.map do
for column = 1, #data.map[row] do
local t = data.map[row][column]
local type = t:sub(1,4)
if t ~= "empty" then
object[#object+1] = display.newImage( groupGround, "images/"..t..".png", xStart+32*(column-1), yStart+32*(row-1) )
if type == "wall" then
physics.addBody( object[#object], "static" )
end
-- if type == "wall" or type == "item" then
-- physics.addBody( object[#object], "static" )
-- if t == "item_loot" then
-- object.isLoot = true
-- totalLoot = totalLoot+1
-- elseif t == "item_plant" then
-- object.isPlant = true
-- end
-- end
end
end
end
lootText.text = "Loot left: "..totalLoot
for i = 1, #data.guard do
newGuard( data.guard[i] )
end
for i = 1, #data.camera do
newCamera( data.camera[i] )
end
for i = 1, #data.loot do
object[#object+1] = display.newImage( groupGround, "images/loot.png", data.loot[i].x, data.loot[i].y )
object[#object].rotation = data.loot[i].r or 0
physics.addBody( object[#object], "static" )
object[#object].collision = onCollision
object[#object]:addEventListener( "collision" )
object[#object].isLoot = true
totalLoot = totalLoot+1
end
player = display.newRect( groupObjects, data.player.x, data.player.y, 20, 20 )
physics.addBody( player, "dynamic", {radius=10} )
player.collision = onCollision
player:addEventListener( "collision" )
player.isPlayer = true
player.gravityScale = 0
player.frame1 = {
type = "image",
filename = "images/player_walk1.png"
}
player.frame2 = {
type = "image",
filename = "images/player_walk2.png"
}
player.usingFrame1 = true
player.fill = player.frame1
local plusOrMinus = math.random() > 0.5 and 1 or -1
player.car = display.newImage( groupObjects, "images/car.png", player.x+plusOrMinus*math.random(80,120), player.y+plusOrMinus*math.random(20,40) )
physics.addBody( player.car, "static" )
if player.x < 480 then
if player.y < 320 then
player.car.rotation = math.random(-170,-150)
else
player.car.rotation = math.random(150,170)
end
else
if player.y < 320 then
player.car.rotation = math.random(-30,-10)
else
player.car.rotation = math.random(10,30)
end
end
player.escapeRadius = display.newCircle( groupObjects, player.car.x, player.car.y, 60 )
player.escapeRadius:toBack()
player.escapeRadius:setFillColor(0.1,0.8,0.1,0.3)
player.escapeRadius.alpha = 0
blockTouch = false
countdown.value = 0 -- uncomment to skip to game.
startTimer = timer.performWithDelay( 250, updateCountdown )
end
end
function scene:hide( event )
local sceneGroup = self.view
local phase = event.phase
if phase == "will" then
transition.to( buttonMenu, {time=400,x=buttonMenu.x+40})
gameClock:stop()
elseif phase == "did" then
countdown.alpha = 0
for i = 1, #guard do
_dRemove(guard[i].aura)
_dRemove(guard[i].sight)
_dRemove(guard[i])
guard[i] = nil
end
for i = 1, #camera do
_dRemove(camera[i].scan)
_dRemove(camera[i])
camera[i] = nil
end
for i = 1, #object do
_dRemove(object[i])
object[i] = nil
end
for i, j in pairs(action) do
action[i] = false
end
_dRemove(player.escapeRadius)
_dRemove(player.car)
_dRemove(player)
player = nil
end
end
scene:addEventListener( "create", scene )
scene:addEventListener( "show", scene )
scene:addEventListener( "hide", scene )
return scene | 33.132701 | 200 | 0.57574 |
e618f8bdacc7051fbadf685de3a6e57e2866d1e9 | 1,127 | go | Go | gui/jid.go | 0x27/coyim | d44546231aec54ade904f091159a4229f40c6447 | [
"BSD-3-Clause"
] | 1 | 2020-12-06T19:22:37.000Z | 2020-12-06T19:22:37.000Z | gui/jid.go | 0x27/coyim | d44546231aec54ade904f091159a4229f40c6447 | [
"BSD-3-Clause"
] | null | null | null | gui/jid.go | 0x27/coyim | d44546231aec54ade904f091159a4229f40c6447 | [
"BSD-3-Clause"
] | 2 | 2016-04-25T08:22:48.000Z | 2020-12-06T19:22:52.000Z | package gui
import (
"strings"
)
// Method to validate a jabber id is correct according to the RFC-6122
// on Address Format
// TODO: verify the resource part
func verifyXmppAddress(address string) (bool, string) {
var err string
tldIndex := strings.LastIndex(address, ".")
atIndex := strings.Index(address, "@")
isValidDomain, errDomain := verifyDomainPart(tldIndex, atIndex, address)
isValidPart, errPart := verifyLocalPart(atIndex)
isValid := isValidDomain && isValidPart
if !isValid {
errs := []string{errDomain, errPart, "XMPP address should look like local@domain.com"}
err = strings.Join(errs, ", ")
}
return isValid, err
}
func verifyDomainPart(tldIndex, atIndex int, address string) (bool, string) {
isValid := true
var err string
if tldIndex < 0 || tldIndex == len(address)-1 || tldIndex-atIndex < 2 {
isValid = false
err = "XMPP address has an invalid domain part"
}
return isValid, err
}
func verifyLocalPart(atIndex int) (bool, string) {
isValid := true
var err string
if atIndex < 1 {
isValid = false
err = "XMMP address has an invalid local part"
}
return isValid, err
}
| 23.479167 | 88 | 0.708962 |
4becbd95686043c3f2fa5a4c2b5342f6740470ff | 2,832 | swift | Swift | ixy/Sources/ixy/Device/Config/DeviceStats.swift | Danappelxx/ixy.swift | 0517f7384b5fd574ed9b3f215e6d63aadb154f87 | [
"MIT"
] | 27 | 2018-10-09T14:33:59.000Z | 2021-11-10T13:51:22.000Z | ixy/Sources/ixy/Device/Config/DeviceStats.swift | Danappelxx/ixy.swift | 0517f7384b5fd574ed9b3f215e6d63aadb154f87 | [
"MIT"
] | 3 | 2019-01-01T22:11:56.000Z | 2022-03-23T06:11:24.000Z | ixy/Sources/ixy/Device/Config/DeviceStats.swift | Danappelxx/ixy.swift | 0517f7384b5fd574ed9b3f215e6d63aadb154f87 | [
"MIT"
] | 4 | 2018-12-29T21:52:30.000Z | 2022-02-22T22:30:59.000Z | //
// DeviceStats.swift
// ixy
//
// Created by Thomas Günzel on 29.09.2018.
//
import Foundation
/// small struct for the device stats
public struct DeviceStats {
/// small substruct for the stats for a line (RX/TX)
public struct LineStats {
public var packets: UInt32
public var bytes: UInt64
static let zero = LineStats()
init(packets: UInt32 = 0, bytes: UInt64 = 0) {
self.packets = packets
self.bytes = bytes
}
}
public var transmitted: LineStats
public var received: LineStats
public static let zero = DeviceStats(transmitted: .zero, received: .zero)
init(transmitted: LineStats = LineStats(), received: LineStats = LineStats()) {
self.transmitted = transmitted
self.received = received
}
init(transmittedPackets: UInt32, transmittedBytes: UInt64, receivedPackets: UInt32, receivedBytes: UInt64) {
self.transmitted = LineStats(packets: transmittedPackets, bytes: transmittedBytes)
self.received = LineStats(packets: receivedPackets, bytes: receivedBytes)
}
public init() {
self.transmitted = LineStats(packets: 10568232, bytes: 676366848)
self.received = LineStats(packets: 14894297, bytes: 953235008)
}
}
// MARK: - CustomStringConvertible
extension DeviceStats.LineStats: CustomStringConvertible {
public var description: String {
return "(packets=\(packets),bytes=\(bytes))"
}
}
extension DeviceStats: CustomStringConvertible {
public var description: String {
return "Stats(tx=\(self.transmitted), rx=\(self.received))"
}
}
// MARK: - Basic Arithmetic Operations
public func +=(_ lhs: inout DeviceStats.LineStats, rhs: DeviceStats.LineStats) {
lhs.packets += rhs.packets
lhs.bytes += rhs.bytes
}
public func +=(_ lhs: inout DeviceStats, rhs: DeviceStats) {
lhs.transmitted += rhs.transmitted
lhs.received += rhs.received
}
public func -=(_ lhs: inout DeviceStats.LineStats, rhs: DeviceStats.LineStats) {
lhs.packets -= rhs.packets
lhs.bytes -= rhs.bytes
}
public func -=(_ lhs: inout DeviceStats, rhs: DeviceStats) {
lhs.transmitted -= rhs.transmitted
lhs.received -= rhs.received
}
public func +(_ lhs: DeviceStats.LineStats, rhs: DeviceStats.LineStats) -> DeviceStats.LineStats {
return DeviceStats.LineStats(packets: lhs.packets + rhs.packets, bytes: lhs.bytes + rhs.bytes)
}
public func +(_ lhs: DeviceStats, rhs: DeviceStats) -> DeviceStats {
return DeviceStats(transmitted: (lhs.transmitted + rhs.transmitted), received: (lhs.received + rhs.received))
}
public func -(_ lhs: DeviceStats.LineStats, rhs: DeviceStats.LineStats) -> DeviceStats.LineStats {
return DeviceStats.LineStats(packets: lhs.packets - rhs.packets, bytes: lhs.bytes - rhs.bytes)
}
public func -(_ lhs: DeviceStats, rhs: DeviceStats) -> DeviceStats {
return DeviceStats(transmitted: (lhs.transmitted - rhs.transmitted), received: (lhs.received - rhs.received))
}
| 28.897959 | 110 | 0.736229 |
9e3eed74cb944c8d2a74850343d42958253ef49a | 5,173 | swift | Swift | 301085484_Assignment1/ViewController.swift | Abdeali-53/iOS_Development-Basic_Calculator_Part2 | 18b56e25b918b2ed084d16daf775c72ec36ca325 | [
"MIT"
] | null | null | null | 301085484_Assignment1/ViewController.swift | Abdeali-53/iOS_Development-Basic_Calculator_Part2 | 18b56e25b918b2ed084d16daf775c72ec36ca325 | [
"MIT"
] | null | null | null | 301085484_Assignment1/ViewController.swift | Abdeali-53/iOS_Development-Basic_Calculator_Part2 | 18b56e25b918b2ed084d16daf775c72ec36ca325 | [
"MIT"
] | null | null | null | //
// ViewController.swift
// 301085484_Assignment1 (FILE NAME)
//
// Created by Abdeali Mody on 2020-09-30. (AUTHOR'S NAME & DATE)
// 301085484 (STUDENT ID)
// VERSION 1.0
import UIKit
class ViewController: UIViewController
{
//Declaring the variables : Datatype = value.
//abc
var operand1: Double = 0.0
var operand2: Double = 0.0
var activeOperation : String = ""
var operators: String = ""
var result: String = ""
@IBOutlet weak var ResultLabel: UILabel!
override func viewDidLoad()
{
super.viewDidLoad()
}
//Creating function for number buttons.
@IBAction func OnNumberButton_Press(_ sender: UIButton)
{
switch sender.titleLabel!.text!
{
case "C":
ResultLabel.text! = "0"
//Here I am cleaning the result variable as we are using this variable to save the numbers the user enter again ,we cannot have "trunk values".
result = ""
case "⌫":
//popLast method will remove the last entered number or operator from the display panel.
ResultLabel.text!.popLast()
if((ResultLabel.text!.count < 1) || (ResultLabel.text! == "-"))
{
ResultLabel.text! = "0"
}
case ".":
if(!ResultLabel.text!.contains("."))
{
ResultLabel.text! += "."
}
case "+/-":
//if the number is 5 and we press this button it is going to change to -5 and vice-versa
if(ResultLabel.text! != "0")
{
if(!ResultLabel.text!.contains("-"))
{
ResultLabel.text!.insert("-", at: ResultLabel.text!.startIndex)
}
else
{
ResultLabel.text!.remove(at: ResultLabel.text!.startIndex)
}
}
default:
if(ResultLabel.text == "0")
{
ResultLabel.text! = sender.titleLabel!.text!
result += sender.titleLabel!.text!
}
else
{
ResultLabel.text! += sender.titleLabel!.text!
result += sender.titleLabel!.text!
}
/*if(ResultLabel.text!.contains("."))
{
print(Double(ResultLabel.text!)!)
}*/
}
}
// Creating function for operator buttons.
@IBAction func OnOperatorButton_Press(_ sender: UIButton)
{
activeOperation = sender.titleLabel!.text!
//we need to check that the entered number is operand1 or operand2, now we will save the first value in operand1.
if operand1 == 0.0
{
print(result)
operand1 = Double(result)!
result = ""
}
else
{
operand2 = Double(result)!
result = ""
}
switch(activeOperation)
{
case "+":
ResultLabel.text! += "+"
operators = "+"
case "-":
ResultLabel.text! += "-"
operators = "-"
case "x":
ResultLabel.text! += "x"
operators = "x"
case "÷":
ResultLabel.text! += "÷"
operators = "÷"
case "%":
var test = ""
test = calculate(math: operators)
ResultLabel.text! = test
operators = "%"
case "=":
var test = ""
//just calling the calculate function and passing the the parameters. This will help us to call a particular operator.
test = calculate(math: operators)
//Now we already have the value isnside the test variable, so we display the output in result panel.
ResultLabel.text! = test
default:
print("error")
}
}
func calculate(math: String) -> String
{
var finalresult = ""
//here we check the signal to go to the correct operation
if (math == "+")
{
finalresult = String(Float32(operand1 + operand2))
}
else if (math == "-")
{
finalresult = String(Float32(operand1 - operand2))
}
else if (math == "x")
{
finalresult = String(Float32(operand1 * operand2))
}
else if (math == "÷")
{
finalresult = String(Float32(operand1 / operand2))
}
else if (math == "%")
{
finalresult = String(Float32((operand1 / operand2) * 100))
}
//Here we need to clear the operand so user can perform more operations.
operand1 = 0.0
operand2 = 0.0
result = finalresult
//returning the final result.
return finalresult
}
}
| 29.392045 | 151 | 0.470133 |
40b104bc52db048368ada772fd1176a639ba9c5f | 2,904 | py | Python | SimpleApp/stylemanager.py | 0xMartin/SimpleApp-Pygame-framework | fa443c1a05d3cc87595f0c6e0e65ff4471fe9c85 | [
"MIT"
] | null | null | null | SimpleApp/stylemanager.py | 0xMartin/SimpleApp-Pygame-framework | fa443c1a05d3cc87595f0c6e0e65ff4471fe9c85 | [
"MIT"
] | null | null | null | SimpleApp/stylemanager.py | 0xMartin/SimpleApp-Pygame-framework | fa443c1a05d3cc87595f0c6e0e65ff4471fe9c85 | [
"MIT"
] | null | null | null | """
Simple library for multiple views game aplication with pygame
File: stylemanager.py
Date: 09.02.2022
Github: https://github.com/0xMartin
Email: martin.krcma1@gmail.com
Copyright (C) 2022 Martin Krcma
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.
"""
from .utils import *
class StyleManager:
"""
Provides style for each GUI element. Loading and preserves all application styles.
"""
def __init__(self, styles_path):
"""
Create style manager
Parameters:
styles_path -> Path where is file with styles for all guil elements
"""
self.styles_path = styles_path
def init(self):
"""
Init style manager
"""
self.loadStyleSheet(self.styles_path)
def loadStyleSheet(self, styles_path):
"""
Load stylesheet from file
Parameters:
styles_path -> Path where is file with styles for all guil elements
"""
self.styles = loadConfig(styles_path)
def getStyleWithName(self, name) -> dict:
"""
Get style with specific name from stylsheet
Parameters:
name -> Name of style
"""
if name not in self.styles.keys():
return None
else:
return self.processStyle(self.styles[name])
def processStyle(self, style) -> dict:
"""
Some string values are replaced by an object if necessary
Parameters:
style -> Some style
"""
# colors
new_style = style.copy()
for tag in new_style.keys():
if "color" in tag:
rgb = new_style[tag].split(",")
new_style[tag] = tuple([int(rgb[0]), int(rgb[1]), int(rgb[2])])
elif isinstance(new_style[tag], dict):
new_style[tag] = self.processStyle(new_style[tag])
return new_style
| 32.266667 | 86 | 0.653926 |
1d117899be0b2f08386e33359074a00201b8522b | 510 | ps1 | PowerShell | ScienceLogic_SL1/internal/functions/ConvertTo-Appliance.ps1 | trir262/PowerShell_SL1 | b27c3b43bf92736b2130ada6861ff546a27b9243 | [
"MIT"
] | null | null | null | ScienceLogic_SL1/internal/functions/ConvertTo-Appliance.ps1 | trir262/PowerShell_SL1 | b27c3b43bf92736b2130ada6861ff546a27b9243 | [
"MIT"
] | 14 | 2019-04-07T22:12:03.000Z | 2020-01-04T20:36:29.000Z | ScienceLogic_SL1/internal/functions/ConvertTo-Appliance.ps1 | trir262/PowerShell_SL1 | b27c3b43bf92736b2130ada6861ff546a27b9243 | [
"MIT"
] | null | null | null | function ConvertTo-Appliance {
[CmdletBinding()]
Param(
[Parameter(Mandatory, Position=0, ValueFromPipeline)]
[ValidateNotNullOrEmpty()]
$SL1Appliance,
[Parameter(Mandatory, Position=1)]
[ValidateRange(0,([int64]::MaxValue))]
[int64]$Id
)
Process {
$SL1Appliance | Add-Member -TypeName 'appliance'
$SL1Appliance | Add-Member -NotePropertyName 'URI' -NotePropertyValue "/api/appliance/$($Id)"
$SL1Appliance | Add-Member -NotePropertyName 'ID' -NotePropertyValue $Id
$SL1Appliance
}
} | 26.842105 | 95 | 0.723529 |
fd31305c526b8c1c46b9f21c82f4ce2b6a82227c | 5,853 | swift | Swift | swaap/swaap/View Controllers/SignUpViewController.swift | mredig/conference-contacts-ios | e53429af5438dd6ec8d45be1b779438941bcb953 | [
"MIT"
] | 1 | 2020-05-04T16:35:47.000Z | 2020-05-04T16:35:47.000Z | swaap/swaap/View Controllers/SignUpViewController.swift | mredig/conference-contacts-ios | e53429af5438dd6ec8d45be1b779438941bcb953 | [
"MIT"
] | 14 | 2019-12-10T22:20:18.000Z | 2020-04-29T15:04:31.000Z | swaap/swaap/View Controllers/SignUpViewController.swift | mredig/conference-contacts-ios | e53429af5438dd6ec8d45be1b779438941bcb953 | [
"MIT"
] | 4 | 2020-02-08T22:25:20.000Z | 2020-09-21T17:35:57.000Z | //
// SignUpViewController.swift
// swaap
//
// Created by Michael Redig on 11/19/19.
// Copyright © 2019 swaap. All rights reserved.
//
import UIKit
import Auth0
class SignUpViewController: UIViewController {
@IBOutlet private weak var emailForm: FormInputView!
@IBOutlet private weak var passwordForm: FormInputView!
@IBOutlet private weak var passwordConfirmForm: FormInputView!
@IBOutlet private weak var signUpButton: ButtonHelper!
@IBOutlet private weak var passwordStrengthLabel: UILabel!
let authManager: AuthManager
let profileController: ProfileController
// MARK: - Lifecycle
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init coder not implemented")
}
init?(coder: NSCoder, authManager: AuthManager, profileController: ProfileController) {
self.authManager = authManager
self.profileController = profileController
super.init(coder: coder)
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
private func setupUI() {
overrideUserInterfaceStyle = .light
emailForm.contentType = .emailAddress
emailForm.keyboardType = .emailAddress
passwordForm.contentType = .newPassword
passwordConfirmForm.contentType = .newPassword
updateSignUpButtonEnabled()
updatePasswordStrengthLabel()
}
@IBAction func signupTapped(_ sender: ButtonHelper) {
guard let (email, password) = checkFormValidity() else { return }
authManager.signUp(with: email, password: password, completion: { [weak self] error in
self?.profileController.createProfileOnServer()
DispatchQueue.main.async {
if let error = error {
let alertVC = UIAlertController(error: error)
self?.present(alertVC, animated: true)
return
}
let alertVC = UIAlertController(title: "Signup Successful!", message: "You've created an account with the email address '\(email)'! Please sign in to continue.", preferredStyle: .alert)
alertVC.addAction(UIAlertAction(title: "Woohoo!", style: .default))
self?.present(alertVC, animated: true)
}
})
[sender, emailForm, passwordForm, passwordConfirmForm].forEach { $0.resignFirstResponder() }
}
@IBAction func textFieldChanged(_ sender: FormInputView) {
updateSignUpButtonEnabled()
}
@IBAction func emailFormDidFinish(_ sender: FormInputView) {
sender.validationState = checkEmail() != nil ? .pass : .fail
}
@IBAction func passwordFormDidFinish(_ sender: FormInputView) {
sender.validationState = checkPasswordStrength() != nil ? .pass : .fail
}
@IBAction func textFieldDidBeginEditing(_ sender: FormInputView) {
sender.validationState = .hidden
}
@IBAction func passwordFieldDidChange(_ sender: FormInputView) {
updatePasswordStrengthLabel()
}
@IBAction func confirmPasswordFormDidFinish(_ sender: FormInputView) {
sender.validationState = (checkPasswordStrength() != nil && checkPasswordMatch()) ? .pass : .fail
}
// MARK: - Form Validation
private func updateSignUpButtonEnabled() {
signUpButton.isEnabled = checkFormValidity() != nil
}
private func updatePasswordStrengthLabel() {
let passwordStrengthText = """
Password requirements:
• minimum of 8 Characters
• at least 1 lowercase
• at least 1 uppercase
• at least 1 symbol
• at least 1 number
• no identifying portion of your email
""" as NSString
let font = UIFont.preferredFont(forTextStyle: .footnote)
let boldFont = UIFont.boldSystemFont(ofSize: font.pointSize)
let attrStr = NSMutableAttributedString(string: passwordStrengthText as String, attributes: [.font: font])
attrStr.addAttribute(.font, value: boldFont, range: passwordStrengthText.range(of: "Password requirements:"))
if let password = passwordForm.text {
let color: UIColor = .systemTeal
if password.hasAtLeastXCharacters(8) {
attrStr.addAttribute(.foregroundColor, value: color, range: passwordStrengthText.range(of: "minimum of 8 Characters"))
}
if password.hasALowercaseCharacter {
attrStr.addAttribute(.foregroundColor, value: color, range: passwordStrengthText.range(of: "at least 1 lowercase"))
}
if password.hasAnUppercaseCharacter {
attrStr.addAttribute(.foregroundColor, value: color, range: passwordStrengthText.range(of: "at least 1 uppercase"))
}
if password.hasANumericalCharacter {
attrStr.addAttribute(.foregroundColor, value: color, range: passwordStrengthText.range(of: "at least 1 number"))
}
if password.hasASpecialCharacter {
attrStr.addAttribute(.foregroundColor, value: color, range: passwordStrengthText.range(of: "at least 1 symbol"))
}
if !password.hasPartOfEmailAddress(checkEmail()) {
attrStr.addAttribute(.foregroundColor, value: color, range: passwordStrengthText.range(of: "no identifying portion of your email"))
}
}
passwordStrengthLabel.attributedText = attrStr
}
private func checkEmail() -> String? {
(emailForm.text?.isEmail ?? false) ? emailForm.text : nil
}
private func checkPasswordStrength() -> String? {
guard let password = passwordForm.text,
password.hasAtLeastXCharacters(8),
password.hasALowercaseCharacter,
password.hasAnUppercaseCharacter,
password.hasANumericalCharacter,
password.hasASpecialCharacter,
!password.hasPartOfEmailAddress(checkEmail()) else { return nil }
return password
}
private func checkPasswordMatch() -> Bool {
passwordForm.text == passwordConfirmForm.text
}
private func checkFormValidity() -> (email: String, password: String)? {
guard let email = checkEmail(), let password = checkPasswordStrength(), checkPasswordMatch() else { return nil }
signUpButton.isEnabled = true
return (email, password)
}
}
extension SignUpViewController: RootAuthViewControllerDelegate {
func controllerWillScroll(_ controller: RootAuthViewController) {
[emailForm, passwordForm, passwordConfirmForm].forEach { _ = $0.resignFirstResponder() }
}
}
| 33.83237 | 189 | 0.750555 |
71c343fa767e12038ef2eebe5ea76e587d0f93a8 | 14,199 | swift | Swift | NA Meeting Search/BMLT_MeetingSearch_PageRenderer.swift | cheefbird/BMLT-NA-Meeting-Search | 327928cff13dd8f77fb97ace7208595f46959d23 | [
"MIT"
] | null | null | null | NA Meeting Search/BMLT_MeetingSearch_PageRenderer.swift | cheefbird/BMLT-NA-Meeting-Search | 327928cff13dd8f77fb97ace7208595f46959d23 | [
"MIT"
] | 3 | 2019-09-17T08:41:19.000Z | 2021-08-15T17:22:36.000Z | NA Meeting Search/BMLT_MeetingSearch_PageRenderer.swift | cheefbird/BMLT-NA-Meeting-Search | 327928cff13dd8f77fb97ace7208595f46959d23 | [
"MIT"
] | 3 | 2018-12-28T20:48:36.000Z | 2020-03-13T20:43:07.000Z | //
// BMLT_MeetingSearch_PageRenderer.swift
// NA Meeting Search
//
// Created by BMLT-Enabled
//
// https://bmlt.app/
//
// This software is licensed under the MIT License.
// Copyright (c) 2017 BMLT-Enabled
//
// 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 UIKit
import MapKit
import BMLTiOSLib
/* ###################################################################################################################################### */
/**
This extension allows us to get the displayed height and width (given a full-sized canvas -so no wrapping or truncating) of an attributed string.
*/
extension NSAttributedString {
/* ################################################################## */
/**
- returns: The string height required to display the string.
*/
var stringHeight: CGFloat {
let rect = self.boundingRect(with: CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil)
return ceil(rect.size.height)
}
/* ################################################################## */
/**
- returns: The string width required to display the string.
*/
var stringWidth: CGFloat {
let rect = self.boundingRect(with: CGSize.init(width: CGFloat.greatestFiniteMagnitude, height: CGFloat.greatestFiniteMagnitude), options: [.usesLineFragmentOrigin, .usesFontLeading], context: nil)
return ceil(rect.size.width)
}
}
/* ###################################################################################################################################### */
/**
This class is a printe renderer for list results. It creates a fairly simple black-and-white list.
*/
class BMLT_MeetingSearch_ListResults_PageRenderer: UIPrintPageRenderer {
// MARK: - Fixed Instance Properties
/* ################################################################################################################################## */
/** The font size can be dynamic for each meeting. We start with this, and get smaller, if necessary. */
let startingFontSize: CGFloat = 30
// MARK: - Variable Instance Properties
/* ################################################################################################################################## */
/** This is the maximum number of meetings to display per page. */
var maxMeetingsPerPage: Int = 10
/** These are the actual meeting objects being rendered. */
var meetings: [BMLTiOSLibMeetingNode] = []
// MARK: - Base Class Override Calculated Instance Properties
/* ################################################################################################################################## */
/* ################################################################## */
/**
- returns: The number of pages required to display the list of meetings.
*/
override var numberOfPages: Int {
let perPageCount = Float(self.maxMeetingsPerPage)
let meetingCount = Float(self.meetings.count)
return Int(ceil(meetingCount / perPageCount))
}
// MARK: - Initializers
/* ################################################################################################################################## */
/* ################################################################## */
/**
Initializer with a list of meetings.
- parameter meetings: This is an array of meeting objects.
*/
init(meetings: [BMLTiOSLibMeetingNode]) {
super.init()
self.meetings = meetings
self.headerHeight = 0
self.footerHeight = 0
}
// MARK: - Base Class Override Methods
/* ################################################################################################################################## */
/* ################################################################## */
/**
This loops through the subset of meeting objects being printed on the given page, and renders them.
- parameter pageIndex: This is the 0-based index of the page.
- parameter in: This is the display rect.
*/
override func drawContentForPage(at pageIndex: Int, in contentRect: CGRect) {
let perMeetingHeight: CGFloat = contentRect.size.height / CGFloat(min(self.maxMeetingsPerPage, self.meetings.count))
let startingPoint = pageIndex * self.maxMeetingsPerPage
let endingPointPlusOne = min(self.meetings.count, startingPoint + self.maxMeetingsPerPage)
for index in startingPoint..<endingPointPlusOne {
let top = contentRect.origin.y + (CGFloat(index - startingPoint) * perMeetingHeight)
let meetingRect = CGRect(x: contentRect.origin.x, y: top, width: contentRect.size.width, height: perMeetingHeight)
self.drawMeeting(at: index, in: meetingRect)
}
}
// MARK: - Instance Methods
/* ################################################################################################################################## */
/* ################################################################## */
/**
This displays a single meeting.
- parameter at: The 0-based index of the meeting to be rendered.
- parameter in: This is the display rect.
*/
func drawMeeting(at meetingIndex: Int, in contentRect: CGRect) {
let cRect = contentRect.insetBy(dx: 4, dy: 4)
let myMeetingObject = self.meetings[meetingIndex]
if (1 < self.meetings.count) && (0 == meetingIndex % 2) {
if let drawingContext = UIGraphicsGetCurrentContext() {
drawingContext.setFillColor(UIColor.black.withAlphaComponent(0.075).cgColor)
drawingContext.fill(contentRect)
}
}
var fontSize = self.startingFontSize
var width: CGFloat = 0
var height: CGFloat = 0
var descriptionString: NSAttributedString! = nil
// What we do here, is continuously sample the display rect of the string, until we find a font size that fits the display.
repeat {
var attributes: [NSAttributedString.Key: Any] = [:]
attributes[NSAttributedString.Key.backgroundColor] = UIColor.clear
attributes[NSAttributedString.Key.foregroundColor] = UIColor.black
attributes[NSAttributedString.Key.font] = UIFont.italicSystemFont(ofSize: fontSize)
var stringContent = myMeetingObject.description
if !myMeetingObject.comments.isEmpty {
stringContent += "\n" + myMeetingObject.comments
}
descriptionString = NSAttributedString(string: stringContent, attributes: attributes)
width = descriptionString.stringWidth
height = descriptionString.stringHeight
fontSize -= 0.25
} while (width > cRect.size.width) || (height > cRect.size.height)
if nil != descriptionString {
descriptionString.draw(at: cRect.origin)
}
}
}
/* ###################################################################################################################################### */
/**
This class extends the above, so that the first page is the displayed map.
*/
class BMLT_MeetingSearch_MapResults_PageRenderer: BMLT_MeetingSearch_ListResults_PageRenderer {
/** This is the formatter used to render the map on the first page. */
var mapFormatter: UIViewPrintFormatter! = nil
// MARK: - Initializers
/* ################################################################################################################################## */
/* ################################################################## */
/**
Default initializer.
- parameter meetings: An array of meeting objects to be listed after the map.
- parameter mapFormatter: The formatter generated by the displayed map.
*/
init(meetings: [BMLTiOSLibMeetingNode], mapFormatter: UIViewPrintFormatter) {
super.init(meetings: meetings)
self.mapFormatter = mapFormatter
}
// MARK: - Base Class Override Calculated Instance Properties
/* ################################################################################################################################## */
/* ################################################################## */
/**
- returns: The number of pages required to display the list of meetings (We add one for tha map).
*/
override var numberOfPages: Int {
return super.numberOfPages + 1
}
// MARK: - Base Class Override Methods
/* ################################################################################################################################## */
/* ################################################################## */
/**
This draws the map, then loops through the subset of meeting objects being printed on the given page, and renders them.
- parameter pageIndex: This is the 0-based index of the page.
- parameter in: This is the display rect.
*/
override func drawContentForPage(at pageIndex: Int, in contentRect: CGRect) {
if 0 < pageIndex {
super.drawContentForPage(at: pageIndex - 1, in: contentRect)
} else {
self.mapFormatter.draw(in: contentRect, forPageAt: 0)
}
}
}
/* ###################################################################################################################################### */
/**
This extends the list formatter for a single page, with a single meetings and a map.
*/
class BMLT_MeetingSearch_SingleMeeting_PageRenderer: BMLT_MeetingSearch_ListResults_PageRenderer {
/// This is the formatter object we'll use to render the page.
var mapFormatter: UIViewPrintFormatter! = nil
// MARK: - Base Class Override Calculated Instance Properties
/* ################################################################################################################################## */
/* ################################################################## */
/**
- returns: The number of pages required to display the meeting (always 1).
*/
override var numberOfPages: Int { return 1 }
// MARK: - Initializers
/* ################################################################################################################################## */
/* ################################################################## */
/**
Default initializer.
- parameter meeting: A meeting object to be displayed.
- parameter mapFormatter: The formatter generated by the displayed map.
*/
init(meeting: BMLTiOSLibMeetingNode, mapFormatter: UIViewPrintFormatter) {
super.init(meetings: [meeting])
self.mapFormatter = mapFormatter
}
// MARK: - Base Class Override Methods
/* ################################################################################################################################## */
/* ################################################################## */
/**
This draws the meeting info.
- parameter pageIndex: This is the 0-based index of the page.
- parameter in: This is the display rect.
*/
override func drawContentForPage(at pageIndex: Int, in contentRect: CGRect) {
let cRect = contentRect.insetBy(dx: 4, dy: 4)
let myMeetingObject = self.meetings[0]
var fontSize = self.startingFontSize
var width: CGFloat = 0
var height: CGFloat = 0
var descriptionString: NSAttributedString! = nil
// What we do here, is continuously sample the display rect of the string, until we find a font size that fits the display.
repeat {
var attributes: [NSAttributedString.Key: Any] = [:]
attributes[NSAttributedString.Key.backgroundColor] = UIColor.clear
attributes[NSAttributedString.Key.foregroundColor] = UIColor.black
attributes[NSAttributedString.Key.font] = UIFont.italicSystemFont(ofSize: fontSize)
var stringContent = myMeetingObject.description
if !myMeetingObject.comments.isEmpty {
stringContent += "\n" + myMeetingObject.comments
}
descriptionString = NSAttributedString(string: stringContent, attributes: attributes)
width = descriptionString.stringWidth
height = descriptionString.stringHeight
fontSize -= 0.25
} while (width > cRect.size.width) || (height > cRect.size.height)
if nil != descriptionString {
descriptionString.draw(at: cRect.origin)
}
let bottomDrawingRect = CGRect(x: cRect.origin.x, y: cRect.origin.y + height, width: cRect.size.width, height: cRect.size.height - height)
self.mapFormatter.draw(in: bottomDrawingRect, forPageAt: 0)
}
}
| 47.488294 | 204 | 0.519473 |
83dc03865a3ee21bc0da6d5f14bddac61a3eaab4 | 3,781 | go | Go | pkg/executor/fuse.go | infradash/dash | dbbe6ce01a443a12316845f2ad75d4c1b3ecf972 | [
"Apache-2.0"
] | null | null | null | pkg/executor/fuse.go | infradash/dash | dbbe6ce01a443a12316845f2ad75d4c1b3ecf972 | [
"Apache-2.0"
] | null | null | null | pkg/executor/fuse.go | infradash/dash | dbbe6ce01a443a12316845f2ad75d4c1b3ecf972 | [
"Apache-2.0"
] | null | null | null | package executor
import (
"errors"
"fmt"
"github.com/golang/glog"
"github.com/qorio/maestro/pkg/registry"
"github.com/qorio/maestro/pkg/zk"
"os"
"strings"
)
type FileSystem interface {
Mount(dir string, perm os.FileMode) error
Close() error
}
var (
ErrMissingMount = errors.New("err-missing-mount-point")
ErrMissingResource = errors.New("err-missing-resource")
ErrMountPointNotAbs = errors.New("err-mount-point-not-absolute-path")
ErrResourceNotSupported = errors.New("err-resource-not-supported")
ResourceMqtt = "mqtt://"
ResourceZk = "zk://"
ResourceTypes = []string{ResourceMqtt, ResourceZk}
resourceFS = map[string]func(resource string, zc zk.ZK) FileSystem{
ResourceZk: func(resource string, zc zk.ZK) FileSystem {
return NewZkFS(zc, registry.Path(resource))
},
}
fsOpen = map[FileSystem]FileSystem{}
fsRegister = make(chan FileSystem)
fsClose = make(chan FileSystem)
fsErrors = make(chan error)
)
func init() {
go func() {
for {
select {
case c := <-fsRegister:
fsOpen[c] = c
case c := <-fsClose:
c.Close()
delete(fsOpen, c)
case e := <-fsErrors:
glog.Warningln("Error from fuse filesystem:", e)
}
}
}()
}
func StartFileMounts(list []*Fuse, zc zk.ZK) error {
for _, f := range list {
if err := f.IsValid(); err != nil {
fsErrors <- err
return err
}
f.zc = zc
if fs, err := f.Mount(); err != nil {
glog.Infoln("Error mounting filesystem:", f, "err=", err)
fsErrors <- err
return err
} else {
fsRegister <- fs
}
}
return nil
}
func StopFileMounts() {
stop := []FileSystem{}
for c, _ := range fsOpen {
stop = append(stop, c)
}
for _, c := range stop {
fsClose <- c
}
}
func (this *Fuse) IsValid() error {
if len(this.MountPoint) == 0 {
return ErrMissingMount
}
if len(this.Resource) == 0 {
return ErrMissingResource
}
misses := 0
for _, p := range ResourceTypes {
if strings.Index(this.Resource, p) != 0 {
misses++
}
}
if misses == len(ResourceTypes) {
return ErrResourceNotSupported
}
return nil
}
func (this *Fuse) GetResourceType() string {
switch {
case strings.Index(this.Resource, ResourceMqtt) == 0:
return this.Resource[0:len(ResourceMqtt)]
case strings.Index(this.Resource, ResourceZk) == 0:
return this.Resource[0:len(ResourceZk)]
}
return ""
}
func strip_resource_type(p string) string {
switch {
case strings.Index(p, ResourceMqtt) == 0:
return p[len(ResourceMqtt):]
case strings.Index(p, ResourceZk) == 0:
return p[len(ResourceZk):]
default:
return p
}
}
func (this *Fuse) Mount() (FileSystem, error) {
if err := this.IsValid(); err != nil {
return nil, err
}
switch {
case strings.Index(this.MountPoint, ".") == 0:
this.MountPoint = strings.Replace(this.MountPoint, ".", os.Getenv("PWD"), 1)
case strings.Index(this.MountPoint, "~") == 0:
this.MountPoint = strings.Replace(this.MountPoint, "~", os.Getenv("HOME"), 1)
}
var perm os.FileMode = 0644
fmt.Sscanf(this.Perm, "%v", &perm)
if err := os.MkdirAll(this.MountPoint, perm); err != nil {
return nil, err
}
filesys := resourceFS[this.GetResourceType()](strip_resource_type(this.Resource), this.zc)
go func() {
glog.Infoln("Mounting filesystem:", this, "type=", this.GetResourceType(), "filesys=", filesys)
glog.Infoln("Start serving", filesys, "on", this.MountPoint, "backed", this.Resource)
filesys.Mount(this.MountPoint, perm)
}()
return filesys, nil
}
func NewZkFS(zc zk.ZK, path registry.Path) *zkFs {
return &zkFs{
impl: zk.NewFS(zc, path),
}
}
type zkFs struct {
impl *zk.FS
}
func (this *zkFs) Close() error {
return this.impl.Shutdown()
}
func (this *zkFs) Mount(dir string, perm os.FileMode) error {
return this.impl.Mount(dir, perm)
}
| 22.372781 | 97 | 0.654853 |
a60bb8f93e05cdaa6da691ade40b536048f30b9f | 652 | asm | Assembly | oeis/301/A301571.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 11 | 2021-08-22T19:44:55.000Z | 2022-03-20T16:47:57.000Z | oeis/301/A301571.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 9 | 2021-08-29T13:15:54.000Z | 2022-03-09T19:52:31.000Z | oeis/301/A301571.asm | neoneye/loda-programs | 84790877f8e6c2e821b183d2e334d612045d29c0 | [
"Apache-2.0"
] | 3 | 2021-08-22T20:56:47.000Z | 2021-09-29T06:26:12.000Z | ; A301571: Number of vertices at distance 2 from a given vertex in the n-Keller graph.
; 0,10,29,84,247,734,2193,6568,19691,59058,177157,531452,1594335,4782982,14348921,43046736,129140179,387420506,1162261485,3486784420,10460353223,31381059630,94143178849,282429536504,847288609467,2541865828354,7625597485013,22876792454988,68630377364911,205891132094678,617673396283977,1853020188851872,5559060566555555,16677181699666602,50031545098999741,150094635296999156,450283905890997399,1350851717672992126,4052555153018976305,12157665459056928840,36472996377170786443,109418989131512359250
mov $1,$0
min $0,1
add $0,$1
mov $2,3
pow $2,$0
add $0,$2
sub $0,1
| 59.272727 | 496 | 0.851227 |
1688c76c844b1a82a4f30fe70167748d82aed6f3 | 899 | h | C | exp_lang/exp_lang/variables.h | Mihahanya/Exp-lang | b782093f0ce7281c32e939ccdc8e3f8e1679b68c | [
"MIT"
] | 1 | 2021-12-13T13:17:03.000Z | 2021-12-13T13:17:03.000Z | exp_lang/exp_lang/variables.h | Mihahanya/Exp-lang | b782093f0ce7281c32e939ccdc8e3f8e1679b68c | [
"MIT"
] | null | null | null | exp_lang/exp_lang/variables.h | Mihahanya/Exp-lang | b782093f0ce7281c32e939ccdc8e3f8e1679b68c | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <string>
using namespace std;
struct var {
size_t id;
int val;
string name;
};
class Variables
{
public:
vector<var> v_strg = { {0, 0, ""}, {25184, 0, "df"}, {SIZE_MAX, 0, ""}};
void choose(string name) {
if (name == this->name) return;
this->name = name;
cid = hash<string>{}(name);;
pos = pos_id(cid);
}
var* get_ind_by_name(bool check=true) {
if (check && !has_var()) {
add();
pos++;
}
return &v_strg[pos];
}
private:
size_t cid, pos;
string name;
inline bool has_var() {
return v_strg[pos].name == name;
}
inline void add() {
v_strg.insert(v_strg.begin()+1+pos, {cid, 0, name});
}
size_t pos_id(size_t id) {
/// The binary search a variavle by id
size_t l=0, r=v_strg.size(), mid;
while (l < r) {
mid = (l+r)>>1;
if (v_strg[mid].id > id) r = mid;
else l = mid+1;
}
return r-1;
}
};
| 16.053571 | 73 | 0.581758 |
f4122e3964714bd05ca55ac1f3942f95c1d389a6 | 1,375 | go | Go | pkg/utils/sysctl/sysctl_test.go | intelsdi-x/swan | 851671dd1cd2508cc04b7a3075a7e1e0fb03c285 | [
"Apache-2.0"
] | 44 | 2017-05-05T09:21:01.000Z | 2021-04-02T05:30:55.000Z | pkg/utils/sysctl/sysctl_test.go | intelsdi-x/swan | 851671dd1cd2508cc04b7a3075a7e1e0fb03c285 | [
"Apache-2.0"
] | 130 | 2017-04-28T17:40:27.000Z | 2018-12-27T14:13:40.000Z | pkg/utils/sysctl/sysctl_test.go | intelsdi-x/swan | 851671dd1cd2508cc04b7a3075a7e1e0fb03c285 | [
"Apache-2.0"
] | 17 | 2017-04-28T17:45:42.000Z | 2021-07-31T16:26:48.000Z | // Copyright (c) 2017 Intel Corporation
//
// 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 sysctl
import (
"testing"
. "github.com/smartystreets/goconvey/convey"
)
func TestSysctl(t *testing.T) {
Convey("Reading a sane sysctl value (kernel.ostype)", t, func() {
value, err := Get("kernel.ostype")
Convey("Should not return an error", func() {
So(err, ShouldBeNil)
Convey("And should contain 'Linux'", func() {
So(value, ShouldEqual, "Linux")
})
})
})
Convey("Reading a non-sense sysctl value (foo.bar.baz)", t, func() {
value, err := Get("foo.bar.baz")
Convey("Should return an error", func() {
So(err, ShouldNotBeNil)
So(err.Error(), ShouldContainSubstring, "open /proc/sys/foo/bar/baz: no such file or directory")
Convey("And the value should be empty", func() {
So(value, ShouldEqual, "")
})
})
})
}
| 28.061224 | 99 | 0.685091 |
7bb0bc296f5f5b39d8816e2b14a7380df7a1c47c | 1,131 | kt | Kotlin | src/main/kotlin/yt/javi/spring/examples/springevents/user/domain/services/user/register/RegisterUserService.kt | javiyt/spring-events | b27eea4dac7cf03539caaee52c5c39ff3dd17744 | [
"Apache-2.0"
] | null | null | null | src/main/kotlin/yt/javi/spring/examples/springevents/user/domain/services/user/register/RegisterUserService.kt | javiyt/spring-events | b27eea4dac7cf03539caaee52c5c39ff3dd17744 | [
"Apache-2.0"
] | 100 | 2019-04-11T20:15:07.000Z | 2021-09-23T16:28:06.000Z | src/main/kotlin/yt/javi/spring/examples/springevents/user/domain/services/user/register/RegisterUserService.kt | javiyt/spring-events | b27eea4dac7cf03539caaee52c5c39ff3dd17744 | [
"Apache-2.0"
] | null | null | null | package yt.javi.spring.examples.springevents.user.domain.services.user.register
import yt.javi.spring.examples.springevents.user.domain.ActionEvent
import yt.javi.spring.examples.springevents.user.domain.model.user.User
import yt.javi.spring.examples.springevents.user.domain.model.user.UserEvent
import yt.javi.spring.examples.springevents.user.domain.model.user.UserEventPublisher
import yt.javi.spring.examples.springevents.user.domain.model.user.UserRepository
data class RegisterUserRequest(val username: String, val email: String)
class RegisterUserService(private val repository: UserRepository, private val eventPublisher: UserEventPublisher) {
operator fun invoke(request: RegisterUserRequest) {
val user = User.create(
id = null,
username = request.username,
email = request.email
)
repository.save(user)
eventPublisher.publishEvent(user.toEvent())
}
fun User.toEvent() = UserEvent(
userId = userId.toString(),
username = username.toString(),
email = email.toString(),
action = ActionEvent.CREATE
)
} | 39 | 115 | 0.73298 |
7de7cc46ae570a70145ac0f2c93f0fb259e8d1d3 | 887 | lua | Lua | programs/neovim-lsp/lua/lsp/servers/sumneko_lua.lua | slaser79/dotfiles-nix | 0a42d6f7a534135010ba30154780afe454c3f9f9 | [
"BSD-3-Clause"
] | null | null | null | programs/neovim-lsp/lua/lsp/servers/sumneko_lua.lua | slaser79/dotfiles-nix | 0a42d6f7a534135010ba30154780afe454c3f9f9 | [
"BSD-3-Clause"
] | null | null | null | programs/neovim-lsp/lua/lsp/servers/sumneko_lua.lua | slaser79/dotfiles-nix | 0a42d6f7a534135010ba30154780afe454c3f9f9 | [
"BSD-3-Clause"
] | null | null | null | -- local sumneko_bin = (function()
-- for _, p in pairs(vim.split(vim.env.PATH, ":")) do
-- if string.find(p, "lua-language-server", 1, true) ~= nil then return p end
-- end
-- end)()
-- local sumneko_root = string.sub(sumneko_bin, 1, string.len(sumneko_bin) - 4)
-- local sumneko_executable = sumneko_bin.."/lua-language-server"
-- local sumneko_main = sumneko_root.."/share/lua-language-server/main.lua"
local runtime_path = vim.split(package.path, ';')
table.insert(runtime_path, "lua/?.lua")
table.insert(runtime_path, "lua/?/init.lua")
return {
settings = {
Lua = {
runtime = {
version = 'LuaJIT',
path = runtime_path,
},
diagnostics = {
globals = { 'vim' },
},
workspace = {
library = vim.api.nvim_get_runtime_file("", true),
},
telemetry = {
enable = false,
},
},
},
}
| 26.088235 | 81 | 0.587373 |
1d42a65fd9f990ac9bd5b5ab9136c61801043760 | 1,213 | swift | Swift | Emergence/Models/Electric Objects/Image.swift | artsy/Emergence | 43c881d3cb115824143ef04bd71ab284647b295a | [
"MIT"
] | 395 | 2015-09-22T08:01:32.000Z | 2021-11-16T10:55:24.000Z | Emergence/Models/Electric Objects/Image.swift | artsy/Emergence | 43c881d3cb115824143ef04bd71ab284647b295a | [
"MIT"
] | 74 | 2015-09-22T07:59:00.000Z | 2017-09-11T06:25:44.000Z | Emergence/Models/Electric Objects/Image.swift | artsy/Emergence | 43c881d3cb115824143ef04bd71ab284647b295a | [
"MIT"
] | 47 | 2015-10-21T21:50:43.000Z | 2019-12-22T08:34:18.000Z | import Gloss
import Foundation
import CoreGraphics
struct Image: Imageable, ImageURLThumbnailable, GeminiThumbnailable {
let id: String
let imageFormatString: String
let imageVersions: [String]
let imageSize: CGSize
let aspectRatio: CGFloat?
let geminiToken: String?
let isDefault: Bool
func bestThumbnailWithHeight(height:CGFloat) -> NSURL? {
if let url = geminiThumbnailURLWithHeight(Int(height)) {
return url
}
return bestAvailableThumbnailURL()
}
}
extension Image: Decodable {
init?(json: JSON) {
guard
let idValue: String = "id" <~~ json,
let imageFormatStringValue: String = "image_url" <~~ json,
let imageVersionsValue: [String] = "image_versions" <~~ json
else {
return nil
}
id = idValue
imageFormatString = imageFormatStringValue
imageVersions = imageVersionsValue
geminiToken = "gemini_token" <~~ json
imageSize = CGSize(width: "original_width" <~~ json ?? 1, height: "original_height" <~~ json ?? 1)
aspectRatio = "aspect_ratio" <~~ json
isDefault = "is_default" <~~ json ?? false
}
} | 28.209302 | 106 | 0.625721 |
f792ef7a9152458c363aa400930a96eb604ef736 | 115 | h | C | src/string_p.h | lzf-lamer/BurningHttp | 048e8120513366dba9d1278ba61a2b76d11735a7 | [
"Apache-2.0"
] | null | null | null | src/string_p.h | lzf-lamer/BurningHttp | 048e8120513366dba9d1278ba61a2b76d11735a7 | [
"Apache-2.0"
] | null | null | null | src/string_p.h | lzf-lamer/BurningHttp | 048e8120513366dba9d1278ba61a2b76d11735a7 | [
"Apache-2.0"
] | null | null | null | #ifndef _STRING_P_H_
#define _STRING_P_H_
#endif
#include<string.h>
int strstr_p(char * str1,const char * str2);
| 14.375 | 44 | 0.756522 |
41cde71b9ce1b06bb7b778565d7bbb68607c62db | 3,731 | kt | Kotlin | src/main/kotlin/org/jetbrains/research/ml/tasktracker/reporting/GitHubErrorReporter.kt | nbirillo/coding-assistant-ui | 83767acd6098ad2272950917afd7937b2fb68fee | [
"MIT"
] | 1 | 2021-03-17T13:03:38.000Z | 2021-03-17T13:03:38.000Z | src/main/kotlin/org/jetbrains/research/ml/tasktracker/reporting/GitHubErrorReporter.kt | nbirillo/coding-assistant-ui | 83767acd6098ad2272950917afd7937b2fb68fee | [
"MIT"
] | 9 | 2020-07-09T16:17:08.000Z | 2020-09-21T09:45:30.000Z | src/main/kotlin/org/jetbrains/research/ml/tasktracker/reporting/GitHubErrorReporter.kt | nbirillo/coding-assistant-ui | 83767acd6098ad2272950917afd7937b2fb68fee | [
"MIT"
] | 6 | 2021-03-11T11:45:15.000Z | 2022-03-24T19:24:54.000Z | package org.jetbrains.research.ml.tasktracker.reporting
import com.intellij.diagnostic.IdeaReportingEvent
import com.intellij.diagnostic.ReportMessages
import com.intellij.ide.DataManager
import com.intellij.idea.IdeaLogger
import com.intellij.notification.NotificationListener
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.application.ApplicationNamesInfo
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.diagnostic.ErrorReportSubmitter
import com.intellij.openapi.diagnostic.IdeaLoggingEvent
import com.intellij.openapi.diagnostic.SubmittedReportInfo
import com.intellij.openapi.progress.EmptyProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.util.Consumer
import java.awt.Component
class GitHubErrorReporter : ErrorReportSubmitter() {
override fun submit(
events: Array<IdeaLoggingEvent>, additionalInfo: String?, parentComponent: Component,
consumer: Consumer<SubmittedReportInfo>
): Boolean {
val errorReportInformation = ErrorInformation(
IdeaLogger.ourLastActionId,
ApplicationInfo.getInstance() as ApplicationInfoEx,
ApplicationNamesInfo.getInstance(),
events[0].throwable
)
return doSubmit(
events[0],
parentComponent,
consumer,
errorReportInformation
)
}
override fun getReportActionText(): String {
return "Report to TaskTracker Github Issue Tracker"
}
/**
* Provides functionality to show an error report message to the user that gives a clickable link to the created issue.
*/
internal class CallbackWithNotification(
private val originalConsumer: Consumer<SubmittedReportInfo>,
private val project: Project?
) :
Consumer<SubmittedReportInfo> {
override fun consume(reportInfo: SubmittedReportInfo) {
originalConsumer.consume(reportInfo)
val notificationType =
if (reportInfo.status == SubmittedReportInfo.SubmissionStatus.FAILED) {
NotificationType.ERROR
} else {
NotificationType.INFORMATION
}
ReportMessages.GROUP.createNotification(
ReportMessages.ERROR_REPORT,
reportInfo.linkText,
notificationType,
NotificationListener.URL_OPENING_LISTENER
).setImportant(false).notify(project)
}
}
private fun doSubmit(
event: IdeaLoggingEvent,
parentComponent: Component,
callback: Consumer<SubmittedReportInfo>,
errorInformation: ErrorInformation
): Boolean {
if (event is IdeaReportingEvent) {
event.plugin?.let {
errorInformation.setUserInformation(UserInformationType.PLUGIN_NAME, it.name)
errorInformation.setUserInformation(UserInformationType.PLUGIN_VERSION, it.version)
}
}
val dataContext = DataManager.getInstance().getDataContext(parentComponent)
val project = CommonDataKeys.PROJECT.getData(dataContext)
val task = ErrorReportTask(
project,
"Submitting error report",
true,
errorInformation,
CallbackWithNotification(callback, project)
)
project?.let { ProgressManager.getInstance().run(task) } ?: run {
task.run(EmptyProgressIndicator())
}
return true
}
} | 38.071429 | 123 | 0.688823 |
18f7ecdb7f84adc1b626c2236c648d9e3f24762d | 169 | rb | Ruby | config/initializers/constants.rb | AleksandrKudashkin/bixi-list | c19bfd18649afecd21bf05b3e7152b67cdc1ae91 | [
"MIT"
] | null | null | null | config/initializers/constants.rb | AleksandrKudashkin/bixi-list | c19bfd18649afecd21bf05b3e7152b67cdc1ae91 | [
"MIT"
] | null | null | null | config/initializers/constants.rb | AleksandrKudashkin/bixi-list | c19bfd18649afecd21bf05b3e7152b67cdc1ae91 | [
"MIT"
] | null | null | null | FX_LAT = 45.506318.freeze
FX_LNG = -73.569021.freeze
REFRESH_TIMEOUT = 5.freeze
PAGE_LIMIT = 20.freeze
API_ENDPOINT = "https://secure.bixi.com/data/stations.json".freeze | 33.8 | 66 | 0.781065 |
40cc59239cb095d0547e109beef718f568bd2b7b | 21,325 | py | Python | src/journal/migrations/0001_initial.py | Nnonexistent/chemphys | d2f34364d006a494bb965bb83d1967d7dd56f9ba | [
"MIT"
] | null | null | null | src/journal/migrations/0001_initial.py | Nnonexistent/chemphys | d2f34364d006a494bb965bb83d1967d7dd56f9ba | [
"MIT"
] | 19 | 2015-03-08T08:46:09.000Z | 2019-10-01T05:16:43.000Z | src/journal/migrations/0001_initial.py | Nnonexistent/chemphys | d2f34364d006a494bb965bb83d1967d7dd56f9ba | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.utils.timezone
from django.conf import settings
import journal.models
class Migration(migrations.Migration):
dependencies = [
('auth', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='JournalUser',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(default=django.utils.timezone.now, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('moderation_status', models.PositiveSmallIntegerField(default=0, verbose_name='Moderation status', choices=[(0, 'New'), (1, 'Rejected'), (2, 'Approved')])),
('email', models.EmailField(unique=True, max_length=75, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('degree', models.CharField(default=b'', max_length=200, verbose_name='Degree', blank=True)),
('groups', models.ManyToManyField(help_text='The groups this user belongs to. A user will get all permissions granted to each of his/her group.', to='auth.Group', verbose_name='groups', blank=True)),
('user_permissions', models.ManyToManyField(help_text='Specific permissions for this user.', to='auth.Permission', verbose_name='user permissions', blank=True)),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Article',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('status', models.PositiveSmallIntegerField(default=0, verbose_name='Status', choices=[(0, 'Adding / Overview'), (1, 'Adding / Abstract'), (2, 'Adding / Authors'), (3, 'Adding / Media'), (11, 'New'), (12, 'Rejected'), (13, 'In review'), (14, 'Reviewed'), (15, 'In rework'), (10, 'Published')])),
('date_in', models.DateTimeField(default=django.utils.timezone.now, verbose_name='Date in')),
('date_published', models.DateTimeField(null=True, verbose_name='Publish date', blank=True)),
('old_number', models.SmallIntegerField(help_text='to link consistently with old articles', null=True, verbose_name='Old number', blank=True)),
('image', models.ImageField(default=b'', upload_to=journal.models.article_upload_to, verbose_name='Image', blank=True)),
('type', models.PositiveSmallIntegerField(default=1, verbose_name='Article type', choices=[(1, 'Article'), (2, 'Short message'), (3, 'Presentation'), (4, 'Data')])),
('content', models.FileField(default=b'', upload_to=b'published', verbose_name='Content', blank=True)),
],
options={
'ordering': ['date_in'],
'verbose_name': 'Article',
'verbose_name_plural': 'Articles',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='ArticleAttach',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('order', models.PositiveIntegerField(default=0, verbose_name='Order', blank=True)),
('type', models.PositiveSmallIntegerField(default=0, verbose_name='Attach type', choices=[(0, 'Generic'), (1, 'Image'), (2, 'Video')])),
('file', models.FileField(upload_to=b'attaches', verbose_name='File')),
('comment', models.TextField(default=b'', verbose_name='Comment', blank=True)),
('date_created', models.DateTimeField(default=django.utils.timezone.now, verbose_name='Date created')),
('article', models.ForeignKey(verbose_name='Article', to='journal.Article')),
],
options={
'ordering': ['order'],
'get_latest_by': 'date_created',
'verbose_name': 'Article attach',
'verbose_name_plural': 'Article attaches',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='ArticleAuthor',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('order', models.PositiveIntegerField(default=0, verbose_name='Order', blank=True)),
('article', models.ForeignKey(verbose_name='Article', to='journal.Article')),
],
options={
'ordering': ['order'],
'verbose_name': 'Article author',
'verbose_name_plural': 'Article authors',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='ArticleResolution',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('date_created', models.DateTimeField(default=django.utils.timezone.now, verbose_name='Date created')),
('status', models.PositiveSmallIntegerField(verbose_name='Status', choices=[(0, 'None'), (1, 'Rejected'), (2, 'Rework required'), (3, 'Approved')])),
('text', models.TextField(verbose_name='Text')),
('article', models.ForeignKey(verbose_name='Article', to='journal.Article')),
],
options={
'ordering': ['date_created'],
'get_latest_by': 'date_created',
'verbose_name': 'Article resolution',
'verbose_name_plural': 'Article resolutions',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='ArticleSource',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('date_created', models.DateTimeField(default=django.utils.timezone.now, verbose_name='Date created')),
('file', models.FileField(upload_to=b'sources', verbose_name='File')),
('comment', models.TextField(default=b'', verbose_name='Staff comment', blank=True)),
('article', models.ForeignKey(verbose_name='Article', to='journal.Article')),
],
options={
'ordering': ['date_created'],
'get_latest_by': 'date_created',
'verbose_name': 'Article source',
'verbose_name_plural': 'Article sources',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Issue',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('order', models.PositiveIntegerField(default=0, verbose_name='Order', blank=True)),
('is_active', models.BooleanField(default=False, verbose_name='Active')),
('number', models.CharField(max_length=100, null=True, verbose_name='Number', blank=True)),
('volume', models.PositiveIntegerField(verbose_name='Volume')),
('year', models.PositiveIntegerField(verbose_name='Year')),
('description', models.TextField(default='', verbose_name='Description', blank=True)),
],
options={
'ordering': ['order'],
'verbose_name': 'Issue',
'verbose_name_plural': 'Issues',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='LocalizedArticleContent',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('lang', models.CharField(max_length=2, verbose_name='Language', choices=[(b'ru', 'Russian'), (b'en', 'English')])),
('title', models.TextField(verbose_name='Title')),
('abstract', models.TextField(default='', verbose_name='Abstract', blank=True)),
('keywords', models.TextField(default='', verbose_name='Keywords', blank=True)),
('references', models.TextField(default=b'', verbose_name='References', blank=True)),
('article', models.ForeignKey(verbose_name='Article', to='journal.Article')),
],
options={
'ordering': ('article', 'lang'),
'verbose_name': 'Localized article content',
'verbose_name_plural': 'Localized article content',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='LocalizedName',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('lang', models.CharField(max_length=2, verbose_name='Language', choices=[(b'ru', 'Russian'), (b'en', 'English')])),
('first_name', models.CharField(max_length=60, verbose_name='First name', blank=True)),
('last_name', models.CharField(max_length=60, verbose_name='Last name', blank=True)),
('user', models.ForeignKey(verbose_name='User', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ('user', 'lang'),
'verbose_name': 'Localized name',
'verbose_name_plural': 'Localized names',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Organization',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('moderation_status', models.PositiveSmallIntegerField(default=0, verbose_name='Moderation status', choices=[(0, 'New'), (1, 'Rejected'), (2, 'Approved')])),
('short_name', models.CharField(default=b'', help_text='for admin site', max_length=32, verbose_name='Short name', blank=True)),
('alt_names', models.TextField(default=b'', help_text='one per line', verbose_name='Alternative names', blank=True)),
('site', models.URLField(default=b'', verbose_name='Site URL', blank=True)),
('obsolete', models.BooleanField(default=False, verbose_name='Obsolete')),
('previous', models.ManyToManyField(related_name='previous_rel_+', verbose_name='Previous versions', to='journal.Organization', blank=True)),
],
options={
'ordering': ['short_name'],
'verbose_name': 'Organization',
'verbose_name_plural': 'Organizations',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='OrganizationLocalizedContent',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('lang', models.CharField(max_length=2, verbose_name='Language', choices=[(b'ru', 'Russian'), (b'en', 'English')])),
('name', models.TextField(verbose_name='Name')),
('country', models.CharField(default=b'', max_length=100, verbose_name='Country', blank=True)),
('city', models.CharField(default=b'', max_length=100, verbose_name='City', blank=True)),
('address', models.TextField(default=b'', verbose_name='Address', blank=True)),
('org', models.ForeignKey(to='journal.Organization')),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='PositionInOrganization',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('position', models.CharField(default=b'', max_length=200, verbose_name='Position', blank=True)),
('organization', models.ForeignKey(verbose_name='Organization', to='journal.Organization')),
('user', models.ForeignKey(verbose_name='User', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ['id'],
'verbose_name': 'Position in organization',
'verbose_name_plural': 'Position in organizations',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Review',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('key', models.CharField(default=journal.models.default_key, verbose_name='Key', unique=True, max_length=32, editable=False)),
('status', models.PositiveSmallIntegerField(default=0, verbose_name='Status', choices=[(0, 'Pending'), (1, 'Unfinished'), (2, 'Done')])),
('date_created', models.DateTimeField(default=django.utils.timezone.now, verbose_name='Created')),
('field_values', models.TextField(default=b'', verbose_name='Field values', editable=False)),
('comment_for_authors', models.TextField(default='', verbose_name='Comment for authors', blank=True)),
('comment_for_editors', models.TextField(default='', verbose_name='Comment for editors', blank=True)),
('resolution', models.PositiveSmallIntegerField(default=0, verbose_name='Resolution', choices=[(0, 'None'), (1, 'Rejected'), (2, 'Rework required'), (3, 'Approved')])),
('article', models.ForeignKey(verbose_name='Article', to='journal.Article')),
('reviewer', models.ForeignKey(verbose_name='Reviewer', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ['date_created'],
'verbose_name': 'Review',
'verbose_name_plural': 'Reviews',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='ReviewField',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('order', models.PositiveIntegerField(default=0, verbose_name='Order', blank=True)),
('field_type', models.PositiveSmallIntegerField(verbose_name='Field type', choices=[(0, 'Header'), (1, 'Choices field'), (2, 'Text string'), (3, 'Text field'), (4, 'Checkbox')])),
('name', models.CharField(max_length=64, verbose_name='Name')),
('description', models.TextField(default=b'', verbose_name='Description', blank=True)),
('choices', models.TextField(default=b'', verbose_name='Choices', blank=True)),
],
options={
'ordering': ['order'],
'verbose_name': 'Review field',
'verbose_name_plural': 'Review fields',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='ReviewFile',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('file', models.FileField(upload_to=b'reviews', verbose_name='File')),
('comment', models.TextField(default=b'', verbose_name='Comment', blank=True)),
('review', models.ForeignKey(verbose_name='Review', to='journal.Review')),
],
options={
'ordering': ['id'],
'verbose_name': 'Review file',
'verbose_name_plural': 'Review files',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Section',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('order', models.PositiveIntegerField(default=0, verbose_name='Order', blank=True)),
('moderators', models.ManyToManyField(to=settings.AUTH_USER_MODEL, verbose_name='Moderators', blank=True)),
],
options={
'ordering': ['order'],
'verbose_name': 'Section',
'verbose_name_plural': 'Sections',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='SectionName',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('lang', models.CharField(max_length=2, verbose_name='Language', choices=[(b'ru', 'Russian'), (b'en', 'English')])),
('name', models.CharField(max_length=100, verbose_name='Name')),
('section', models.ForeignKey(verbose_name='Section', to='journal.Section')),
],
options={
'verbose_name': 'Section name',
'verbose_name_plural': 'Section names',
},
bases=(models.Model,),
),
migrations.CreateModel(
name='StaffMember',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('chief_editor', models.BooleanField(default=False, verbose_name='Chief editor')),
('editor', models.BooleanField(default=False, verbose_name='Editor')),
('reviewer', models.BooleanField(default=False, verbose_name='Reviewer')),
('user', models.OneToOneField(verbose_name='User', to=settings.AUTH_USER_MODEL)),
],
options={
'ordering': ('chief_editor', 'editor', 'reviewer', 'user__localizedname__last_name'),
'verbose_name': 'Staff member',
'verbose_name_plural': 'Staff members',
},
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name='sectionname',
unique_together=set([('lang', 'section')]),
),
migrations.AlterUniqueTogether(
name='positioninorganization',
unique_together=set([('user', 'organization')]),
),
migrations.AlterUniqueTogether(
name='organizationlocalizedcontent',
unique_together=set([('lang', 'org')]),
),
migrations.AlterUniqueTogether(
name='localizedname',
unique_together=set([('user', 'lang')]),
),
migrations.AlterUniqueTogether(
name='localizedarticlecontent',
unique_together=set([('article', 'lang')]),
),
migrations.AddField(
model_name='articleresolution',
name='reviews',
field=models.ManyToManyField(to='journal.Review', verbose_name='Reviews'),
preserve_default=True,
),
migrations.AddField(
model_name='articleauthor',
name='organization',
field=models.ForeignKey(verbose_name='Organization', to='journal.Organization'),
preserve_default=True,
),
migrations.AddField(
model_name='articleauthor',
name='user',
field=models.ForeignKey(verbose_name='User', to=settings.AUTH_USER_MODEL),
preserve_default=True,
),
migrations.AlterUniqueTogether(
name='articleauthor',
unique_together=set([('article', 'user', 'organization')]),
),
migrations.AddField(
model_name='article',
name='issue',
field=models.ForeignKey(verbose_name='Issue', blank=True, to='journal.Issue', null=True),
preserve_default=True,
),
migrations.AddField(
model_name='article',
name='sections',
field=models.ManyToManyField(to='journal.Section', verbose_name='Sections', blank=True),
preserve_default=True,
),
migrations.AddField(
model_name='article',
name='senders',
field=models.ManyToManyField(to=settings.AUTH_USER_MODEL, verbose_name='Senders', blank=True),
preserve_default=True,
),
]
| 55.678851 | 311 | 0.574115 |
7773d5f54cdcac110e6e28ec5e0a1244968c3587 | 814 | html | HTML | scratch/test.html | raydot/hf-ecc | ef1c733d164f2287d3cb755ca56e45540486e38f | [
"Unlicense"
] | null | null | null | scratch/test.html | raydot/hf-ecc | ef1c733d164f2287d3cb755ca56e45540486e38f | [
"Unlicense"
] | 5 | 2021-05-10T02:56:26.000Z | 2022-02-26T15:33:06.000Z | scratch/test.html | raydot/hf-ecc | ef1c733d164f2287d3cb755ca56e45540486e38f | [
"Unlicense"
] | null | null | null | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" type="text/css" href="test.css" />
<title>Document</title>
</head>
<body>
Flippy card:
<div class="flip-card">
<div class="flip-card--inner">
<div class="flip-card__front parent">
<h4 class="ribbon">FEATURED</h4>
<img src="https://placedog.net/300/300" alt="Avatar" style="width:300px;height:300px;">
</div>
<div class="flip-card__back parent">
<h1>Good Dogs, Inc.</h1>
<p>Dogs-R-Us</p>
<p>We Like Treats!</p>
</div>
</div>
</div>
</body>
</html> | 28.068966 | 99 | 0.546683 |
bb47c64d690631c03fe3e8175ddd76733f0dca49 | 123,869 | html | HTML | resources/html/tema.html | ferrorenan/study-javascript | 264c15d95ceb6f42c07ccad98931da2a244ad866 | [
"MIT"
] | null | null | null | resources/html/tema.html | ferrorenan/study-javascript | 264c15d95ceb6f42c07ccad98931da2a244ad866 | [
"MIT"
] | null | null | null | resources/html/tema.html | ferrorenan/study-javascript | 264c15d95ceb6f42c07ccad98931da2a244ad866 | [
"MIT"
] | null | null | null | <!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8">
<title>Tema</title>
<meta name="viewport"
content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible"
content="IE=edge"/>
<link href="/css/frontend.css" rel="stylesheet">
<style>
body {
padding-top: 20px
}
pre {
background: #f7f7f9
}
@media (min-width: 768px) {
body > .navbar-transparent {
box-shadow: none
}
body > .navbar-transparent .navbar-nav > .open > a {
box-shadow: none
}
}
#home {
padding-top: 0px
}
#home .navbar {
transition: box-shadow 200ms ease-in
}
#home .navbar-brand .nav-link {
display: inline-block;
margin-right: -30px
}
#home .navbar-brand img {
display: inline-block;
margin: 0 10px;
width: 30px
}
#home .btn {
padding: 0.6em 0.7em;
box-shadow: none;
font-size: 0.7rem
}
.bs-docs-section {
margin-top: 4em
}
.bs-docs-section .page-header h1 {
padding: 2rem 0;
font-size: 3rem
}
.dropdown-menu.show[aria-labelledby="themes"] {
display: flex;
width: 420px;
flex-wrap: wrap
}
.dropdown-menu.show[aria-labelledby="themes"] .dropdown-item {
width: 33.333%
}
.dropdown-menu.show[aria-labelledby="themes"] .dropdown-item:first-child {
width: 100%
}
.bs-component {
position: relative
}
.bs-component + .bs-component {
margin-top: 1rem
}
.bs-component .card {
margin-bottom: 1rem
}
.bs-component .modal {
position: relative;
top: auto;
right: auto;
left: auto;
bottom: auto;
z-index: 1;
display: block
}
.bs-component .modal-dialog {
width: 90%
}
.bs-component .popover {
position: relative;
display: inline-block;
width: 220px;
margin: 20px
}
#source-button {
position: absolute;
top: 0;
right: 0;
z-index: 100;
font-weight: bold
}
.nav-tabs {
margin-bottom: 15px
}
.progress {
margin-bottom: 10px
}
#footer {
margin: 5em 0
}
#footer li {
float: left;
margin-right: 1.5em;
margin-bottom: 1.5em
}
#footer p {
clear: left;
margin-bottom: 0
}
.splash {
padding: 12em 0 6em;
background-color: #2196f3;
color: #fff;
text-align: center
}
.splash .logo {
width: 160px
}
.splash h1 {
font-size: 3em;
color: #fff
}
.splash #social {
margin: 2em 0 6em
}
.splash .alert {
margin: 2em 0;
border: none
}
.splash .sponsor a {
color: #fff
}
.section-tout {
padding: 6em 0 1em;
border-bottom: 1px solid rgba(0, 0, 0, 0.05);
background-color: #eaf1f1
}
.section-tout .fa {
margin-right: 0.2em
}
.section-tout p {
margin-bottom: 5em
}
.section-preview {
padding: 4em 0 4em
}
.section-preview .preview {
margin-bottom: 4em;
background-color: #eaf1f1
}
.section-preview .preview img {
max-width: 100%
}
.section-preview .preview .image {
position: relative
}
.section-preview .preview .image:before {
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.1);
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
content: "";
pointer-events: none
}
.section-preview .preview .options {
padding: 2em;
border: 1px solid rgba(0, 0, 0, 0.05);
border-top: none;
text-align: center
}
.section-preview .preview .options p {
margin-bottom: 2em
}
.section-preview .dropdown-menu {
text-align: left
}
.section-preview .lead {
margin-bottom: 2em
}
@media (max-width: 767px) {
.section-preview .image img {
width: 100%
}
}
.sponsor img {
max-width: 100%
}
.sponsor #carbonads {
max-width: 240px;
margin: 0 auto
}
.sponsor .carbon-text {
display: block;
margin-top: 1em;
font-size: 12px
}
.sponsor .carbon-poweredby {
float: right;
margin-top: 1em;
font-size: 10px
}
@media (max-width: 767px) {
.splash {
padding-top: 8em
}
.splash .logo {
width: 100px
}
.splash h1 {
font-size: 2em
}
#banner {
margin-bottom: 2em;
text-align: center
}
}
</style>
</head>
<body>
<div class="container">
<div class="page-header"
id="banner">
<div class="row">
<div class="col-lg-8 col-md-7 col-sm-6">
<h1>Tema</h1>
<p class="lead">Agência F&MD</p>
</div>
<div class="col-lg-4 col-md-5 col-sm-6">
</div>
</div>
</div>
<!-- Navbar
================================================== -->
<div class="bs-docs-section clearfix">
<div class="row">
<div class="col-lg-12">
<div class="page-header">
<h1 id="navbars">Navbars</h1>
</div>
<div class="bs-component">
<nav class="navbar navbar-expand-lg navbar-dark bg-primary">
<a class="navbar-brand"
href="#">Navbar
</a>
<button class="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navbarColor01"
aria-controls="navbarColor01"
aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse"
id="navbarColor01">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link"
href="#">Home <span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link"
href="#">Features
</a>
</li>
<li class="nav-item">
<a class="nav-link"
href="#">Pricing
</a>
</li>
<li class="nav-item">
<a class="nav-link"
href="#">About
</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2"
type="text"
placeholder="Search">
<button class="btn btn-secondary my-2 my-sm-0"
type="submit">Search
</button>
</form>
</div>
</nav>
</div>
<div class="bs-component">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<a class="navbar-brand"
href="#">Navbar
</a>
<button class="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navbarColor02"
aria-controls="navbarColor02"
aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse"
id="navbarColor02">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link"
href="#">Home <span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link"
href="#">Features
</a>
</li>
<li class="nav-item">
<a class="nav-link"
href="#">Pricing
</a>
</li>
<li class="nav-item">
<a class="nav-link"
href="#">About
</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2"
type="text"
placeholder="Search">
<button class="btn btn-secondary my-2 my-sm-0"
type="submit">Search
</button>
</form>
</div>
</nav>
</div>
<div class="bs-component">
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand"
href="#">Navbar
</a>
<button class="navbar-toggler"
type="button"
data-toggle="collapse"
data-target="#navbarColor03"
aria-controls="navbarColor03"
aria-expanded="false"
aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse"
id="navbarColor03">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link"
href="#">Home <span class="sr-only">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link"
href="#">Features
</a>
</li>
<li class="nav-item">
<a class="nav-link"
href="#">Pricing
</a>
</li>
<li class="nav-item">
<a class="nav-link"
href="#">About
</a>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2"
type="text"
placeholder="Search">
<button class="btn btn-secondary my-2 my-sm-0"
type="submit">Search
</button>
</form>
</div>
</nav>
</div>
</div>
</div>
</div>
<!-- Buttons
================================================== -->
<div class="bs-docs-section">
<div class="page-header">
<div class="row">
<div class="col-lg-12">
<h1 id="buttons">Buttons</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-7">
<p class="bs-component">
<button type="button"
class="btn btn-primary">Primary
</button>
<button type="button"
class="btn btn-secondary">Secondary
</button>
<button type="button"
class="btn btn-success">Success
</button>
<button type="button"
class="btn btn-info">Info
</button>
<button type="button"
class="btn btn-warning">Warning
</button>
<button type="button"
class="btn btn-danger">Danger
</button>
<button type="button"
class="btn btn-link">Link
</button>
</p>
<p class="bs-component">
<button type="button"
class="btn btn-primary disabled">Primary
</button>
<button type="button"
class="btn btn-secondary disabled">Secondary
</button>
<button type="button"
class="btn btn-success disabled">Success
</button>
<button type="button"
class="btn btn-info disabled">Info
</button>
<button type="button"
class="btn btn-warning disabled">Warning
</button>
<button type="button"
class="btn btn-danger disabled">Danger
</button>
<button type="button"
class="btn btn-link disabled">Link
</button>
</p>
<p class="bs-component">
<button type="button"
class="btn btn-outline-primary">Primary
</button>
<button type="button"
class="btn btn-outline-secondary">Secondary
</button>
<button type="button"
class="btn btn-outline-success">Success
</button>
<button type="button"
class="btn btn-outline-info">Info
</button>
<button type="button"
class="btn btn-outline-warning">Warning
</button>
<button type="button"
class="btn btn-outline-danger">Danger
</button>
</p>
<div class="bs-component">
<div class="btn-group"
role="group"
aria-label="Button group with nested dropdown">
<button type="button"
class="btn btn-primary">Primary
</button>
<div class="btn-group"
role="group">
<button id="btnGroupDrop1"
type="button"
class="btn btn-primary dropdown-toggle"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"></button>
<div class="dropdown-menu"
aria-labelledby="btnGroupDrop1">
<a class="dropdown-item"
href="#">Dropdown link
</a>
<a class="dropdown-item"
href="#">Dropdown link
</a>
</div>
</div>
</div>
<div class="btn-group"
role="group"
aria-label="Button group with nested dropdown">
<button type="button"
class="btn btn-success">Success
</button>
<div class="btn-group"
role="group">
<button id="btnGroupDrop2"
type="button"
class="btn btn-success dropdown-toggle"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"></button>
<div class="dropdown-menu"
aria-labelledby="btnGroupDrop2">
<a class="dropdown-item"
href="#">Dropdown link
</a>
<a class="dropdown-item"
href="#">Dropdown link
</a>
</div>
</div>
</div>
<div class="btn-group"
role="group"
aria-label="Button group with nested dropdown">
<button type="button"
class="btn btn-info">Info
</button>
<div class="btn-group"
role="group">
<button id="btnGroupDrop3"
type="button"
class="btn btn-info dropdown-toggle"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"></button>
<div class="dropdown-menu"
aria-labelledby="btnGroupDrop3">
<a class="dropdown-item"
href="#">Dropdown link
</a>
<a class="dropdown-item"
href="#">Dropdown link
</a>
</div>
</div>
</div>
<div class="btn-group"
role="group"
aria-label="Button group with nested dropdown">
<button type="button"
class="btn btn-danger">Danger
</button>
<div class="btn-group"
role="group">
<button id="btnGroupDrop4"
type="button"
class="btn btn-danger dropdown-toggle"
data-toggle="dropdown"
aria-haspopup="true"
aria-expanded="false"></button>
<div class="dropdown-menu"
aria-labelledby="btnGroupDrop4">
<a class="dropdown-item"
href="#">Dropdown link
</a>
<a class="dropdown-item"
href="#">Dropdown link
</a>
</div>
</div>
</div>
</div>
<div class="bs-component">
<button type="button"
class="btn btn-primary btn-lg">Large button
</button>
<button type="button"
class="btn btn-primary">Default button
</button>
<button type="button"
class="btn btn-primary btn-sm">Small button
</button>
</div>
<div class="bs-component">
<h2>
Buttons + spinners
</h2>
<!-- Para alterar o padding horizontal acesse: frontnend/_variables.scss-->
<!-- e edite a variável $btn-spinner-padding-x-->
<span class="badge badge-danger">
Em teste
</span>
<div class="mt-1">
<button type="submit"
class="btn btn-primary btn-spinner">
<span class="position-relative">
<span class="spinner-border spinner-border-sm text-light"
role="status"></span>
Enviar
</span>
</button>
</div>
</div>
</div>
<div class="col-lg-5">
<p class="bs-component">
<button type="button"
class="btn btn-primary btn-lg btn-block">Block level
button
</button>
</p>
<div class="bs-component"
style="margin-bottom: 15px;">
<div class="btn-group btn-group-toggle"
data-toggle="buttons">
<label class="btn btn-primary active">
<input type="checkbox"
checked
autocomplete="off">
Active
</label>
<label class="btn btn-primary">
<input type="checkbox"
autocomplete="off">
Check
</label>
<label class="btn btn-primary">
<input type="checkbox"
autocomplete="off">
Check
</label>
</div>
</div>
<div class="bs-component"
style="margin-bottom: 15px;">
<div class="btn-group btn-group-toggle"
data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio"
name="options"
id="option1"
autocomplete="off"
checked>
Active
</label>
<label class="btn btn-primary">
<input type="radio"
name="options"
id="option2"
autocomplete="off">
Radio
</label>
<label class="btn btn-primary">
<input type="radio"
name="options"
id="option3"
autocomplete="off">
Radio
</label>
</div>
</div>
<div class="bs-component"
style="margin-bottom: 15px;">
<div class="btn-group"
role="group"
aria-label="Basic example">
<button type="button"
class="btn btn-secondary">Left
</button>
<button type="button"
class="btn btn-secondary">Middle
</button>
<button type="button"
class="btn btn-secondary">Right
</button>
</div>
</div>
<div class="bs-component"
style="margin-bottom: 15px;">
<div class="btn-toolbar"
role="toolbar"
aria-label="Toolbar with button groups">
<div class="btn-group mr-2"
role="group"
aria-label="First group">
<button type="button"
class="btn btn-secondary">1
</button>
<button type="button"
class="btn btn-secondary">2
</button>
<button type="button"
class="btn btn-secondary">3
</button>
<button type="button"
class="btn btn-secondary">4
</button>
</div>
<div class="btn-group mr-2"
role="group"
aria-label="Second group">
<button type="button"
class="btn btn-secondary">5
</button>
<button type="button"
class="btn btn-secondary">6
</button>
<button type="button"
class="btn btn-secondary">7
</button>
</div>
<div class="btn-group"
role="group"
aria-label="Third group">
<button type="button"
class="btn btn-secondary">8
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Typography
================================================== -->
<div class="bs-docs-section">
<div class="row">
<div class="col-lg-12">
<div class="page-header">
<h1 id="typography">Typography</h1>
</div>
</div>
</div>
<!-- Headings -->
<div class="row">
<div class="col-lg-4">
<div class="bs-component">
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>
<h3>
Heading
<small class="text-muted">with muted text</small>
</h3>
<p class="lead">Vivamus sagittis lacus vel augue laoreet rutrum
faucibus dolor auctor.
</p>
</div>
</div>
<div class="col-lg-4">
<div class="bs-component">
<h2>Example body text</h2>
<p>Nullam quis risus eget
<a href="#">urna mollis ornare</a>
vel eu leo. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus
mus.
Nullam id dolor id nibh
ultricies vehicula.
</p>
<p>
<small>This line of text is meant to be treated as fine print.
</small>
</p>
<p>The following is <strong>rendered as bold text</strong>.</p>
<p>The following is <em>rendered as italicized text</em>.</p>
<p>An abbreviation of the word attribute is
<abbr title="attribute">attr</abbr>.
</p>
</div>
</div>
<div class="col-lg-4">
<div class="bs-component">
<h2>Emphasis classes</h2>
<p class="text-muted">Fusce dapibus, tellus ac cursus commodo,
tortor
mauris nibh.
</p>
<p class="text-primary">Nullam id dolor id nibh ultricies vehicula
ut
id elit.
</p>
<p class="text-warning">Etiam porta sem malesuada magna mollis
euismod.
</p>
<p class="text-danger">Donec ullamcorper nulla non metus auctor
fringilla.
</p>
<p class="text-success">Duis mollis, est non commodo luctus, nisi
erat
porttitor ligula.
</p>
<p class="text-info">Maecenas sed diam eget risus varius blandit
sit
amet non magna.
</p>
</div>
</div>
</div>
<!-- Blockquotes -->
<div class="row">
<div class="col-lg-12">
<h2 id="type-blockquotes">Blockquotes</h2>
</div>
</div>
<div class="row">
<div class="col-lg-4">
<div class="bs-component">
<blockquote class="blockquote">
<p class="mb-0">Lorem ipsum dolor sit amet, consectetur
adipiscing
elit. Integer posuere erat a
ante.
</p>
<footer class="blockquote-footer">Someone famous in
<cite title="Source Title">Source
Title</cite></footer>
</blockquote>
</div>
</div>
<div class="col-lg-4">
<div class="bs-component">
<blockquote class="blockquote text-center">
<p class="mb-0">Lorem ipsum dolor sit amet, consectetur
adipiscing
elit. Integer posuere erat a
ante.
</p>
<footer class="blockquote-footer">Someone famous in
<cite title="Source Title">Source
Title</cite></footer>
</blockquote>
</div>
</div>
<div class="col-lg-4">
<div class="bs-component">
<blockquote class="blockquote text-right">
<p class="mb-0">Lorem ipsum dolor sit amet, consectetur
adipiscing
elit. Integer posuere erat a
ante.
</p>
<footer class="blockquote-footer">Someone famous in
<cite title="Source Title">Source
Title</cite></footer>
</blockquote>
</div>
</div>
</div>
</div>
<!-- Tables
================================================== -->
<div class="bs-docs-section">
<div class="row">
<div class="col-lg-12">
<div class="page-header">
<h1 id="tables">Tables</h1>
</div>
<div class="bs-component">
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Type</th>
<th scope="col">Column heading</th>
<th scope="col">Column heading</th>
<th scope="col">Column heading</th>
</tr>
</thead>
<tbody>
<tr class="table-active">
<th scope="row">Active</th>
<td>Column content</td>
<td>Column content</td>
<td>Column content</td>
</tr>
<tr>
<th scope="row">Default</th>
<td>Column content</td>
<td>Column content</td>
<td>Column content</td>
</tr>
<tr class="table-primary">
<th scope="row">Primary</th>
<td>Column content</td>
<td>Column content</td>
<td>Column content</td>
</tr>
<tr class="table-secondary">
<th scope="row">Secondary</th>
<td>Column content</td>
<td>Column content</td>
<td>Column content</td>
</tr>
<tr class="table-success">
<th scope="row">Success</th>
<td>Column content</td>
<td>Column content</td>
<td>Column content</td>
</tr>
<tr class="table-danger">
<th scope="row">Danger</th>
<td>Column content</td>
<td>Column content</td>
<td>Column content</td>
</tr>
<tr class="table-warning">
<th scope="row">Warning</th>
<td>Column content</td>
<td>Column content</td>
<td>Column content</td>
</tr>
<tr class="table-info">
<th scope="row">Info</th>
<td>Column content</td>
<td>Column content</td>
<td>Column content</td>
</tr>
<tr class="table-light">
<th scope="row">Light</th>
<td>Column content</td>
<td>Column content</td>
<td>Column content</td>
</tr>
<tr class="table-dark">
<th scope="row">Dark</th>
<td>Column content</td>
<td>Column content</td>
<td>Column content</td>
</tr>
</tbody>
</table>
</div><!-- /example -->
</div>
</div>
</div>
<!-- Forms
================================================== -->
<div class="bs-docs-section">
<div class="row">
<div class="col-lg-12">
<div class="page-header">
<h1 id="forms">Forms</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<div class="bs-component">
<form>
<fieldset>
<legend>Legend</legend>
<div class="form-group row">
<label for="staticEmail"
class="col-sm-2 col-form-label">Email
</label>
<div class="col-sm-10">
<input type="text"
readonly
class="form-control-plaintext"
id="staticEmail"
value="email@example.com">
</div>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email"
class="form-control"
id="exampleInputEmail1"
aria-describedby="emailHelp"
placeholder="Enter email">
<small id="emailHelp"
class="form-text text-muted">We'll never share your
email
with
anyone else.
</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password"
class="form-control"
id="exampleInputPassword1"
placeholder="Password">
</div>
<div class="form-group">
<label for="exampleSelect1">Example select</label>
<select class="form-control"
id="exampleSelect1">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<div class="form-group">
<label for="exampleSelect2">Example multiple select</label>
<select multiple
class="form-control"
id="exampleSelect2">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
<div class="form-group">
<label for="exampleTextarea">Example textarea</label>
<textarea class="form-control"
id="exampleTextarea"
rows="3"></textarea>
</div>
<div class="form-group">
<label for="exampleInputFile">File input</label>
<input type="file"
class="form-control-file"
id="exampleInputFile"
aria-describedby="fileHelp">
<small id="fileHelp"
class="form-text text-muted">This is some placeholder
block-level
help text for the above
input. It's a bit
lighter
and easily wraps to a
new
line.
</small>
</div>
<fieldset class="form-group">
<legend>Radio buttons</legend>
<div class="form-check">
<label class="form-check-label">
<input type="radio"
class="form-check-input"
name="optionsRadios"
id="optionsRadios1"
value="option1"
checked>
Option one is this and that—be sure to include why
it's great
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input type="radio"
class="form-check-input"
name="optionsRadios"
id="optionsRadios2"
value="option2">
Option two can be something else and selecting it will
deselect option one
</label>
</div>
<div class="form-check disabled">
<label class="form-check-label">
<input type="radio"
class="form-check-input"
name="optionsRadios"
id="optionsRadios3"
value="option3"
disabled>
Option three is disabled
</label>
</div>
</fieldset>
<fieldset class="form-group">
<legend>Checkboxes</legend>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input"
type="checkbox"
value=""
checked>
Option one is this and that—be sure to include why
it's great
</label>
</div>
<div class="form-check disabled">
<label class="form-check-label">
<input class="form-check-input"
type="checkbox"
value=""
disabled>
Option two is disabled
</label>
</div>
</fieldset>
<button type="submit"
class="btn btn-primary">Submit
</button>
</fieldset>
</form>
</div>
</div>
<div class="col-lg-4 offset-lg-1">
<form class="bs-component">
<div class="form-group">
<fieldset disabled>
<label class="control-label"
for="disabledInput">Disabled input
</label>
<input class="form-control"
id="disabledInput"
type="text"
placeholder="Disabled input here..."
disabled="">
</fieldset>
</div>
<div class="form-group">
<fieldset>
<label class="control-label"
for="readOnlyInput">Readonly input
</label>
<input class="form-control"
id="readOnlyInput"
type="text"
placeholder="Readonly input here…"
readonly>
</fieldset>
</div>
<div class="form-group has-success">
<label class="form-control-label"
for="inputSuccess1">Valid input
</label>
<input type="text"
value="correct value"
class="form-control is-valid"
id="inputValid">
<div class="valid-feedback">Success! You've done it.</div>
</div>
<div class="form-group has-danger">
<label class="form-control-label"
for="inputDanger1">Invalid input
</label>
<input type="text"
value="wrong value"
class="form-control is-invalid"
id="inputInvalid">
<div class="invalid-feedback">Sorry, that username's taken. Try
another?
</div>
</div>
<div class="form-group">
<label class="col-form-label col-form-label-lg"
for="inputLarge">Large input
</label>
<input class="form-control form-control-lg"
type="text"
placeholder=".form-control-lg"
id="inputLarge">
</div>
<div class="form-group">
<label class="col-form-label"
for="inputDefault">Default input
</label>
<input type="text"
class="form-control"
placeholder="Default input"
id="inputDefault">
</div>
<div class="form-group">
<label class="col-form-label col-form-label-sm"
for="inputSmall">Small input
</label>
<input class="form-control form-control-sm"
type="text"
placeholder=".form-control-sm"
id="inputSmall">
</div>
<div class="form-group">
<label class="control-label">Input addons</label>
<div class="form-group">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">$</span>
</div>
<input type="text"
class="form-control"
aria-label="Amount (to the nearest dollar)">
<div class="input-group-append">
<span class="input-group-text">.00</span>
</div>
</div>
</div>
</div>
</form>
<div class="bs-component">
<fieldset>
<legend>Custom forms</legend>
<div class="form-group">
<div class="custom-control custom-radio">
<input type="radio"
id="customRadio1"
name="customRadio"
class="custom-control-input"
checked>
<label class="custom-control-label"
for="customRadio1">Toggle this custom radio
</label>
</div>
<div class="custom-control custom-radio">
<input type="radio"
id="customRadio2"
name="customRadio"
class="custom-control-input">
<label class="custom-control-label"
for="customRadio2">Or toggle this other custom
radio
</label>
</div>
<div class="custom-control custom-radio">
<input type="radio"
id="customRadio3"
name="customRadio"
class="custom-control-input"
disabled>
<label class="custom-control-label"
for="customRadio3">Disabled custom radio
</label>
</div>
</div>
<div class="form-group">
<div class="custom-control custom-checkbox">
<input type="checkbox"
class="custom-control-input"
id="customCheck1"
checked>
<label class="custom-control-label"
for="customCheck1">Check this custom
checkbox
</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox"
class="custom-control-input"
id="customCheck2"
disabled>
<label class="custom-control-label"
for="customCheck2">Disabled custom checkbox
</label>
</div>
</div>
<div class="form-group">
<select class="custom-select">
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
<div class="form-group">
<div class="custom-file">
<input type="file"
id="exampleInputFileCustom"
aria-describedby="fileHelp"
class="custom-file-input">
<label for="exampleInputFileCustom"
class="custom-file-label">
File input custom
</label>
</div>
</div>
</fieldset>
</div>
</div>
</div>
<p>Trava botão no submit</p>
<form class="needs-validation"
novalidate>
<div class="row">
<div class="col-6">
<div class="form-group">
<label class=""
for="news-name">Nome
</label>
<input type="text"
class="form-control"
placeholder="Nome"
id="news-name"
required>
<div class="invalid-feedback">
Digite o campo nome.
</div>
</div>
<button type="submit"
class="btn btn-primary btn-block">
Enviar
</button>
</div>
</div>
</form>
</div>
<!-- Navs
================================================== -->
<div class="bs-docs-section">
<div class="row">
<div class="col-lg-12">
<div class="page-header">
<h1 id="navs">Navs</h1>
</div>
</div>
</div>
<div class="row"
style="margin-bottom: 2rem;">
<div class="col-lg-6">
<h2 id="nav-tabs">Tabs</h2>
<div class="bs-component">
<ul class="nav nav-tabs">
<li class="nav-item">
<a class="nav-link active"
data-toggle="tab"
href="#home">Home
</a>
</li>
<li class="nav-item">
<a class="nav-link"
data-toggle="tab"
href="#profile">Profile
</a>
</li>
<li class="nav-item">
<a class="nav-link disabled"
href="#">Disabled
</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle"
data-toggle="dropdown"
href="#"
role="button"
aria-haspopup="true"
aria-expanded="false">Dropdown
</a>
<div class="dropdown-menu">
<a class="dropdown-item"
href="#">Action
</a>
<a class="dropdown-item"
href="#">Another action
</a>
<a class="dropdown-item"
href="#">Something else here
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item"
href="#">Separated link
</a>
</div>
</li>
</ul>
<div id="myTabContent"
class="tab-content">
<div class="tab-pane fade show active"
id="home">
<p>Raw denim you probably haven't heard of them jean shorts
Austin. Nesciunt tofu stumptown
aliqua, retro synth master cleanse. Mustache cliche tempor,
williamsburg carles vegan
helvetica. Reprehenderit butcher retro keffiyeh
dreamcatcher
synth. Cosby sweater eu
banh mi, qui irure terry richardson ex squid. Aliquip
placeat
salvia cillum iphone.
Seitan aliquip quis cardigan american apparel, butcher
voluptate nisi qui.
</p>
</div>
<div class="tab-pane fade"
id="profile">
<p>Food truck fixie locavore, accusamus mcsweeney's marfa
nulla
single-origin coffee squid.
Exercitation +1 labore velit, blog sartorial PBR leggings
next
level wes anderson
artisan four loko farm-to-table craft beer twee. Qui photo
booth letterpress, commodo
enim craft beer mlkshk aliquip jean shorts ullamco ad vinyl
cillum PBR. Homo nostrud
organic, assumenda labore aesthetic magna delectus mollit.
</p>
</div>
<div class="tab-pane fade"
id="dropdown1">
<p>Etsy mixtape wayfarers, ethical wes anderson tofu before
they
sold out mcsweeney's
organic lomo retro fanny pack lo-fi farm-to-table
readymade.
Messenger bag gentrify
pitchfork tattooed craft beer, iphone skateboard locavore
carles etsy salvia banksy
hoodie helvetica. DIY synth PBR banksy irony. Leggings
gentrify
squid 8-bit cred
pitchfork.
</p>
</div>
<div class="tab-pane fade"
id="dropdown2">
<p>Trust fund seitan letterpress, keytar raw denim keffiyeh
etsy
art party before they sold
out master cleanse gluten-free squid scenester freegan
cosby
sweater. Fanny pack
portland seitan DIY, art party locavore wolf cliche high
life
echo park Austin. Cred
vinyl keffiyeh DIY salvia PBR, banh mi before they sold out
farm-to-table VHS viral
locavore cosby sweater.
</p>
</div>
</div>
</div>
</div>
<div class="col-lg-6">
<h2 id="nav-pills">Pills</h2>
<div class="bs-component">
<ul class="nav nav-pills">
<li class="nav-item">
<a class="nav-link active"
href="#">Active
</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle"
data-toggle="dropdown"
href="#"
role="button"
aria-haspopup="true"
aria-expanded="false">Dropdown
</a>
<div class="dropdown-menu">
<a class="dropdown-item"
href="#">Action
</a>
<a class="dropdown-item"
href="#">Another action
</a>
<a class="dropdown-item"
href="#">Something else here
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item"
href="#">Separated link
</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link"
href="#">Link
</a>
</li>
<li class="nav-item">
<a class="nav-link disabled"
href="#">Disabled
</a>
</li>
</ul>
</div>
<br>
<div class="bs-component">
<ul class="nav nav-pills flex-column">
<li class="nav-item">
<a class="nav-link active"
href="#">Active
</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle"
data-toggle="dropdown"
href="#"
role="button"
aria-haspopup="true"
aria-expanded="false">Dropdown
</a>
<div class="dropdown-menu">
<a class="dropdown-item"
href="#">Action
</a>
<a class="dropdown-item"
href="#">Another action
</a>
<a class="dropdown-item"
href="#">Something else here
</a>
<div class="dropdown-divider"></div>
<a class="dropdown-item"
href="#">Separated link
</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link"
href="#">Link
</a>
</li>
<li class="nav-item">
<a class="nav-link disabled"
href="#">Disabled
</a>
</li>
</ul>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<h2 id="nav-breadcrumbs">Breadcrumbs</h2>
<div class="bs-component">
<ol class="breadcrumb">
<li class="breadcrumb-item active">Home</li>
</ol>
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="#">Home</a>
</li>
<li class="breadcrumb-item active">Library</li>
</ol>
<ol class="breadcrumb">
<li class="breadcrumb-item">
<a href="#">Home</a>
</li>
<li class="breadcrumb-item">
<a href="#">Library</a>
</li>
<li class="breadcrumb-item active">Data</li>
</ol>
</div>
</div>
<div class="col-lg-6">
<h2 id="pagination">Pagination</h2>
<div class="bs-component">
<div>
<ul class="pagination">
<li class="page-item disabled">
<a class="page-link"
href="#">«
</a>
</li>
<li class="page-item active">
<a class="page-link"
href="#">1
</a>
</li>
<li class="page-item">
<a class="page-link"
href="#">2
</a>
</li>
<li class="page-item">
<a class="page-link"
href="#">3
</a>
</li>
<li class="page-item">
<a class="page-link"
href="#">4
</a>
</li>
<li class="page-item">
<a class="page-link"
href="#">5
</a>
</li>
<li class="page-item">
<a class="page-link"
href="#">»
</a>
</li>
</ul>
</div>
<div>
<ul class="pagination pagination-lg">
<li class="page-item disabled">
<a class="page-link"
href="#">«
</a>
</li>
<li class="page-item active">
<a class="page-link"
href="#">1
</a>
</li>
<li class="page-item">
<a class="page-link"
href="#">2
</a>
</li>
<li class="page-item">
<a class="page-link"
href="#">3
</a>
</li>
<li class="page-item">
<a class="page-link"
href="#">4
</a>
</li>
<li class="page-item">
<a class="page-link"
href="#">5
</a>
</li>
<li class="page-item">
<a class="page-link"
href="#">»
</a>
</li>
</ul>
</div>
<div>
<ul class="pagination pagination-sm">
<li class="page-item disabled">
<a class="page-link"
href="#">«
</a>
</li>
<li class="page-item active">
<a class="page-link"
href="#">1
</a>
</li>
<li class="page-item">
<a class="page-link"
href="#">2
</a>
</li>
<li class="page-item">
<a class="page-link"
href="#">3
</a>
</li>
<li class="page-item">
<a class="page-link"
href="#">4
</a>
</li>
<li class="page-item">
<a class="page-link"
href="#">5
</a>
</li>
<li class="page-item">
<a class="page-link"
href="#">»
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!-- Indicators
================================================== -->
<div class="bs-docs-section">
<div class="row">
<div class="col-lg-12">
<div class="page-header">
<h1 id="indicators">Indicators</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<h2>Alerts</h2>
<div class="bs-component">
<div class="alert alert-dismissible alert-warning">
<button type="button"
class="close"
data-dismiss="alert">×
</button>
<h4 class="alert-heading">Warning!</h4>
<p class="mb-0">Best check yo self, you're not looking too good.
Nulla vitae elit libero, a
pharetra augue. Praesent commodo cursus magna,
<a href="#"
class="alert-link">vel
scelerisque nisl consectetur et
</a>
.
</p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-4">
<div class="bs-component">
<div class="alert alert-dismissible alert-danger">
<button type="button"
class="close"
data-dismiss="alert">×
</button>
<strong>Oh snap!</strong>
<a href="#"
class="alert-link">Change a few things up
</a>
and try
submitting again.
</div>
</div>
</div>
<div class="col-lg-4">
<div class="bs-component">
<div class="alert alert-dismissible alert-success">
<button type="button"
class="close"
data-dismiss="alert">×
</button>
<strong>Well done!</strong> You successfully read
<a href="#"
class="alert-link">this important
alert message
</a>
.
</div>
</div>
</div>
<div class="col-lg-4">
<div class="bs-component">
<div class="alert alert-dismissible alert-info">
<button type="button"
class="close"
data-dismiss="alert">×
</button>
<strong>Heads up!</strong> This
<a href="#"
class="alert-link">alert needs your attention
</a>
,
but it's not super important.
</div>
</div>
</div>
</div>
<div>
<h2>Badges</h2>
<div class="bs-component"
style="margin-bottom: 40px;">
<span class="badge badge-primary">Primary</span>
<span class="badge badge-secondary">Secondary</span>
<span class="badge badge-success">Success</span>
<span class="badge badge-danger">Danger</span>
<span class="badge badge-warning">Warning</span>
<span class="badge badge-info">Info</span>
<span class="badge badge-light">Light</span>
<span class="badge badge-dark">Dark</span>
</div>
<div class="bs-component">
<span class="badge badge-pill badge-primary">Primary</span>
<span class="badge badge-pill badge-secondary">Secondary</span>
<span class="badge badge-pill badge-success">Success</span>
<span class="badge badge-pill badge-danger">Danger</span>
<span class="badge badge-pill badge-warning">Warning</span>
<span class="badge badge-pill badge-info">Info</span>
<span class="badge badge-pill badge-light">Light</span>
<span class="badge badge-pill badge-dark">Dark</span>
</div>
</div>
</div>
<!-- Progress
================================================== -->
<div class="bs-docs-section">
<div class="row">
<div class="col-lg-12">
<div class="page-header">
<h1 id="progress">Progress</h1>
</div>
<h3 id="progress-basic">Basic</h3>
<div class="bs-component">
<div class="progress">
<div class="progress-bar"
role="progressbar"
style="width: 25%;"
aria-valuenow="25"
aria-valuemin="0"
aria-valuemax="100"></div>
</div>
</div>
<h3 id="progress-alternatives">Contextual alternatives</h3>
<div class="bs-component">
<div class="progress">
<div class="progress-bar bg-success"
role="progressbar"
style="width: 25%"
aria-valuenow="25"
aria-valuemin="0"
aria-valuemax="100"></div>
</div>
<div class="progress">
<div class="progress-bar bg-info"
role="progressbar"
style="width: 50%"
aria-valuenow="50"
aria-valuemin="0"
aria-valuemax="100"></div>
</div>
<div class="progress">
<div class="progress-bar bg-warning"
role="progressbar"
style="width: 75%"
aria-valuenow="75"
aria-valuemin="0"
aria-valuemax="100"></div>
</div>
<div class="progress">
<div class="progress-bar bg-danger"
role="progressbar"
style="width: 100%"
aria-valuenow="100"
aria-valuemin="0"
aria-valuemax="100"></div>
</div>
</div>
<h3 id="progress-multiple">Multiple bars</h3>
<div class="bs-component">
<div class="progress">
<div class="progress-bar"
role="progressbar"
style="width: 15%"
aria-valuenow="15"
aria-valuemin="0"
aria-valuemax="100"></div>
<div class="progress-bar bg-success"
role="progressbar"
style="width: 30%"
aria-valuenow="30"
aria-valuemin="0"
aria-valuemax="100"></div>
<div class="progress-bar bg-info"
role="progressbar"
style="width: 20%"
aria-valuenow="20"
aria-valuemin="0"
aria-valuemax="100"></div>
</div>
</div>
<h3 id="progress-striped">Striped</h3>
<div class="bs-component">
<div class="progress">
<div class="progress-bar progress-bar-striped"
role="progressbar"
style="width: 10%"
aria-valuenow="10"
aria-valuemin="0"
aria-valuemax="100"></div>
</div>
<div class="progress">
<div class="progress-bar progress-bar-striped bg-success"
role="progressbar"
style="width: 25%"
aria-valuenow="25"
aria-valuemin="0"
aria-valuemax="100"></div>
</div>
<div class="progress">
<div class="progress-bar progress-bar-striped bg-info"
role="progressbar"
style="width: 50%"
aria-valuenow="50"
aria-valuemin="0"
aria-valuemax="100"></div>
</div>
<div class="progress">
<div class="progress-bar progress-bar-striped bg-warning"
role="progressbar"
style="width: 75%"
aria-valuenow="75"
aria-valuemin="0"
aria-valuemax="100"></div>
</div>
<div class="progress">
<div class="progress-bar progress-bar-striped bg-danger"
role="progressbar"
style="width: 100%"
aria-valuenow="100"
aria-valuemin="0"
aria-valuemax="100"></div>
</div>
</div>
<h3 id="progress-animated">Animated</h3>
<div class="bs-component">
<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated"
role="progressbar"
aria-valuenow="75"
aria-valuemin="0"
aria-valuemax="100"
style="width: 75%"></div>
</div>
</div>
</div>
</div>
</div>
<!-- Containers
================================================== -->
<div class="bs-docs-section">
<div class="row">
<div class="col-lg-12">
<div class="page-header">
<h1 id="containers">Containers</h1>
</div>
<div class="bs-component">
<div class="jumbotron">
<h1 class="display-3">Hello, world!</h1>
<p class="lead">This is a simple hero unit, a simple
jumbotron-style
component for calling extra
attention to featured content or information.
</p>
<hr class="my-4">
<p>It uses utility classes for typography and spacing to space
content out within the larger
container.
</p>
<p class="lead">
<a class="btn btn-primary btn-lg"
href="#"
role="button">Learn more
</a>
</p>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<h2>List groups</h2>
</div>
</div>
<div class="row">
<div class="col-lg-4">
<div class="bs-component">
<ul class="list-group">
<li class="list-group-item d-flex justify-content-between align-items-center">
Cras justo odio
<span class="badge badge-primary badge-pill">14</span>
</li>
<li class="list-group-item d-flex justify-content-between align-items-center">
Dapibus ac facilisis in
<span class="badge badge-primary badge-pill">2</span>
</li>
<li class="list-group-item d-flex justify-content-between align-items-center">
Morbi leo risus
<span class="badge badge-primary badge-pill">1</span>
</li>
</ul>
</div>
</div>
<div class="col-lg-4">
<div class="bs-component">
<div class="list-group">
<a href="#"
class="list-group-item list-group-item-action active">
Cras justo odio
</a>
<a href="#"
class="list-group-item list-group-item-action">Dapibus ac
facilisis in
</a>
<a href="#"
class="list-group-item list-group-item-action disabled">Morbi
leo
risus
</a>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="bs-component">
<div class="list-group">
<a href="#"
class="list-group-item list-group-item-action flex-column align-items-start active">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1">List group item heading</h5>
<small>3 days ago</small>
</div>
<p class="mb-1">Donec id elit non mi porta gravida at eget
metus.
Maecenas sed diam eget
risus varius blandit.
</p>
<small>Donec id elit non mi porta.</small>
</a>
<a href="#"
class="list-group-item list-group-item-action flex-column align-items-start">
<div class="d-flex w-100 justify-content-between">
<h5 class="mb-1">List group item heading</h5>
<small class="text-muted">3 days ago</small>
</div>
<p class="mb-1">Donec id elit non mi porta gravida at eget
metus.
Maecenas sed diam eget
risus varius blandit.
</p>
<small class="text-muted">Donec id elit non mi porta.</small>
</a>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<h2>Cards</h2>
</div>
</div>
<div class="row">
<div class="col-lg-4">
<div class="bs-component">
<div class="card text-white bg-primary mb-3"
style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body">
<h4 class="card-title">Primary card title</h4>
<p class="card-text">Some quick example text to build on the
card
title and make up the bulk
of the card's content.
</p>
</div>
</div>
<div class="card text-white bg-secondary mb-3"
style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body">
<h4 class="card-title">Secondary card title</h4>
<p class="card-text">Some quick example text to build on the
card
title and make up the bulk
of the card's content.
</p>
</div>
</div>
<div class="card text-white bg-success mb-3"
style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body">
<h4 class="card-title">Success card title</h4>
<p class="card-text">Some quick example text to build on the
card
title and make up the bulk
of the card's content.
</p>
</div>
</div>
<div class="card text-white bg-danger mb-3"
style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body">
<h4 class="card-title">Danger card title</h4>
<p class="card-text">Some quick example text to build on the
card
title and make up the bulk
of the card's content.
</p>
</div>
</div>
<div class="card text-white bg-warning mb-3"
style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body">
<h4 class="card-title">Warning card title</h4>
<p class="card-text">Some quick example text to build on the
card
title and make up the bulk
of the card's content.
</p>
</div>
</div>
<div class="card text-white bg-info mb-3"
style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body">
<h4 class="card-title">Info card title</h4>
<p class="card-text">Some quick example text to build on the
card
title and make up the bulk
of the card's content.
</p>
</div>
</div>
<div class="card bg-light mb-3"
style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body">
<h4 class="card-title">Light card title</h4>
<p class="card-text">Some quick example text to build on the
card
title and make up the bulk
of the card's content.
</p>
</div>
</div>
<div class="card text-white bg-dark mb-3"
style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body">
<h4 class="card-title">Dark card title</h4>
<p class="card-text">Some quick example text to build on the
card
title and make up the bulk
of the card's content.
</p>
</div>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="bs-component">
<div class="card border-primary mb-3"
style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body text-primary">
<h4 class="card-title">Primary card title</h4>
<p class="card-text">Some quick example text to build on the
card
title and make up the bulk
of the card's content.
</p>
</div>
</div>
<div class="card border-secondary mb-3"
style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body text-secondary">
<h4 class="card-title">Secondary card title</h4>
<p class="card-text">Some quick example text to build on the
card
title and make up the bulk
of the card's content.
</p>
</div>
</div>
<div class="card border-success mb-3"
style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body text-success">
<h4 class="card-title">Success card title</h4>
<p class="card-text">Some quick example text to build on the
card
title and make up the bulk
of the card's content.
</p>
</div>
</div>
<div class="card border-danger mb-3"
style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body text-danger">
<h4 class="card-title">Danger card title</h4>
<p class="card-text">Some quick example text to build on the
card
title and make up the bulk
of the card's content.
</p>
</div>
</div>
<div class="card border-warning mb-3"
style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body text-warning">
<h4 class="card-title">Warning card title</h4>
<p class="card-text">Some quick example text to build on the
card
title and make up the bulk
of the card's content.
</p>
</div>
</div>
<div class="card border-info mb-3"
style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body text-info">
<h4 class="card-title">Info card title</h4>
<p class="card-text">Some quick example text to build on the
card
title and make up the bulk
of the card's content.
</p>
</div>
</div>
<div class="card border-light mb-3"
style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body">
<h4 class="card-title">Light card title</h4>
<p class="card-text">Some quick example text to build on the
card
title and make up the bulk
of the card's content.
</p>
</div>
</div>
<div class="card border-dark mb-3"
style="max-width: 20rem;">
<div class="card-header">Header</div>
<div class="card-body text-dark">
<h4 class="card-title">Dark card title</h4>
<p class="card-text">Some quick example text to build on the
card
title and make up the bulk
of the card's content.
</p>
</div>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="bs-component">
<div class="card mb-3">
<h3 class="card-header">Card header</h3>
<div class="card-body">
<h5 class="card-title">Special title treatment</h5>
<h6 class="card-subtitle text-muted">Support card subtitle
</h6>
</div>
<img style="height: 200px; width: 100%; display: block;"
src="data:image/svg+xml;charset=UTF-8,%3Csvg%20width%3D%22318%22%20height%3D%22180%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20318%20180%22%20preserveAspectRatio%3D%22none%22%3E%3Cdefs%3E%3Cstyle%20type%3D%22text%2Fcss%22%3E%23holder_158bd1d28ef%20text%20%7B%20fill%3Argba(255%2C255%2C255%2C.75)%3Bfont-weight%3Anormal%3Bfont-family%3AHelvetica%2C%20monospace%3Bfont-size%3A16pt%20%7D%20%3C%2Fstyle%3E%3C%2Fdefs%3E%3Cg%20id%3D%22holder_158bd1d28ef%22%3E%3Crect%20width%3D%22318%22%20height%3D%22180%22%20fill%3D%22%23777%22%3E%3C%2Frect%3E%3Cg%3E%3Ctext%20x%3D%22129.359375%22%20y%3D%2297.35%22%3EImage%3C%2Ftext%3E%3C%2Fg%3E%3C%2Fg%3E%3C%2Fsvg%3E"
alt="Card image"
loading="lazy">
<div class="card-body">
<p class="card-text">Some quick example text to build on the
card
title and make up the bulk
of the card's content.
</p>
</div>
<ul class="list-group list-group-flush">
<li class="list-group-item">Cras justo odio</li>
<li class="list-group-item">Dapibus ac facilisis in</li>
<li class="list-group-item">Vestibulum at eros</li>
</ul>
<div class="card-body">
<a href="#"
class="card-link">Card link
</a>
<a href="#"
class="card-link">Another link
</a>
</div>
<div class="card-footer text-muted">
2 days ago
</div>
</div>
<div class="card">
<div class="card-body">
<h4 class="card-title">Card title</h4>
<h6 class="card-subtitle mb-2 text-muted">Card subtitle</h6>
<p class="card-text">Some quick example text to build on the
card
title and make up the bulk
of the card's content.
</p>
<a href="#"
class="card-link">Card link
</a>
<a href="#"
class="card-link">Another link
</a>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- Dialogs
================================================== -->
<div class="bs-docs-section">
<div class="row">
<div class="col-lg-12">
<div class="page-header">
<h1 id="dialogs">Dialogs</h1>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<h2>Modals</h2>
<div class="bs-component">
<div class="modal">
<div class="modal-dialog"
role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button"
class="close"
data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Modal body text goes here.</p>
</div>
<div class="modal-footer">
<button type="button"
class="btn btn-primary">Save changes
</button>
<button type="button"
class="btn btn-secondary"
data-dismiss="modal">Close
</button>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-lg-6">
<h2>Popovers</h2>
<div class="bs-component"
style="margin-bottom: 3em;">
<button type="button"
class="btn btn-secondary"
title="Popover Title"
data-container="body"
data-toggle="popover"
data-placement="left"
data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus.">
Left
</button>
<button type="button"
class="btn btn-secondary"
title="Popover Title"
data-container="body"
data-toggle="popover"
data-placement="top"
data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus.">
Top
</button>
<button type="button"
class="btn btn-secondary"
title="Popover Title"
data-container="body"
data-toggle="popover"
data-placement="bottom"
data-content="Vivamus
sagittis lacus vel augue laoreet rutrum faucibus.">Bottom
</button>
<button type="button"
class="btn btn-secondary"
title="Popover Title"
data-container="body"
data-toggle="popover"
data-placement="right"
data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus.">
Right
</button>
</div>
<h2>Tooltips</h2>
<div class="bs-component">
<button type="button"
class="btn btn-secondary"
data-toggle="tooltip"
data-placement="left"
title="Tooltip on left">Left
</button>
<button type="button"
class="btn btn-secondary"
data-toggle="tooltip"
data-placement="top"
title="Tooltip on top">Top
</button>
<button type="button"
class="btn btn-secondary"
data-toggle="tooltip"
data-placement="bottom"
title="Tooltip on bottom">Bottom
</button>
<button type="button"
class="btn btn-secondary"
data-toggle="tooltip"
data-placement="right"
title="Tooltip on right">Right
</button>
</div>
</div>
</div>
</div>
<!-- Imagens para trocar
================================================== -->
<div class="bs-docs-section">
<div class="row">
<div class="col-lg-12">
<div class="page-header">
<h1 id="dialogs">
<a href="https://realfavicongenerator.net/"
target="_blank">Images
</a>
</h1>
<div class="d-flex align-items-center mb-1">
<div class="bg-danger mr-0h"
style="width: 20px; height: 20px;"></div>
Missing <kbd class="ml-0h">alt=""</kbd>
</div>
<div class="d-flex align-items-center mb-2">
<div class="bg-warning mr-0h"
style="width: 20px; height: 20px"></div>
Missing <kbd class="ml-0h">loading=""</kbd>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-6">
<div class="p-3 mb-2 bg-light">
<figure class="figure mb-0">
<img src="/images/logo.png"
class="figure-img img-fluid"
alt="200x70 - logo.png (1,8 KB)"
loading="lazy"
width="200"
height="70">
<figcaption class="figure-caption">200x70 - logo.png (1,8 KB)
</figcaption>
</figure>
</div>
</div>
<div class="col-6">
<div class="p-3 mb-2 bg-light">
<figure class="figure mb-0">
<img src="/images/logo-email.png"
class="figure-img img-fluid"
alt="200x70 - logo-email.png (1,8 KB)"
loading="lazy"
width="200"
height="70">
<figcaption class="figure-caption">200x70 - logo-email.png (1,8
KB)
</figcaption>
</figure>
</div>
</div>
<div class="col-6">
<div class="p-3 mb-2 bg-light">
<figure class="figure mb-0">
<img src="/images/favicon.ico"
class="figure-img img-fluid"
alt="48x48 - favicon.ico (15,09 KB)"
loading="lazy"
width="48"
height="48">
<figcaption class="figure-caption">48x48 - favicon.ico (15,09
KB)
</figcaption>
</figure>
</div>
</div>
<div class="col-6">
<div class="p-3 mb-2 bg-light">
<figure class="figure mb-0">
<img src="/images/logo-amp.png"
class="figure-img img-fluid"
alt="60x60 - logo-amp.png (1 KB)"
loading="lazy"
width="60"
height="60">
<figcaption class="figure-caption">60x60 - logo-amp.png (1 KB)
</figcaption>
</figure>
</div>
</div>
<div class="col-12">
<div class="p-3 mb-2 bg-light">
<figure class="figure mb-0">
<img src="/images/mstile-150x150.png"
class="figure-img img-fluid"
alt="150x150 - mstile-150x150.png (1,7 KB)"
loading="lazy"
loading="lazy"
width="150"
height="150">
<figcaption class="figure-caption">150x150 - mstile-150x150.png
(1,7
KB)
</figcaption>
</figure>
</div>
</div>
<div class="col-6">
<div class="p-3 mb-2 bg-light">
<figure class="figure mb-0">
<img src="/images/safari-pinned-tab.svg"
class="figure-img img-fluid"
alt="192x192 - safari-pinned-tab.svg (5 KB)"
loading="lazy"
width="192"
height="192">
<figcaption class="figure-caption">192x192 -
safari-pinned-tab.svg
(5 KB)
</figcaption>
</figure>
</div>
</div>
<div class="col-6">
<div class="p-3 mb-2 bg-light">
<figure class="figure mb-0">
<img src="/images/apple-touch-icon.png"
class="figure-img img-fluid"
alt="192x192 - apple-touch-icon.png (3,51 KB)"
loading="lazy"
width="192"
height="192">
<figcaption class="figure-caption">192x192 -
apple-touch-icon.png
(3,51 KB)
</figcaption>
</figure>
</div>
</div>
<div class="col-12">
<div class="p-3 mb-2 bg-light">
<figure class="figure mb-0">
<img src="/images/icon-192x192.png"
class="figure-img img-fluid"
alt="192x192 - icon-192x192.png (5,28 KB)"
loading="lazy"
width="192"
height="192">
<figcaption class="figure-caption">192x192 - icon-192x192.png
(5,28
KB)
</figcaption>
</figure>
</div>
</div>
<div class="col-12">
<div class="p-3 mb-2 bg-light">
<figure class="figure mb-0">
<img src="/images/icon-512x512.png"
class="figure-img img-fluid"
alt="512x512 - icon-512x512.png (13,55 KB)"
loading="lazy"
width="512"
height="512">
<figcaption class="figure-caption">
512x512 - icon-512x512.png (13,55 KB)
</figcaption>
</figure>
</div>
</div>
</div>
</div>
<!--Inifinte Scroll Loading Icon-->
<h2>Ícone do Infinite Scroll</h2>
<div class="ic-infinite-scroll-loading"></div>
<div id="source-modal"
class="modal fade">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Source Code</h4>
<button type="button"
class="close"
data-dismiss="modal"
aria-hidden="true">×
</button>
</div>
<div class="modal-body">
<pre></pre>
</div>
</div>
</div>
</div>
<footer id="footer">
<div class="row">
<div class="col-lg-12">
<ul class="list-unstyled">
<li class="float-lg-right">
<a href="#top">Back to top</a>
</li>
<li>
<a href="http://blog.bootswatch.com"
onclick="pageTracker._link(this.href); return false;">Blog
</a>
</li>
<li>
<a href="https://feeds.feedburner.com/bootswatch">RSS</a>
</li>
<li>
<a href="https://twitter.com/bootswatch">Twitter</a>
</li>
<li>
<a href="https://github.com/thomaspark/bootswatch/">GitHub</a>
</li>
<li>
<a href="../help/#api">API</a>
</li>
<li>
<a href="../help/#donate">Donate</a>
</li>
</ul>
<p>Made by
<a href="http://thomaspark.co">Thomas Park</a>
.
</p>
<p>Code released under the
<a href="https://github.com/thomaspark/bootswatch/blob/master/LICENSE">
MIT
License
</a>
.
</p>
<p>Based on
<a href="https://getbootstrap.com"
rel="nofollow">Bootstrap
</a>
. Icons from
<a
href="http://fontawesome.io/"
rel="nofollow">Font Awesome
</a>
. Web fonts from
<a
href="https://fonts.google.com/"
rel="nofollow">Google
</a>
.
</p>
</div>
</div>
</footer>
</div>
<script src="/js/frontend.js"></script>
<script>
(function () {
var $button = $(
'<div id=\'source-button\' class=\'btn btn-primary\'>< ></div>')
.click(function () {
var html = $(this)
.parent()
.html();
html = cleanSource(html);
$('#source-modal pre')
.text(html);
$('#source-modal')
.modal();
});
$('.bs-component')
.hover(function () {
$(this)
.append($button);
$button.show();
}, function () {
$button.hide();
});
function cleanSource(html) {
html = html.replace(/×/g, '×')
.replace(/«/g, '«')
.replace(/»/g, '»')
.replace(/←/g, '←')
.replace(/→/g, '→');
var lines = html.split(/\n/);
lines.shift();
lines.splice(-1, 1);
var indentSize = lines[0].length - lines[0].trim().length,
re = new RegExp(' {' + indentSize + '}');
lines = lines.map(function (line) {
if (line.match(re)) {
line = line.substring(indentSize);
}
return line;
});
lines = lines.join('\n');
return lines;
}
})();
</script>
<script id="__bs_script__">//<![CDATA[
document.write(
'<script async src=\'//HOST:3000/browser-sync/browser-sync-client.js?v=2.18.6\'><\/script>'.replace(
'HOST',
location.hostname,
));
//]]>
</script>
</body>
</html>
| 43.38669 | 712 | 0.320298 |
551121fd8f8390c0a56e063cdd58eac1129244cf | 1,162 | swift | Swift | Test/YoutubeVideoConfigTest.swift | dklamma/edx-app-ios | 7ba6ab3234bcb88bef12e095732a662c4532ef81 | [
"Apache-2.0"
] | null | null | null | Test/YoutubeVideoConfigTest.swift | dklamma/edx-app-ios | 7ba6ab3234bcb88bef12e095732a662c4532ef81 | [
"Apache-2.0"
] | 1 | 2019-10-23T13:00:09.000Z | 2019-10-23T13:00:09.000Z | Test/YoutubeVideoConfigTest.swift | dklamma/edx-app-ios | 7ba6ab3234bcb88bef12e095732a662c4532ef81 | [
"Apache-2.0"
] | 1 | 2020-06-11T13:27:00.000Z | 2020-06-11T13:27:00.000Z | //
// YoutubeVideoConfigTests.swift
// edXTests
//
// Created by Andrey Canon on 4/12/19.
// Copyright © 2018 edX. All rights reserved.
//
import Foundation
@testable import edX
class YoutubeVideoConfigTests: XCTestCase {
func testNoYoutubeVideoConfig() {
let config = OEXConfig(dictionary:[:])
XCTAssertFalse(config.youtubeVideoConfig.enabled)
}
func testEmptyYoutubeVideoConfig() {
let config = OEXConfig(dictionary:["YOUTUBE_VIDEO":[:]])
XCTAssertFalse(config.youtubeVideoConfig.enabled)
}
func testYoutubeVideoConfig() {
let configDictionary = [
"YOUTUBE_VIDEO" : [
"ENABLED": true,
]
]
let config = OEXConfig(dictionary: configDictionary)
XCTAssertTrue(config.youtubeVideoConfig.enabled)
}
func testYoutubeVideoDisableConfig() {
let configDictionary = [
"YOUTUBE_VIDEO" : [
"ENABLED": false,
]
]
let config = OEXConfig(dictionary: configDictionary)
XCTAssertFalse(config.youtubeVideoConfig.enabled)
}
}
| 24.208333 | 64 | 0.609294 |
212c6d775514f7e402d36b67c8fb8da11e5d96d2 | 1,619 | rs | Rust | src/main.rs | Leafwing-Studios/bevy-momentum-platformer-template | 2c31d250314ded2546c5a764f9740227304c7e68 | [
"BlueOak-1.0.0"
] | null | null | null | src/main.rs | Leafwing-Studios/bevy-momentum-platformer-template | 2c31d250314ded2546c5a764f9740227304c7e68 | [
"BlueOak-1.0.0"
] | null | null | null | src/main.rs | Leafwing-Studios/bevy-momentum-platformer-template | 2c31d250314ded2546c5a764f9740227304c7e68 | [
"BlueOak-1.0.0"
] | null | null | null | #![allow(dead_code, unused_variables, unused_mut, unused_imports)]
use bevy::prelude::*;
use bevy::asset::LoadState;
mod physics;
mod player;
mod environment;
mod utils;
fn main() {
App::build()
.init_resource::<SpriteHandles>()
.add_plugins(DefaultPlugins)
.add_state(AssetLoadingState::Loading)
.add_system_set(SystemSet::on_enter(AssetLoadingState::Loading).with_system(load_textures.system()))
.add_system_set(SystemSet::on_update(AssetLoadingState::Loading).with_system(check_textures.system()))
.add_system_set(SystemSet::on_enter(AssetLoadingState::Finished).with_system(setup.system()))
.add_plugin(environment::EnvironmentPlugin)
.add_plugin(player::PlayerPlugin)
.add_plugin(physics::PhysicsPlugin)
.run();
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum AssetLoadingState {
Loading,
Finished,
}
#[derive(Default)]
struct SpriteHandles {
handles: Vec<Handle<ColorMaterial>>,
}
fn load_textures(mut sprite_handles: ResMut<SpriteHandles>, asset_server: Res<AssetServer>) {
sprite_handles.handles.push(asset_server.load("player.png"));
}
fn check_textures(
mut state: ResMut<State<AssetLoadingState>>,
sprite_handles: ResMut<SpriteHandles>,
asset_server: Res<AssetServer>,
) {
if let LoadState::Loaded =
asset_server.get_group_load_state(sprite_handles.handles.iter().map(|handle| handle.id))
{
state.set_next(AssetLoadingState::Finished).unwrap();
}
}
fn setup(
mut commands: Commands,
) {
commands
.spawn(OrthographicCameraBundle::new_2d())
.spawn(UiCameraBundle::default());
} | 28.403509 | 106 | 0.725757 |
81092afb6848f5612ea210bf4d8db8f25e7412ea | 2,217 | go | Go | modules/hepa/services/openapi_consumer/interface.go | harverywxu/erda | 521b773a73424f514756b7bfcb515c594003b19a | [
"Apache-2.0"
] | 2,402 | 2021-03-08T00:47:58.000Z | 2022-03-31T15:15:54.000Z | modules/hepa/services/openapi_consumer/interface.go | harverywxu/erda | 521b773a73424f514756b7bfcb515c594003b19a | [
"Apache-2.0"
] | 3,828 | 2021-03-15T03:33:16.000Z | 2022-03-31T10:51:30.000Z | modules/hepa/services/openapi_consumer/interface.go | harverywxu/erda | 521b773a73424f514756b7bfcb515c594003b19a | [
"Apache-2.0"
] | 315 | 2021-03-05T09:53:24.000Z | 2022-03-31T09:48:35.000Z | // Copyright (c) 2021 Terminus, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package openapi_consumer
import (
"context"
"github.com/erda-project/erda/modules/hepa/common"
"github.com/erda-project/erda/modules/hepa/gateway/dto"
"github.com/erda-project/erda/modules/hepa/repository/orm"
)
var Service GatewayOpenapiConsumerService
type GatewayOpenapiConsumerService interface {
Clone(context.Context) GatewayOpenapiConsumerService
GrantPackageToConsumer(consumerId, packageId string) error
RevokePackageFromConsumer(consumerId, packageId string) error
CreateClientConsumer(clientName, clientId, clientSecret, clusterName string) (*orm.GatewayConsumer, error)
CreateConsumer(*dto.DiceArgsDto, *dto.OpenConsumerDto) (string, bool, error)
GetConsumers(*dto.GetOpenConsumersDto) (common.NewPageQuery, error)
GetConsumersName(*dto.GetOpenConsumersDto) ([]dto.OpenConsumerInfoDto, error)
UpdateConsumer(string, *dto.OpenConsumerDto) (*dto.OpenConsumerInfoDto, error)
DeleteConsumer(string) (bool, error)
GetConsumerCredentials(string) (dto.ConsumerCredentialsDto, error)
UpdateConsumerCredentials(string, *dto.ConsumerCredentialsDto) (dto.ConsumerCredentialsDto, string, error)
GetConsumerAcls(string) ([]dto.ConsumerAclInfoDto, error)
UpdateConsumerAcls(string, *dto.ConsumerAclsDto) (bool, error)
GetConsumersOfPackage(string) ([]orm.GatewayConsumer, error)
GetKongConsumerName(consumer *orm.GatewayConsumer) string
GetPackageAcls(string) ([]dto.PackageAclInfoDto, error)
UpdatePackageAcls(string, *dto.PackageAclsDto) (bool, error)
GetPackageApiAcls(string, string) ([]dto.PackageAclInfoDto, error)
UpdatePackageApiAcls(string, string, *dto.PackageAclsDto) (bool, error)
}
| 46.1875 | 107 | 0.797925 |
f7051a9a7ac60990c60cbdf064c2b2d7d79b8b23 | 2,032 | h | C | HF5R0x_0.1.0/src/hexabitz/BOS.h | HexabitzPlatform/HF5R0x-Firmware | c00c708c327a9de4d5bd8652e1087599a4b39177 | [
"MIT"
] | null | null | null | HF5R0x_0.1.0/src/hexabitz/BOS.h | HexabitzPlatform/HF5R0x-Firmware | c00c708c327a9de4d5bd8652e1087599a4b39177 | [
"MIT"
] | null | null | null | HF5R0x_0.1.0/src/hexabitz/BOS.h | HexabitzPlatform/HF5R0x-Firmware | c00c708c327a9de4d5bd8652e1087599a4b39177 | [
"MIT"
] | null | null | null | /*
BitzOS (BOS) V0.2.3 - Copyright (C) 2017-2020 Hexabitz
All rights reserved
File Name : BOS.h
Description : Header file for Bitz Operating System (BOS).
*/
/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef BOS_H
#define BOS_H
/* Includes ------------------------------------------------------------------*/
/* C STD Libraries */
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
#include <unistd.h>
#include <thread>
#include <chrono>
#include <ctype.h>
#include <tgmath.h>
#include <cstring>
#include <fcntl.h>
#include <termios.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <iostream>
/*Nvidia Libraries */
#include "serial.h"
/*Hexabitz Libraries */
#include "MessageCode.h"
#include "BOS_Message.h"
#include "BOS_Porting.h"
/* Firmware version */
#define _firmMajor 0
#define _firmMinor 2
#define _firmPatch 3
#define BOS_RESPONSE_ALL 0x60 // Send response messages for both Messaging and CLI
#define BOS_RESPONSE_MSG 0x20 // Send response messages for Messaging only (no CLI)
#define BOS_RESPONSE_CLI 0x40 // Send response messages for CLI only (no messages)
#define BOS_RESPONSE_NONE 0x00 // Do not send any response messages
typedef enum { TRACE_NONE = 0, TRACE_MESSAGE, TRACE_RESPONSE, TRACE_BOTH } traceOptions_t;
/* BOS Struct Type Definition */
typedef struct
{
uint8_t response;
traceOptions_t trace;
}
BOS_t;
/* BOS_Status Type Definition */
typedef enum
{ BOS_OK = 0,
BOS_ERR_UnknownMessage = 1,
BOS_ERR_NoResponse = 2,
BOS_MULTICAST = 254,
BOS_BROADCAST = 255,
} BOS_Status;
/* Exported internal functions ---------------------------------------------------------*/
extern void init(void);
extern void delay_s(uint8_t duration);
extern BOS_t BOS;
#endif /* BOS_H */
/************************ (C) COPYRIGHT HEXABITZ *****END OF FILE****/
| 23.905882 | 91 | 0.632874 |
d25f2a9efe2abb4f83d46090cafee77904bf3482 | 3,929 | php | PHP | application/views/admin/ekskul.php | yayanrw/siekskul | b551ee37d9fed19ebd19712ae1fb1cc2e3b8fe5d | [
"MIT"
] | null | null | null | application/views/admin/ekskul.php | yayanrw/siekskul | b551ee37d9fed19ebd19712ae1fb1cc2e3b8fe5d | [
"MIT"
] | null | null | null | application/views/admin/ekskul.php | yayanrw/siekskul | b551ee37d9fed19ebd19712ae1fb1cc2e3b8fe5d | [
"MIT"
] | null | null | null | <html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo $title_page; ?></title>
<!-- CSS -->
<?php $this->load->view('assets/css'); ?>
<?php $this->load->view('assets/css_datatable'); ?>
<!-- End CSS -->
</head>
<body>
<!-- Navbar -->
<?php $this->load->view('menu/view_navbar'); ?>
<!-- End Navbar -->
<!-- Sidebar -->
<?php $this->load->view('menu/view_sidebar'); ?>
<!-- End Sidebar -->
<div class="col-sm-9 col-sm-offset-3 col-lg-10 col-lg-offset-2 main">
<!-- Breadcrumb -->
<?php $this->load->view('menu/view_breadcrumb'); ?>
<!-- End Breadcrumb -->
<!--Alert-->
<?php $this->load->view('menu/view_alert');?>
<!--EndAlert-->
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="panel panel-info">
<div class="panel-heading"><i class="fa fa-user"></i> <?= $title ?></div>
<div class="panel-body">
<table id="datatable" class="table table-striped table-hover">
<thead>
<tr>
<th>#</th>
<th>Ekskul</th>
<th>Pengaju</th>
<th>Periode</th>
<th>Status</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
<?php $i=1;
foreach ($ekskul as $key) { ?>
<tr>
<td><?= $i++; ?></td>
<td><?= $key->nama ?></td>
<td><?= $key->username ?></td>
<td><?= $key->periode ?></td>
<td>
<?php if($key->status == 'Disetujui') {?>
<span class="label label-success"><?= $key->status ?></span>
<?php } ?>
<?php if($key->status == 'Ditolak') {?>
<span class="label label-danger"><?= $key->status ?></span>
<?php } ?>
<?php if($key->status == 'Menunggu') {?>
<span class="label label-warning"><?= $key->status ?></span>
<?php } ?>
</td>
<td>
<?php if($key->status == 'Menunggu') {?>
<a href="<?= base_url('ekskul/setuju/'.$key->id_ekskul); ?>" class="btn btn-xs btn-success"><i class="fa fa-check"></i> Setujui</a>
<a href="<?= base_url('ekskul/tolak/'.$key->id_ekskul); ?>" class="btn btn-xs btn-danger"><i class="fa fa-times"></i> Tolak</a>
<a href="<?= base_url('ekskul/show/'.$key->id_ekskul); ?>" class="btn btn-xs btn-primary"><i class="fa fa-eye"></i> Lihat</a>
<?php } ?>
<?php if($key->status == 'Disetujui') {?>
<a href="<?= base_url('ekskul/show/'.$key->id_ekskul); ?>" class="btn btn-xs btn-primary"><i class="fa fa-eye"></i> Lihat</a>
<?php } ?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
</div> <!--/.main-->
<!-- JS -->
<?php $this->load->view('assets/js'); ?>
<?php $this->load->view('assets/js_datatable'); ?>
<script>
$("#notif").fadeTo(2000, 500).slideUp(500, function(){
$("#notif").slideUp(500);
});
</script>
<!-- End JS -->
</body>
</html>
| 37.778846 | 163 | 0.372105 |
0c2bfd8d747cac76672a232be6a7f55d685fb374 | 150 | sql | SQL | sql/create_books_db.sql | vvydier/ClaimAcademy | a4666bb4498d741e03f64bc7cda0f508b26c2d37 | [
"MIT"
] | null | null | null | sql/create_books_db.sql | vvydier/ClaimAcademy | a4666bb4498d741e03f64bc7cda0f508b26c2d37 | [
"MIT"
] | null | null | null | sql/create_books_db.sql | vvydier/ClaimAcademy | a4666bb4498d741e03f64bc7cda0f508b26c2d37 | [
"MIT"
] | 1 | 2016-03-08T23:16:44.000Z | 2016-03-08T23:16:44.000Z | mysql -uusername -h 127.0.0.1 -ppassword
mysql>DROP DATABASE `books`;
mysql>create database books;
mysql>use books;
mysql>show tables;
| 13.636364 | 41 | 0.693333 |
fbb071842d5c8de5270f03ccb024a1d3d4bda4e8 | 722 | java | Java | gmall-scheduled/src/main/java/com/atguigu/gmall/scheduled/juc/ScheduleDemo.java | zhifei-BF/guli-0211 | 61fd91de7571a06d80624ff9d492d142287a14c1 | [
"Apache-2.0"
] | null | null | null | gmall-scheduled/src/main/java/com/atguigu/gmall/scheduled/juc/ScheduleDemo.java | zhifei-BF/guli-0211 | 61fd91de7571a06d80624ff9d492d142287a14c1 | [
"Apache-2.0"
] | 3 | 2021-03-19T20:25:01.000Z | 2021-09-20T21:00:52.000Z | gmall-scheduled/src/main/java/com/atguigu/gmall/scheduled/juc/ScheduleDemo.java | zhifei-BF/gmall-0211 | 61fd91de7571a06d80624ff9d492d142287a14c1 | [
"Apache-2.0"
] | null | null | null | package com.atguigu.gmall.scheduled.juc;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ScheduleDemo {
public static void main(String[] args) {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(3);
System.out.println("任务启动时间:" + System.currentTimeMillis());
// executorService.schedule(()->{
// System.out.println("这是一个定时任务。" + System.currentTimeMillis());
// }, 10, TimeUnit.SECONDS);
executorService.scheduleAtFixedRate(()->{
System.out.println("这是一个定时任务。" + System.currentTimeMillis());
},5,10,TimeUnit.SECONDS);
}
}
| 38 | 87 | 0.695291 |
82ccc0411bf9edc4459846d7f48d7a9fd6e42dda | 9,526 | kt | Kotlin | src/test/kotlin/br/com/zupedu/pix/endpoints/RetrievePixServiceGrpcEndpointTest.kt | olucasokarin/orange-talents-05-template-pix-keymanager-grpc | 7832099ab206788de2c5ed04a69d1952e4c9201d | [
"Apache-2.0"
] | null | null | null | src/test/kotlin/br/com/zupedu/pix/endpoints/RetrievePixServiceGrpcEndpointTest.kt | olucasokarin/orange-talents-05-template-pix-keymanager-grpc | 7832099ab206788de2c5ed04a69d1952e4c9201d | [
"Apache-2.0"
] | null | null | null | src/test/kotlin/br/com/zupedu/pix/endpoints/RetrievePixServiceGrpcEndpointTest.kt | olucasokarin/orange-talents-05-template-pix-keymanager-grpc | 7832099ab206788de2c5ed04a69d1952e4c9201d | [
"Apache-2.0"
] | null | null | null | package br.com.zupedu.pix.endpoints
import br.com.zupedu.grpc.RetrievePixRequest
import br.com.zupedu.grpc.RetrievePixServiceGrpc
import br.com.zupedu.pix.externalConnections.bcb.ClientBcb
import br.com.zupedu.pix.externalConnections.bcb.requests.*
import br.com.zupedu.pix.model.Institution
import br.com.zupedu.pix.model.KeyPix
import br.com.zupedu.pix.model.Owner
import br.com.zupedu.pix.model.enums.TypeAccount
import br.com.zupedu.pix.model.enums.TypeKey
import br.com.zupedu.pix.repository.PixRepository
import io.grpc.ManagedChannel
import io.grpc.Status
import io.grpc.StatusRuntimeException
import io.micronaut.context.annotation.Bean
import io.micronaut.context.annotation.Factory
import io.micronaut.grpc.annotation.GrpcChannel
import io.micronaut.grpc.server.GrpcServerChannel
import io.micronaut.http.HttpResponse
import io.micronaut.test.annotation.MockBean
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.mockito.Mockito
import org.mockito.Mockito.`when`
import java.util.*
import javax.inject.Inject
@MicronautTest(transactional = false)
internal class RetrievePixServiceGrpcEndpointTest(
@Inject private val pixRepository: PixRepository,
@Inject private val retrieveGrpcClient: RetrievePixServiceGrpc.RetrievePixServiceBlockingStub
) {
@Inject
private lateinit var clientBcb: ClientBcb
companion object {
private val CLIENT_ID = UUID.randomUUID()
}
@BeforeEach
internal fun setUp() {
pixRepository.deleteAll()
}
//internal access
@Test
fun`should be retrieved a pix key from internal access`() {
//scenario
val savedPix = pixRepository.save(createNewKey())
`when`(clientBcb.retrieveKey(key = savedPix.valueKey))
.thenReturn(HttpResponse.ok())
//actions
val retrieveResponse = retrieveGrpcClient.retrieve(retrieveInternalAccessGrpcRequest(savedPix))
//assertions
with(retrieveResponse) {
assertEquals(savedPix.externalId.toString(), idPix)
assertEquals(savedPix.idClient.toString(), idClient)
assertEquals(savedPix.valueKey, valueKey)
assertEquals(savedPix.typeKey.name, typeKey.name)
assertEquals(savedPix.typeAccount.name, institution.typeAccount.name)
}
}
@Test
fun`should not be retrieved when not found in bd from internal access`() {
//actions
val assertThrows = assertThrows<StatusRuntimeException> {
retrieveGrpcClient.retrieve(
RetrievePixRequest.newBuilder()
.setIdPix(
RetrievePixRequest.MessageInternal.newBuilder()
.setIdPix(UUID.randomUUID().toString())
.setIdClient(UUID.randomUUID().toString())
.build()
)
.build()
)
}
//assertions
with(assertThrows) {
assertEquals(Status.NOT_FOUND.code, status.code)
assertEquals("Pix not found", status.description)
}
}
@Test
fun`should not be retrieved when not found on system BCB from internal access`() {
//scenario
val savedPix = pixRepository.save(createNewKey())
`when`(clientBcb.retrieveKey(savedPix.valueKey))
.thenReturn(HttpResponse.notFound())
//actions
val assertThrows = assertThrows<StatusRuntimeException> {
retrieveGrpcClient.retrieve(
RetrievePixRequest.newBuilder()
.setIdPix(
RetrievePixRequest.MessageInternal.newBuilder()
.setIdPix(savedPix.externalId.toString())
.setIdClient(savedPix.idClient.toString())
.build()
)
.build()
)
}
//assertions
with(assertThrows) {
assertEquals(Status.NOT_FOUND.code, status.code)
assertEquals("Pix not found on BCB", status.description)
}
}
// External Access
@Test
fun`should be retrieved a pix key from external access`() {
//scenario
val savedPix = pixRepository.save(createNewKey())
`when`(clientBcb.retrieveKey(key = savedPix.valueKey))
.thenReturn(HttpResponse.ok())
//actions
val retrieveResponse = retrieveGrpcClient.retrieve(retrieveExternalAccessGrpcRequest(savedPix))
//assertions
with(retrieveResponse) {
assertEquals("", "")
assertEquals("", "")
assertEquals(savedPix.valueKey, valueKey)
assertEquals(savedPix.typeKey.name, typeKey.name)
assertEquals(savedPix.typeAccount.name, institution.typeAccount.name)
}
}
@Test
fun`should not be retrieved when not found in bd from external access`() {
//scenario
`when`(clientBcb.retrieveKey("any_data"))
.thenReturn(HttpResponse.ok())
//actions
val assertThrows = assertThrows<StatusRuntimeException> {
retrieveGrpcClient.retrieve(
RetrievePixRequest.newBuilder()
.setValuePix("any_data")
.build()
)
}
//assertions
with(assertThrows) {
assertEquals(Status.NOT_FOUND.code, status.code)
assertEquals("Pix not found", status.description)
}
}
@Test
fun`should not be retrieved when not found on system BCB from external access`() {
//scenario
val savedPix = pixRepository.save(createNewKey())
`when`(clientBcb.retrieveKey(savedPix.valueKey))
.thenReturn(HttpResponse.notFound())
//actions
val assertThrows = assertThrows<StatusRuntimeException> {
retrieveGrpcClient.retrieve(
RetrievePixRequest.newBuilder()
.setValuePix(savedPix.valueKey)
.build()
)
}
//assertions
with(assertThrows) {
assertEquals(Status.NOT_FOUND.code, status.code)
assertEquals("Pix not found", status.description)
}
}
// outer tests
@Test
fun`should not be retrieved when not passed any data`() {
//actions
val assertThrows = assertThrows<StatusRuntimeException> {
retrieveGrpcClient.retrieve(RetrievePixRequest.newBuilder().build())
}
//assertions
with(assertThrows) {
assertEquals(Status.INVALID_ARGUMENT.code, status.code)
assertEquals("Invalid data informed", status.description)
}
}
@Test
fun`should not be retrieved when passed some invalid data`() {
//actions
val assertThrows = assertThrows<StatusRuntimeException> {
retrieveGrpcClient.retrieve(RetrievePixRequest.newBuilder().setValuePix("").build())
}
//assertions
with(assertThrows) {
assertEquals(Status.INVALID_ARGUMENT.code, status.code)
assertEquals("Invalid Data", status.description)
}
}
private fun retrieveInternalAccessGrpcRequest(savedPix: KeyPix): RetrievePixRequest? {
return RetrievePixRequest.newBuilder()
.setIdPix(RetrievePixRequest.MessageInternal.newBuilder()
.setIdPix(savedPix.externalId.toString())
.setIdClient(savedPix.idClient.toString())
.build())
.build()
}
private fun retrieveExternalAccessGrpcRequest(savedPix: KeyPix): RetrievePixRequest? {
return RetrievePixRequest.newBuilder()
.setValuePix(savedPix.valueKey)
.build()
}
private fun createNewKey() =
KeyPix(
idClient = CLIENT_ID,
typeKey = TypeKey.EMAIL,
valueKey = "already_key@email.com",
typeAccount = TypeAccount.CHECKING_ACCOUNT,
branch = "0001",
accountNumber = "048967",
institution = Institution(
nome = "My Bank",
ispb = "60701190"
),
owner = Owner(
nome = "John Doe",
cpf = "43951423030"
)
)
private fun createPixBcbRequest(): CreatePixKeyRequest {
val keyPix = createNewKey()
return CreatePixKeyRequest(
keyType = KeyTypeBCB.by(keyPix.typeKey),
key = keyPix.valueKey,
bankAccount = BankAccountRequest(
participant = keyPix.institution.ispb,
branch = keyPix.branch,
accountNumber = keyPix.accountNumber,
accountType = AccountType.by(keyPix.typeAccount)
),
owner = OwnerRequest(
type = OwnerType.NATURAL_PERSON,
name = keyPix.owner.nome,
taxIdNumber = keyPix.owner.cpf
)
)
}
@Factory
class Clients {
@Bean
fun retrieveBlockingStub(@GrpcChannel(GrpcServerChannel.NAME) channel: ManagedChannel) =
RetrievePixServiceGrpc.newBlockingStub(channel)
}
@MockBean(ClientBcb::class)
fun clientBcb() =
Mockito.mock(ClientBcb::class.java)
}
| 32.848276 | 103 | 0.618623 |
dde172061cdf5f72188cef6f4fe3787ad3278413 | 3,107 | php | PHP | ext_localconf.php | juergenfurrer/newt-typo3-ext | be40339f72f2b0ff565bbe08871e6cceb981b5f4 | [
"MIT"
] | null | null | null | ext_localconf.php | juergenfurrer/newt-typo3-ext | be40339f72f2b0ff565bbe08871e6cceb981b5f4 | [
"MIT"
] | 1 | 2022-03-08T07:53:56.000Z | 2022-03-10T06:45:01.000Z | ext_localconf.php | juergenfurrer/newt-typo3-ext | be40339f72f2b0ff565bbe08871e6cceb981b5f4 | [
"MIT"
] | 1 | 2022-03-08T07:08:35.000Z | 2022-03-08T07:08:35.000Z | <?php
defined('TYPO3') || die();
call_user_func(
function ($extKey) {
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
'Newt',
'Api',
[\Infonique\Newt\Controller\ApiController::class => 'endpoints, create, read, update, delete, list'],
[\Infonique\Newt\Controller\ApiController::class => 'endpoints, create, read, update, delete, list']
);
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
'Newt',
'Serverconfig',
[\Infonique\Newt\Controller\EndpointController::class => 'index, tokenRefresh'],
[\Infonique\Newt\Controller\EndpointController::class => 'index, tokenRefresh']
);
// wizards
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addPageTSConfig(
'mod {
wizards.newContentElement.wizardItems.plugins {
elements {
serverconfig {
iconIdentifier = newt-plugin-serverconfig
title = LLL:EXT:newt/Resources/Private/Language/locallang_db.xlf:tx_newt_serverconfig.name
description = LLL:EXT:newt/Resources/Private/Language/locallang_db.xlf:tx_newt_serverconfig.description
tt_content_defValues {
CType = list
list_type = newt_serverconfig
}
}
}
show = *
}
}'
);
// Nodes
$GLOBALS['TYPO3_CONF_VARS']['SYS']['formEngine']['nodeRegistry']['1647092550'] = [
'nodeName' => 'NewtEndpointHintElement',
'priority' => 40,
'class' => \Infonique\Newt\Form\Element\NewtEndpointHintElement::class,
];
$GLOBALS['TYPO3_CONF_VARS']['SYS']['formEngine']['nodeRegistry']['1649659670'] = [
'nodeName' => 'NewtEndpointOptionsHintElement',
'priority' => 40,
'class' => \Infonique\Newt\Form\Element\NewtEndpointOptionsHintElement::class,
];
// Tasks
$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['scheduler']['tasks'][\Infonique\Newt\Task\SendNotificationTask::class] = array(
'extension' => $extKey,
'title' => 'LLL:EXT:newt/Resources/Private/Language/locallang_db.xlf:tx_scheduler.send_notification_task.name',
'description' => 'LLL:EXT:newt/Resources/Private/Language/locallang_db.xlf:tx_scheduler.send_notification_task.description'
);
/** @var \TYPO3\CMS\Core\Imaging\IconRegistry */
$iconRegistry = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Imaging\IconRegistry::class);
$iconRegistry->registerIcon(
'newt-plugin-serverconfig',
\TYPO3\CMS\Core\Imaging\IconProvider\SvgIconProvider::class,
['source' => 'EXT:newt/Resources/Public/Icons/user_plugin_serverconfig.svg']
);
},
$_EXTKEY ?? 'newt'
);
| 45.028986 | 135 | 0.573865 |
9164fe459b2e1cfa773f25be1f26fc0060a12b63 | 14,511 | html | HTML | docs/man/master/man1/localedef.1.html | Z5T1/fidelix.github.io | 24b1cbe95a72d0de5cebfa21e314bed28675a48d | [
"MIT"
] | null | null | null | docs/man/master/man1/localedef.1.html | Z5T1/fidelix.github.io | 24b1cbe95a72d0de5cebfa21e314bed28675a48d | [
"MIT"
] | null | null | null | docs/man/master/man1/localedef.1.html | Z5T1/fidelix.github.io | 24b1cbe95a72d0de5cebfa21e314bed28675a48d | [
"MIT"
] | null | null | null |
<!DOCTYPE HTML>
<head>
<title>/usr/share/man/man1/localedef.1</title> <link rel='stylesheet' href='/mandoc.css' />
<link rel='stylesheet' href='/style.css' />
</head>
<body>
<div class=contents>
<div class=header>
<h1>The Fidelix Linux Distribution</h1>
<h2>Simple, Stable, and Secure</h2>
</div>
<div class=menubar>
<ul>
<li><a href=/>News</a></li>
<li><a href=/about.html>About</a></li>
<div class=dropdown>
<li><a href=/download>Download</a></li>
<ul class=dropdown-content>
<li><a href=/download/>Latest Downloads</a></li>
<li><a href=/download/all.html>All Downloads</a></li>
</ul>
</div>
<div class=dropdown>
<li><a href=#>Documentation</a></li>
<ul class=dropdown-content>
<li><a href=https://github.com/fidelix-project/fidelix/blob/master/doc/README.md>Handbook</a></li>
<li><a href=/man/>Manual Pages</a></li>
</ul>
</div>
<div class=dropdown>
<li><a href=#>Development</a></li>
<ul class=dropdown-content>
<li><a href=https://github.com/fidelix-project>GitHub</a></li>
</ul>
</div>
<div class=dropdown>
<li><a href=#>Community</a></li>
<ul class=dropdown-content>
<li><a href=https://discord.com/invite/Yz8DeUr>Discord</a></li>
<li><a href=/get-involved.html>Get Involved</a></li>
<li><a href=/contact.html>Contact Us</a></li>
</ul>
</div>
</ul>
</div>
<div class=body><table class="head">
<tr>
<td class="head-ltitle">LOCALEDEF(1)</td>
<td class="head-vol">Linux User Manual</td>
<td class="head-rtitle">LOCALEDEF(1)</td>
</tr>
</table>
<div class="manual-text">
<section class="Sh">
<h1 class="Sh" id="NAME"><a class="permalink" href="#NAME">NAME</a></h1>
localedef - compile locale definition files
</section>
<section class="Sh">
<h1 class="Sh" id="SYNOPSIS"><a class="permalink" href="#SYNOPSIS">SYNOPSIS</a></h1>
<b>localedef</b> [<i>options</i>] <i>outputpath</i>
<br/>
<b>localedef --add-to-archive</b> [<i>options</i>] <i>compiledpath</i>
<br/>
<b>localedef --delete-from-archive</b> [<i>options</i>] <i>localename</i> ...
<br/>
<b>localedef --list-archive</b> [<i>options</i>]
<br/>
<b>localedef --help</b>
<br/>
<b>localedef --usage</b>
<br/>
<b>localedef --version</b>
</section>
<section class="Sh">
<h1 class="Sh" id="DESCRIPTION"><a class="permalink" href="#DESCRIPTION">DESCRIPTION</a></h1>
The <b>localedef</b> program reads the indicated <i>charmap</i> and <i>input</i>
files, compiles them to a binary form quickly usable by the locale functions
in the C library (<b>setlocale</b>(3), <b>localeconv</b>(3), etc.), and places
the output in <i>outputpath</i>.
<p class="Pp">The <i>outputpath</i> argument is interpreted as follows:</p>
<ul class="Bl-bullet">
<li>If <i>outputpath</i> contains a slash character ('/'), it is interpreted
as the name of the directory where the output definitions are to be
stored. In this case, there is a separate output file for each locale
category (<i>LC_TIME</i>, <i>LC_NUMERIC</i>, and so on).</li>
<li>If the <b>--no-archive</b> option is used, <i>outputpath</i> is the name
of a subdirectory in <i>/usr/lib/locale</i> where per-category compiled
files are placed.</li>
<li>Otherwise, <i>outputpath</i> is the name of a locale and the compiled
locale data is added to the archive file
<i>/usr/lib/locale/locale-archive</i>. A locale archive is a memory-mapped
file which contains all the system-provided locales; it is used by all
localized programs when the environment variable <b>LOCPATH</b> is not
set.</li>
</ul>
<p class="Pp">In any case, <b>localedef</b> aborts if the directory in which it
tries to write locale files has not already been created.</p>
<p class="Pp">If no <i>charmapfile</i> is given, the value <i>ANSI_X3.4-1968</i>
(for ASCII) is used by default. If no <i>inputfile</i> is given, or if it is
given as a dash (-), <b>localedef</b> reads from standard input.</p>
</section>
<section class="Sh">
<h1 class="Sh" id="OPTIONS"><a class="permalink" href="#OPTIONS">OPTIONS</a></h1>
<section class="Ss">
<h2 class="Ss" id="Operation-selection_options"><a class="permalink" href="#Operation-selection_options">Operation-selection
options</a></h2>
A few options direct <b>localedef</b> to do something other than compile locale
definitions. Only one of these options should be used at a time.
<dl class="Bl-tag">
<dt><b>--add-to-archive</b></dt>
<dd>Add the <i>compiledpath</i> directories to the locale archive file. The
directories should have been created by previous runs of <b>localedef</b>,
using <b>--no-archive</b>.</dd>
<dt><b>--delete-from-archive</b></dt>
<dd>Delete the named locales from the locale archive file.</dd>
<dt><b>--list-archive</b></dt>
<dd>List the locales contained in the locale archive file.</dd>
</dl>
</section>
<section class="Ss">
<h2 class="Ss" id="Other_options"><a class="permalink" href="#Other_options">Other
options</a></h2>
Some of the following options are sensible only for certain operations;
generally, it should be self-evident which ones. Notice that <b>-f</b> and
<b>-c</b> are reversed from what you might expect; that is, <b>-f</b> is not
the same as <b>--force</b>.
<dl class="Bl-tag">
<dt><b>-f</b><i> charmapfile</i><b>, --charmap=</b><i>charmapfile</i></dt>
<dd>Specify the file that defines the character set that is used by the input
file. If <i>charmapfile</i> contains a slash character ('/'), it is
interpreted as the name of the character map. Otherwise, the file is
sought in the current directory and the default directory for character
maps. If the environment variable <b>I18NPATH</b> is set,
<i>$I18NPATH/charmaps/</i> and <i>$I18NPATH/</i> are also searched after
the current directory. The default directory for character maps is printed
by <b>localedef --help</b>.</dd>
<dt><b>-i</b><i> inputfile</i><b>, --inputfile=</b><i>inputfile</i></dt>
<dd>Specify the locale definition file to compile. The file is sought in the
current directory and the default directory for locale definition files.
If the environment variable <b>I18NPATH</b> is set,
<i>$I18NPATH/locales/</i> and <i>$I18NPATH</i> are also searched after the
current directory. The default directory for locale definition files is
printed by <b>localedef --help</b>.</dd>
<dt><b>-u</b><i> repertoirefile</i><b>,
--repertoire-map=</b><i>repertoirefile</i></dt>
<dd>Read mappings from symbolic names to Unicode code points from
<i>repertoirefile</i>. If <i>repertoirefile</i> contains a slash character
('/'), it is interpreted as the pathname of the repertoire map. Otherwise,
the file is sought in the current directory and the default directory for
repertoire maps. If the environment variable <b>I18NPATH</b> is set,
<i>$I18NPATH/repertoiremaps/</i> and <i>$I18NPATH</i> are also searched
after the current directory. The default directory for repertoire maps is
printed by <b>localedef --help</b>.</dd>
<dt><b>-A</b><i> aliasfile</i><b>, --alias-file=</b><i>aliasfile</i></dt>
<dd>Use <i>aliasfile</i> to look up aliases for locale names. There is no
default aliases file.</dd>
<dt><b>-c</b>, <b>--force</b></dt>
<dd>Write the output files even if warnings were generated about the input
file.</dd>
<dt><b>-v</b>, <b>--verbose</b></dt>
<dd>Generate extra warnings about errors that are normally ignored.</dd>
<dt><b>--big-endian</b></dt>
<dd>Generate big-ending output.</dd>
<dt><b>--little-endian</b></dt>
<dd>Generate little-ending output.</dd>
<dt><b>--no-archive</b></dt>
<dd>Do not use the locale archive file, instead create <i>outputpath</i> as a
subdirectory in the same directory as the locale archive file, and create
separate output files for locale categories in it. This is helpful to
prevent system locale archive updates from overwriting custom locales
created with <b>localedef</b>.</dd>
<dt><b>--no-hard-links</b></dt>
<dd>Do not create hard links between installed locales.</dd>
<dt><b>--no-warnings=</b><i>warnings</i></dt>
<dd>Comma-separated list of warnings to disable. Supported warnings are
<i>ascii</i> and <i>intcurrsym</i>.</dd>
<dt><b>--posix</b></dt>
<dd>Conform strictly to POSIX. Implies <b>--verbose</b>. This option currently
has no other effect. POSIX conformance is assumed if the environment
variable <b>POSIXLY_CORRECT</b> is set.</dd>
<dt><b>--prefix=</b><i>pathname</i></dt>
<dd>Set the prefix to be prepended to the full archive pathname. By default,
the prefix is empty. Setting the prefix to <i>foo</i>, the archive would
be placed in <i>foo/usr/lib/locale/locale-archive</i>.</dd>
<dt><b>--quiet</b></dt>
<dd>Suppress all notifications and warnings, and report only fatal
errors.</dd>
<dt><b>--replace</b></dt>
<dd>Replace a locale in the locale archive file. Without this option, if the
locale is in the archive file already, an error occurs.</dd>
<dt><b>--warnings=</b><i>warnings</i></dt>
<dd>Comma-separated list of warnings to enable. Supported warnings are
<i>ascii</i> and <i>intcurrsym</i>.</dd>
<dt><b>-?</b>, <b>--help</b></dt>
<dd>Print a usage summary and exit. Also prints the default paths used by
<b>localedef</b>.</dd>
<dt><b>--usage</b></dt>
<dd>Print a short usage summary and exit.</dd>
<dt><b>-V</b>, <b>--version</b></dt>
<dd>Print the version number, license, and disclaimer of warranty for
<b>localedef</b>.</dd>
</dl>
</section>
</section>
<section class="Sh">
<h1 class="Sh" id="EXIT_STATUS"><a class="permalink" href="#EXIT_STATUS">EXIT
STATUS</a></h1>
One of the following exit values can be returned by <b>localedef</b>:
<div class="Bd-indent">
<dl class="Bl-tag">
<dt><b>0</b></dt>
<dd>Command completed successfully.</dd>
<dt><b>1</b></dt>
<dd>Warnings or errors occurred, output files were written.</dd>
<dt><b>4</b></dt>
<dd>Errors encountered, no output created.</dd>
</dl>
</div>
</section>
<section class="Sh">
<h1 class="Sh" id="ENVIRONMENT"><a class="permalink" href="#ENVIRONMENT">ENVIRONMENT</a></h1>
<dl class="Bl-tag">
<dt><b>POSIXLY_CORRECT</b></dt>
<dd>The <b>--posix</b> flag is assumed if this environment variable is
set.</dd>
<dt><b>I18NPATH</b></dt>
<dd>A colon-separated list of search directories for files.</dd>
</dl>
</section>
<section class="Sh">
<h1 class="Sh" id="FILES"><a class="permalink" href="#FILES">FILES</a></h1>
<dl class="Bl-tag">
<dt><i>/usr/share/i18n/charmaps</i></dt>
<dd>Usual default character map path.</dd>
<dt><i>/usr/share/i18n/locales</i></dt>
<dd>Usual default path for locale definition files.</dd>
<dt><i>/usr/share/i18n/repertoiremaps</i></dt>
<dd>Usual default repertoire map path.</dd>
<dt><i>/usr/lib/locale/locale-archive</i></dt>
<dd>Usual default locale archive location.</dd>
<dt><i>/usr/lib/locale</i></dt>
<dd>Usual default path for compiled individual locale data files.</dd>
<dt><i>outputpath/LC_ADDRESS</i></dt>
<dd>An output file that contains information about formatting of addresses and
geography-related items.</dd>
<dt><i>outputpath/LC_COLLATE</i></dt>
<dd>An output file that contains information about the rules for comparing
strings.</dd>
<dt><i>outputpath/LC_CTYPE</i></dt>
<dd>An output file that contains information about character classes.</dd>
<dt><i>outputpath/LC_IDENTIFICATION</i></dt>
<dd>An output file that contains metadata about the locale.</dd>
<dt><i>outputpath/LC_MEASUREMENT</i></dt>
<dd>An output file that contains information about locale measurements (metric
versus US customary).</dd>
<dt><i>outputpath/LC_MESSAGES/SYS_LC_MESSAGES</i></dt>
<dd>An output file that contains information about the language messages
should be printed in, and what an affirmative or negative answer looks
like.</dd>
<dt><i>outputpath/LC_MONETARY</i></dt>
<dd>An output file that contains information about formatting of monetary
values.</dd>
<dt><i>outputpath/LC_NAME</i></dt>
<dd>An output file that contains information about salutations for
persons.</dd>
<dt><i>outputpath/LC_NUMERIC</i></dt>
<dd>An output file that contains information about formatting of nonmonetary
numeric values.</dd>
<dt><i>outputpath/LC_PAPER</i></dt>
<dd>An output file that contains information about settings related to
standard paper size.</dd>
<dt><i>outputpath/LC_TELEPHONE</i></dt>
<dd>An output file that contains information about formats to be used with
telephone services.</dd>
<dt><i>outputpath/LC_TIME</i></dt>
<dd>An output file that contains information about formatting of data and time
values.</dd>
</dl>
</section>
<section class="Sh">
<h1 class="Sh" id="CONFORMING_TO"><a class="permalink" href="#CONFORMING_TO">CONFORMING
TO</a></h1>
POSIX.1-2008.
</section>
<section class="Sh">
<h1 class="Sh" id="EXAMPLE"><a class="permalink" href="#EXAMPLE">EXAMPLE</a></h1>
Compile the locale files for Finnish in the UTF-8 character set and add it to
the default locale archive with the name <b>fi_FI.UTF-8</b>:
<p class="Pp">
<br/>
</p>
<pre>
localedef -f UTF-8 -i fi_FI fi_FI.UTF-8
</pre>
<br/>
<p class="Pp">The next example does the same thing, but generates files into the
<i>fi_FI.UTF-8</i> directory which can then be used by programs when the
environment variable <b>LOCPATH</b> is set to the current directory (note
that the last argument must contain a slash):</p>
<p class="Pp">
<br/>
</p>
<pre>
localedef -f UTF-8 -i fi_FI ./fi_FI.UTF-8
</pre>
<br/>
</section>
<section class="Sh">
<h1 class="Sh" id="SEE_ALSO"><a class="permalink" href="#SEE_ALSO">SEE
ALSO</a></h1>
<b>locale</b>(1), <b>charmap</b>(5), <b>locale</b>(5), <b>repertoiremap</b>(5),
<b>locale</b>(7)
</section>
<section class="Sh">
<h1 class="Sh" id="COLOPHON"><a class="permalink" href="#COLOPHON">COLOPHON</a></h1>
This page is part of release 5.05 of the Linux <i>man-pages</i> project. A
description of the project, information about reporting bugs, and the latest
version of this page, can be found at https://www.kernel.org/doc/man-pages/.
</section>
</div>
<table class="foot">
<tr>
<td class="foot-date">2019-10-10</td>
<td class="foot-os">Linux</td>
</tr>
</table>
</div>
<div class=footer>
<p>Copyright 2020 Scott Court</p>
</div>
</div>
</body>
| 42.80531 | 124 | 0.671353 |
e7223dc92cb3677e9be29ea506e0e6e936cdac61 | 761 | js | JavaScript | src/yank.js | nathanedwards/yankee-doodle | 3ea7c1c31a534a588e0f223cb9c4d8d8ef80e219 | [
"MIT"
] | null | null | null | src/yank.js | nathanedwards/yankee-doodle | 3ea7c1c31a534a588e0f223cb9c4d8d8ef80e219 | [
"MIT"
] | null | null | null | src/yank.js | nathanedwards/yankee-doodle | 3ea7c1c31a534a588e0f223cb9c4d8d8ef80e219 | [
"MIT"
] | null | null | null | const walk = require('./walk')
const isObject = require('./isObject')
function yank (object, ...args) {
if (!args.length) return object
const schemaList = args.flat()
const yanked = {}
if (!schemaList.every(arg => typeof arg === 'string')) throw 'All arguments must be strings'
for (const schema of schemaList) {
const parsedArgs = schema
.replace(/\s+/g, '')
.replace(/([\w->]+)/g, '"$1"')
.replace(/((?<!}),|(?<=")\s?}|(?<!})$)/g, ':0$1')
const parsedSchema = JSON.parse(`{${parsedArgs}}`)
walk(object, yanked, parsedSchema, this.nullify)
}
if (this && this.nullify && isObject(yanked)) {
const { length } = Object.values(yanked)
if (!length) return null
}
return yanked
}
module.exports = yank
| 24.548387 | 94 | 0.593955 |
963e7a50e649afcf307ba965bd9836cce33edb9f | 370 | php | PHP | app/Models/Audio.php | EmadMohDev/quran | e18ad1f15801789fed5658441e45986a57a6b465 | [
"MIT"
] | null | null | null | app/Models/Audio.php | EmadMohDev/quran | e18ad1f15801789fed5658441e45986a57a6b465 | [
"MIT"
] | null | null | null | app/Models/Audio.php | EmadMohDev/quran | e18ad1f15801789fed5658441e45986a57a6b465 | [
"MIT"
] | null | null | null | <?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Audio extends Model
{
use HasFactory;
protected $table = 'audios';
protected $fillable = ['src', 'quality', 'default_audio', 'ayah_id'];
public function ayah()
{
return $this->belongsTo(Ayah::class);
}
}
| 18.5 | 73 | 0.678378 |
04cf38a30057339ad1290b6e2043c569b0faa868 | 3,537 | java | Java | sdks/java/core/src/test/java/org/apache/beam/sdk/io/SerializableAvroCodecFactoryTest.java | charithe/beam | f085cb500730cf0c67c467ac55f92b3c59f52b39 | [
"Apache-2.0"
] | 5,279 | 2016-12-29T04:00:44.000Z | 2022-03-31T22:56:45.000Z | sdks/java/core/src/test/java/org/apache/beam/sdk/io/SerializableAvroCodecFactoryTest.java | charithe/beam | f085cb500730cf0c67c467ac55f92b3c59f52b39 | [
"Apache-2.0"
] | 14,149 | 2016-12-28T00:43:50.000Z | 2022-03-31T23:50:22.000Z | sdks/java/core/src/test/java/org/apache/beam/sdk/io/SerializableAvroCodecFactoryTest.java | charithe/beam | f085cb500730cf0c67c467ac55f92b3c59f52b39 | [
"Apache-2.0"
] | 3,763 | 2016-12-29T04:06:10.000Z | 2022-03-31T22:25:49.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.io;
import static org.apache.avro.file.DataFileConstants.BZIP2_CODEC;
import static org.apache.avro.file.DataFileConstants.DEFLATE_CODEC;
import static org.apache.avro.file.DataFileConstants.NULL_CODEC;
import static org.apache.avro.file.DataFileConstants.SNAPPY_CODEC;
import static org.apache.avro.file.DataFileConstants.XZ_CODEC;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.List;
import org.apache.avro.file.CodecFactory;
import org.apache.beam.sdk.util.SerializableUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests of SerializableAvroCodecFactory. */
@RunWith(JUnit4.class)
public class SerializableAvroCodecFactoryTest {
private final List<String> avroCodecs =
Arrays.asList(NULL_CODEC, SNAPPY_CODEC, DEFLATE_CODEC, XZ_CODEC, BZIP2_CODEC);
@Test
public void testDefaultCodecsIn() throws Exception {
for (String codec : avroCodecs) {
SerializableAvroCodecFactory codecFactory =
new SerializableAvroCodecFactory(CodecFactory.fromString(codec));
assertEquals(CodecFactory.fromString(codec).toString(), codecFactory.getCodec().toString());
}
}
@Test
public void testDefaultCodecsSerDe() throws Exception {
for (String codec : avroCodecs) {
SerializableAvroCodecFactory codecFactory =
new SerializableAvroCodecFactory(CodecFactory.fromString(codec));
SerializableAvroCodecFactory serdeC = SerializableUtils.clone(codecFactory);
assertEquals(CodecFactory.fromString(codec).toString(), serdeC.getCodec().toString());
}
}
@Test
public void testDeflateCodecSerDeWithLevels() throws Exception {
for (int i = 0; i < 10; ++i) {
SerializableAvroCodecFactory codecFactory =
new SerializableAvroCodecFactory(CodecFactory.deflateCodec(i));
SerializableAvroCodecFactory serdeC = SerializableUtils.clone(codecFactory);
assertEquals(CodecFactory.deflateCodec(i).toString(), serdeC.getCodec().toString());
}
}
@Test
public void testXZCodecSerDeWithLevels() throws Exception {
for (int i = 0; i < 10; ++i) {
SerializableAvroCodecFactory codecFactory =
new SerializableAvroCodecFactory(CodecFactory.xzCodec(i));
SerializableAvroCodecFactory serdeC = SerializableUtils.clone(codecFactory);
assertEquals(CodecFactory.xzCodec(i).toString(), serdeC.getCodec().toString());
}
}
@Test(expected = NullPointerException.class)
public void testNullCodecToString() throws Exception {
// use default CTR (available cause Serializable)
SerializableAvroCodecFactory codec = new SerializableAvroCodecFactory();
codec.toString();
}
}
| 37.62766 | 98 | 0.757987 |
bdbe1ab8409509af1c822347e5bbf65ebd5688d8 | 54,176 | rs | Rust | src/typechecker/typecheck.rs | GeorgeKT/nomad-lang | 5539cccbbfa7ef50172a51da78b0e7db053ddcc4 | [
"MIT"
] | null | null | null | src/typechecker/typecheck.rs | GeorgeKT/nomad-lang | 5539cccbbfa7ef50172a51da78b0e7db053ddcc4 | [
"MIT"
] | null | null | null | src/typechecker/typecheck.rs | GeorgeKT/nomad-lang | 5539cccbbfa7ef50172a51da78b0e7db053ddcc4 | [
"MIT"
] | null | null | null | use std::ops::Deref;
use ast::*;
use compileerror::{CompileResult, CompileError, type_error, unknown_type_result, unknown_name, type_error_result};
use super::typecheckercontext::{TypeCheckerContext, ImportSymbolResolver};
use super::instantiategenerics::instantiate_generics;
use super::typeresolver::{resolve_type, resolve_types, TypeResolved};
use super::matchchecker::check_match_is_exhaustive;
use super::genericmapper::fill_in_generics;
use super::instantiate::make_concrete;
use target::Target;
use span::Span;
#[derive(Debug)]
enum TypeCheckAction
{
Valid(Type),
ReplaceBy(Expression)
}
impl TypeCheckAction
{
pub fn unwrap(self) -> Type
{
match self
{
TypeCheckAction::Valid(t) => t,
_ => panic!("Expecting a real type here, and not a replace by expression !"),
}
}
}
type TypeCheckResult = CompileResult<TypeCheckAction>;
fn valid(typ: Type) -> TypeCheckResult {
Ok(TypeCheckAction::Valid(typ))
}
fn replace_by(e: Expression) -> TypeCheckResult
{
Ok(TypeCheckAction::ReplaceBy(e))
}
fn convert_type(ctx: &mut TypeCheckerContext, dst_type: &Type, src_type: &Type, expr: &mut Expression, target: &Target) -> CompileResult<()>
{
if *dst_type == *src_type {
return Ok(());
}
let mut converted = false;
if let Some(new_expression) = dst_type.convert(src_type, expr) {
*expr = new_expression;
converted = true;
}
if let Expression::Literal(ref mut lit) = *expr {
if let Some(new_lit) = lit.try_convert(dst_type) {
*lit = new_lit;
converted = true;
}
}
if converted {
assert_eq!(type_check_expression(ctx, expr, None, target)?, *dst_type);
Ok(())
} else {
type_error_result(
&expr.span(),
format!("Expecting an expression of type {} or something convertible to, but found one of type {}", dst_type, src_type))
}
}
fn type_check_unary_op(ctx: &mut TypeCheckerContext, u: &mut UnaryOp, target: &Target) -> TypeCheckResult
{
let e_type = type_check_expression(ctx, &mut u.expression, None, target)?;
if e_type.is_generic() {
u.typ = e_type.clone();
return valid(e_type)
}
match u.operator
{
UnaryOperator::Sub => {
if !e_type.is_numeric() {
type_error_result(&u.span, format!("Unary operator {} expects a numeric expression", u.operator))
} else {
u.typ = e_type.clone();
valid(e_type)
}
},
UnaryOperator::Not => {
if e_type != Type::Bool {
type_check_with_conversion(ctx, &mut u.expression, &Type::Bool, target)?;
}
u.typ = Type::Bool;
valid(Type::Bool)
}
}
}
fn type_check_with_conversion(ctx: &mut TypeCheckerContext, e: &mut Expression, expected_type: &Type, target: &Target) -> CompileResult<()>
{
let typ = type_check_expression(ctx, e, None, target)?;
convert_type(ctx, expected_type, &typ, e, target)
}
fn basic_bin_op_checks(ctx: &mut TypeCheckerContext, b: &mut BinaryOp, left_type: Type, right_type: Type, target: &Target) -> CompileResult<()>
{
if left_type != right_type {
let result = type_check_with_conversion(ctx, &mut b.right, &left_type, target)
.or(type_check_with_conversion(ctx, &mut b.left, &right_type, target));
if !result.is_ok() {
return type_error_result(
&b.span,
format!("Operator {} expects operands of the same type (left type: {}, right type: {})", b.operator, left_type, right_type))
}
}
let new_left_type = b.left.get_type(target.int_size);
if !new_left_type.is_binary_operator_supported(b.operator) {
type_error_result(&b.span, format!("Operator {} is not supported on {}", b.operator, new_left_type))
} else {
Ok(())
}
}
fn type_check_binary_op(ctx: &mut TypeCheckerContext, b: &mut BinaryOp, target: &Target) -> TypeCheckResult
{
let left_type = type_check_expression(ctx, &mut b.left, None, target)?;
let right_type = type_check_expression(ctx, &mut b.right, None, target)?;
if left_type.is_generic() || right_type.is_generic() {
return valid(left_type);
}
match b.operator
{
BinaryOperator::Add |
BinaryOperator::Sub |
BinaryOperator::Mul |
BinaryOperator::Div |
BinaryOperator::Mod => {
basic_bin_op_checks(ctx, b, left_type, right_type, target)?;
b.typ = b.left.get_type(target.int_size);
valid(b.typ.clone())
},
BinaryOperator::LessThan |
BinaryOperator::GreaterThan |
BinaryOperator::LessThanEquals |
BinaryOperator::GreaterThanEquals => {
basic_bin_op_checks(ctx, b, left_type, right_type, target)?;
b.typ = Type::Bool;
valid(Type::Bool)
},
BinaryOperator::And => {
type_check_with_conversion(ctx, &mut b.left, &Type::Bool, target)?;
type_check_with_conversion(ctx, &mut b.right, &Type::Bool, target)?;
b.typ = Type::Bool;
valid(Type::Bool)
},
BinaryOperator::Or => {
if left_type.is_optional_of(&right_type) {
b.typ = right_type.clone();
valid(right_type)
} else {
type_check_with_conversion(ctx, &mut b.left, &Type::Bool, target)?;
type_check_with_conversion(ctx, &mut b.right, &Type::Bool, target)?;
b.typ = Type::Bool;
valid(Type::Bool)
}
},
BinaryOperator::Equals |
BinaryOperator::NotEquals => {
if left_type.is_optional_of(&Type::Unknown) && right_type.is_optional_of(&Type::Unknown) {
return if b.operator == BinaryOperator::Equals {
replace_by(Expression::Literal(Literal::Bool(b.span.clone(), true)))
} else {
replace_by(Expression::Literal(Literal::Bool(b.span.clone(), false)))
};
} else if left_type.is_optional() && right_type.is_optional_of(&Type::Unknown) {
type_check_with_conversion(ctx, &mut b.right, &left_type, target)?;
} else if right_type.is_optional() && left_type.is_optional_of(&Type::Unknown) {
type_check_with_conversion(ctx, &mut b.left, &right_type, target)?;
} else {
basic_bin_op_checks(ctx, b, left_type, right_type, target)?;
}
b.typ = Type::Bool;
valid(Type::Bool)
},
_ => type_error_result(&b.span, format!("Operator {} is not a binary operator", b.operator))
}
}
fn type_check_array_literal(ctx: &mut TypeCheckerContext, a: &mut ArrayLiteral, target: &Target) -> TypeCheckResult
{
if a.elements.is_empty() {
a.array_type = array_type(target.native_uint_type.clone(), 0);
return valid(a.array_type.clone());
}
let mut array_element_type = Type::Unknown;
for e in &mut a.elements {
let t = type_check_expression(ctx, e, None, target)?;
if array_element_type == Type::Unknown {
array_element_type = t;
} else if array_element_type != t {
return type_error_result(&e.span(), "Array elements must have the same type");
}
}
let array_type = array_type(array_element_type, a.elements.len());
if a.array_type == Type::Unknown {
a.array_type = array_type;
} else if a.array_type != array_type {
return type_error_result(&a.span, format!("Array has type {}, but elements have type {}", a.array_type, array_type))
}
valid(a.array_type.clone())
}
fn resolve_generic_args_in_call(ctx: &mut TypeCheckerContext, ft: &FuncType, c: &mut Call, target: &Target) -> CompileResult<Vec<Type>>
{
let mut arg_types = Vec::with_capacity(c.args.len());
let mut count = c.generic_args.len();
loop
{
arg_types.clear();
for (arg, expected_arg_type) in c.args.iter_mut().zip(ft.args.iter())
{
let expected_arg_type = make_concrete(ctx, &c.generic_args, expected_arg_type, &arg.span())?;
let arg_type = type_check_expression(ctx, arg, Some(&expected_arg_type), target)?;
let arg_type = make_concrete(ctx, &c.generic_args, &arg_type, &arg.span())?;
if expected_arg_type.is_generic() {
fill_in_generics(ctx, &arg_type, &expected_arg_type, &mut c.generic_args, &arg.span())?;
}
arg_types.push(arg_type);
}
if c.generic_args.len() == count {
break;
}
count = c.generic_args.len();
}
Ok(arg_types)
}
fn type_check_call(ctx: &mut TypeCheckerContext, c: &mut Call, target: &Target) -> TypeCheckResult
{
let resolved = ctx.resolve(&c.callee.name)
.ok_or_else(|| unknown_name(&c.callee.span, format!("Unknown call {}", c.callee.name)))?;
c.callee.name = resolved.name;
if let Type::Func(ref ft) = resolved.typ
{
if ft.args.len() != c.args.len() {
return type_error_result(&c.span,
format!("Attempting to call {} with {} arguments, but it needs {}", c.callee.name, c.args.len(), ft.args.len()));
}
let arg_types = resolve_generic_args_in_call(ctx, ft, c, target)?;
for (idx, arg) in c.args.iter_mut().enumerate()
{
let expected_arg_type = make_concrete(ctx, &c.generic_args, &ft.args[idx], &arg.span())?;
let arg_type = &arg_types[idx];
convert_type(ctx, &expected_arg_type, arg_type, arg, target)?;
}
if ft.return_type.is_generic() {
c.return_type = make_concrete(ctx, &c.generic_args, &ft.return_type, &c.span)?;
return valid(c.return_type.clone());
}
c.return_type = ft.return_type.clone();
valid(ft.return_type.clone())
}
else
{
type_error_result(&c.span, format!("{} is not callable", c.callee.name))
}
}
pub fn type_check_function(ctx: &mut TypeCheckerContext, fun: &mut Function, target: &Target) -> CompileResult<()>
{
ctx.enter_scope(Some(fun.sig.return_type.clone()));
for arg in &mut fun.sig.args
{
ctx.add(Symbol::new(&arg.name, &arg.typ, arg.mutable, &arg.span, SymbolType::Normal))?;
}
let et = match type_check_expression(ctx, &mut fun.expression, Some(&fun.sig.return_type), target)
{
Err(CompileError::UnknownType(ref name, ref expected_type)) => {
update_binding_type(ctx, &mut fun.expression, name, expected_type, target)?;
type_check_expression(ctx, &mut fun.expression, Some(&fun.sig.return_type), target)?
},
Err(e) => return Err(e),
Ok(typ) => typ,
};
ctx.exit_scope();
if et != fun.sig.return_type {
if let Some(expression) = fun.sig.return_type.convert(&et, &fun.expression) {
fun.expression = expression;
} else {
return type_error_result(&fun.span, format!("Function {} has return type {}, but it is returning an expression of type {}",
fun.sig.name, fun.sig.return_type, et));
}
}
fun.type_checked = true;
Ok(())
}
fn is_result_mutable(ctx: &TypeCheckerContext, e: &Expression) -> bool
{
match *e {
Expression::Dereference(ref d) => is_result_mutable(ctx, &d.inner),
Expression::AddressOf(ref a) => is_result_mutable(ctx, &a.inner),
Expression::NameRef(ref nr) =>
ctx.resolve(&nr.name).map(|rn| rn.mutable).unwrap_or(false),
Expression::MemberAccess(ref ma) =>
is_result_mutable(ctx, &ma.left),
_ => false
}
}
fn type_check_match(ctx: &mut TypeCheckerContext, m: &mut MatchExpression, target: &Target) -> TypeCheckResult
{
let target_type = type_check_expression(ctx, &mut m.target, None, target)?;
let target_is_mutable = is_result_mutable(ctx, &m.target);
let mut return_type = Type::Unknown;
for c in &mut m.cases
{
let infer_case_type = |ctx: &mut TypeCheckerContext, e: &mut Expression, return_type: &Type| {
let tt = type_check_expression(ctx, e, None, target)?;
if *return_type != Type::Unknown && *return_type != tt {
type_error_result(&e.span(), "Expressions in match statements must return the same type")
} else {
Ok(tt)
}
};
let match_span = c.pattern.span();
let case_type = match c.pattern
{
Pattern::EmptyArray(ref ap) => {
if !target_type.is_sequence() {
return type_error_result(&ap.span, format!("Attempting to pattern match an expression of type {}, with an empty array", target_type));
}
infer_case_type(ctx, &mut c.to_execute, &return_type)?
},
Pattern::Array(ref ap) => {
if !target_type.is_sequence() {
return type_error_result(&ap.span, format!("Attempting to pattern match an expression of type {}, with an array", target_type));
}
let element_type = target_type.get_element_type().expect("target_type is not an array type");
ctx.enter_scope(None);
ctx.add(Symbol::new(&ap.head, &element_type, false, &ap.span, SymbolType::Normal))?;
ctx.add(Symbol::new(&ap.tail, &slice_type(element_type.clone()), false, &ap.span, SymbolType::Normal))?;
let ct = infer_case_type(ctx, &mut c.to_execute, &return_type)?;
ctx.exit_scope();
ct
},
Pattern::Name(ref mut nr) => {
type_check_name(ctx, nr, Some(&target_type))?;
if nr.typ != target_type {
return type_error_result(&match_span,
format!("Cannot pattern match an expression of type {} with an expression of type {}",
target_type, nr.typ));
}
match nr.typ
{
Type::Sum(ref st) => {
let idx = st.index_of(&nr.name).expect("Internal Compiler Error: cannot determine index of sum type case");
let case = &st.cases[idx];
if case.typ == target.native_uint_type {
infer_case_type(ctx, &mut c.to_execute, &return_type)?
} else {
return type_error_result(&match_span, "Invalid pattern match, match should be with an empty sum case");
}
},
Type::Enum(_) => {
infer_case_type(ctx, &mut c.to_execute, &return_type)?
},
_ => {
return type_error_result(&match_span, "Invalid pattern match");
}
}
},
Pattern::Literal(Literal::Array(ref mut al)) => {
let m_type = type_check_array_literal(ctx, al, target)?.unwrap();
if !target_type.is_matchable(&m_type) {
return type_error_result(&al.span, format!("Pattern match of type {}, cannot match with an expression of type {}",
m_type, target_type));
}
infer_case_type(ctx, &mut c.to_execute, &return_type)?
},
Pattern::Literal(ref lit) => {
let m_type = lit.get_type();
if !target_type.is_matchable(&m_type) {
return type_error_result(&c.pattern.span(), format!("Pattern match of type {}, cannot match with an expression of type {}",
m_type, target_type));
}
infer_case_type(ctx, &mut c.to_execute, &return_type)?
},
Pattern::Struct(ref mut p) => {
ctx.enter_scope(None);
type_check_struct_pattern(ctx, p, target_is_mutable)?;
if p.typ != target_type {
return type_error_result(&match_span,
format!("Cannot pattern match an expression of type {} with an expression of type {}",
target_type, p.typ));
}
let ct = infer_case_type(ctx, &mut c.to_execute, &return_type)?;
ctx.exit_scope();
ct
},
Pattern::Any(_) => {
infer_case_type(ctx, &mut c.to_execute, &return_type)?
},
Pattern::Nil(ref span) => {
if !target_type.is_optional() {
return type_error_result(span,
format!("Cannot match type {} to nil, only optionals can be matched to nil", target_type));
}
infer_case_type(ctx, &mut c.to_execute, &return_type)?
},
Pattern::Optional(ref mut o) => {
if !target_type.is_optional() {
return type_error_result(&o.span,
format!("Cannot match type {} to optional pattern", target_type));
}
o.inner_type = target_type.get_element_type().expect("Optional type expected");
ctx.enter_scope(None);
ctx.add(Symbol::new(&o.binding, &o.inner_type, target_is_mutable, &o.span, SymbolType::Normal))?;
let ct = infer_case_type(ctx, &mut c.to_execute, &return_type)?;
ctx.exit_scope();
ct
},
};
if return_type == Type::Unknown {
return_type = case_type;
} else if return_type != case_type {
return type_error_result(&m.span, "Cases of match statements must return the same type");
}
}
m.typ = return_type.clone();
check_match_is_exhaustive(m, &target_type)?;
valid(return_type)
}
fn type_check_lambda_body(ctx: &mut TypeCheckerContext, m: &mut Lambda, target: &Target) -> TypeCheckResult
{
ctx.enter_scope(None);
for arg in &mut m.sig.args {
ctx.add(Symbol::new(&arg.name, &arg.typ, false, &arg.span, SymbolType::Normal))?;
}
let return_type = type_check_expression(ctx, &mut m.expr, None, target)?;
ctx.exit_scope();
m.set_return_type(return_type);
valid(m.sig.typ.clone())
}
fn type_check_lambda(ctx: &mut TypeCheckerContext, m: &mut Lambda, type_hint: Option<&Type>, target: &Target) -> TypeCheckResult
{
match type_hint
{
Some(typ) => {
use uuid::{Uuid};
m.sig.name = format!("lambda-{}", Uuid::new_v4()); // Add a uuid, so we don't get name clashes
m.apply_type(typ)?;
let infered_type = type_check_lambda_body(ctx, m, target)?.unwrap();
if infered_type != *typ {
return type_error_result(&m.span, format!("Lambda body has the wrong type, expecting {}, got {}", typ, infered_type));
}
valid(infered_type)
},
None => {
if m.is_generic() {
return valid(Type::Unknown);
}
type_check_lambda_body(ctx, m, target)
},
}
}
fn is_instantiation_of(concrete_type: &Type, generic_type: &Type) -> bool
{
if !generic_type.is_generic() {
return *concrete_type == *generic_type;
}
match (concrete_type, generic_type)
{
(&Type::Array(ref a), &Type::Array(ref b)) => is_instantiation_of(&a.element_type, &b.element_type),
(_, &Type::Generic(_)) => true,
(&Type::Struct(ref a), &Type::Struct(ref b)) => {
a.members.len() == b.members.len() &&
a.members.iter()
.zip(b.members.iter())
.all(|(ma, mb)| is_instantiation_of(&ma.typ, &mb.typ))
},
(&Type::Func(ref a), &Type::Func(ref b)) => {
is_instantiation_of(&a.return_type, &b.return_type) &&
a.args.iter()
.zip(b.args.iter())
.all(|(ma, mb)| is_instantiation_of(ma, mb))
}
(&Type::Sum(ref a), &Type::Sum(ref b)) => {
a.cases.iter()
.zip(b.cases.iter())
.all(|(ma, mb)| is_instantiation_of(&ma.typ, &mb.typ))
}
_ => false,
}
}
fn type_check_name(ctx: &mut TypeCheckerContext, nr: &mut NameRef, type_hint: Option<&Type>) -> TypeCheckResult
{
if nr.name == "_" {
return valid(Type::Unknown);
}
if !nr.typ.is_unknown() && !nr.typ.is_generic() {
return valid(nr.typ.clone()); // We have already determined the type
}
let resolved = ctx.resolve(&nr.name)
.ok_or_else(|| unknown_name(&nr.span, format!("Unknown name {}", nr.name)))?;
nr.name = resolved.name;
if let Some(typ) = type_hint {
if resolved.typ == Type::Unknown {
return unknown_type_result(&nr.name, typ);
}
if resolved.typ == *typ {
nr.typ = resolved.typ;
return valid(nr.typ.clone());
}
if !resolved.typ.is_generic() && !typ.is_generic() && !resolved.typ.is_convertible(typ) {
return type_error_result(&nr.span, format!("Type mismatch: expecting {}, but {} has type {}", typ, nr.name, resolved.typ));
}
if resolved.typ.is_generic() && !typ.is_generic() {
if !is_instantiation_of(typ, &resolved.typ) {
type_error_result(&nr.span, format!("Type mismatch: {} is not a valid instantiation of {}", typ, resolved.typ))
} else {
nr.typ = typ.clone();
valid(nr.typ.clone())
}
} else {
nr.typ = resolved.typ;
valid(nr.typ.clone())
}
} else {
nr.typ = resolved.typ;
valid(nr.typ.clone())
}
}
fn add_struct_bindings(ctx: &mut TypeCheckerContext, b: &mut StructPattern, struct_type: &StructType, mutable: bool) -> CompileResult<()>
{
for (binding, member) in b.bindings.iter_mut().zip(struct_type.members.iter()) {
if binding.name == "_" {continue}
let mutable = match binding.mode {
StructPatternBindingMode::Value => {
binding.typ = member.typ.clone();
false
},
StructPatternBindingMode::Pointer => {
binding.typ = ptr_type(member.typ.clone());
mutable
},
};
ctx.add(Symbol::new(&binding.name, &binding.typ, mutable, &b.span, SymbolType::Normal))?;
}
Ok(())
}
fn type_check_binding(ctx: &mut TypeCheckerContext, b: &mut Binding, target: &Target) -> TypeCheckResult
{
b.typ = type_check_expression(ctx, &mut b.init, None, target)?;
match b.binding_type
{
BindingType::Name(ref name) => {
ctx.add(Symbol::new(name, &b.typ, b.mutable, &b.span, SymbolType::Normal))?;
},
BindingType::Struct(ref mut s) => {
s.typ = b.typ.clone();
if let Type::Struct(ref st) = b.typ
{
if st.members.len() != s.bindings.len() {
return type_error_result(&s.span,
format!("Wrong number of members in struct binding (expecting {}, found {})",
st.members.len(), s.bindings.len()));
}
add_struct_bindings(ctx, s, st, false)?;
}
else
{
return type_error_result(&b.init.span(), "Expression does not return a struct type");
}
},
}
valid(b.typ.clone())
}
fn update_binding_type(ctx: &mut TypeCheckerContext, e: &mut Expression, name: &str, expected_type: &Type, target: &Target) -> CompileResult<()>
{
let mut update_binding = |e: &mut Expression| {
if let Expression::Bindings(ref mut bl) = *e {
for b in &mut bl.bindings {
if let BindingType::Name(ref b_name) = b.binding_type
{
if *b_name == *name {
// It's one we know, so lets try again with a proper type hint
b.typ = type_check_expression(ctx, &mut b.init, Some(&expected_type), target)?;
ctx.update(Symbol::new(b_name, &b.typ, b.mutable, &b.span, SymbolType::Normal));
return Ok(())
}
}
}
}
Ok(())
};
e.visit_mut(&mut update_binding)
}
fn type_check_if(ctx: &mut TypeCheckerContext, i: &mut IfExpression, type_hint: Option<&Type>, target: &Target) -> TypeCheckResult
{
type_check_with_conversion(ctx, &mut i.condition, &Type::Bool, target)?;
let on_true_type = type_check_expression(ctx, &mut i.on_true, type_hint.clone(), target)?;
let on_false_type = if let Some(ref mut expr) = i.on_false {
type_check_expression(ctx, expr, type_hint.clone(), target)?
} else {
Type::Void
};
if on_true_type != on_false_type
{
if i.on_false.is_none()
{
type_error_result(&i.span, format!("If expressions without an else part, must return void (type of then part is {})", on_true_type))
}
else if on_true_type.is_optional_of(&on_false_type) || on_true_type.is_optional_of(&Type::Unknown)
{
let optional_type = optional_type(on_false_type);
if let Some(ref mut expr) = i.on_false {
type_check_with_conversion(ctx, expr, &optional_type, target)?;
}
type_check_with_conversion(ctx, &mut i.on_true, &optional_type, target)?;
i.typ = optional_type.clone();
valid(optional_type)
}
else if on_false_type.is_optional_of(&on_true_type) || on_false_type.is_optional_of(&Type::Unknown)
{
let optional_type = optional_type(on_true_type);
if let Some(ref mut expr) = i.on_false {
type_check_with_conversion(ctx, expr, &optional_type, target)?;
}
type_check_with_conversion(ctx, &mut i.on_true, &optional_type, target)?;
i.typ = optional_type.clone();
valid(optional_type)
}
else
{
type_error_result(&i.span,
format!("then and else expression of an if expression need to be of the same type, then has type {}, else has type {}", on_true_type, on_false_type)
)
}
}
else
{
i.typ = on_true_type;
valid(on_false_type)
}
}
fn type_check_struct_members_in_initializer(ctx: &mut TypeCheckerContext, st: &StructType, si: &mut StructInitializer, target: &Target) -> CompileResult<Type>
{
if st.members.len() != si.member_initializers.len() {
return type_error_result(&si.span,
format!("Type {} has {} members, but attempting to initialize {} members", si.struct_name, st.members.len(), si.member_initializers.len()));
}
let mut new_members = Vec::with_capacity(st.members.len());
for (idx, (member, mi)) in st.members.iter().zip(si.member_initializers.iter_mut()).enumerate()
{
let t = type_check_expression(ctx, mi, Some(&member.typ), target)?;
let expected_type = if member.typ.is_generic() {
fill_in_generics(ctx, &t, &member.typ, &mut si.generic_args, &mi.span())?
} else {
member.typ.clone()
};
if t != expected_type
{
if let Some(new_mi) = expected_type.convert(&t, mi) {
*mi = new_mi;
} else {
return type_error_result(
&mi.span(),
format!("Attempting to initialize member {} with type '{}', expecting an expression of type '{}'",
idx, t, expected_type)
);
}
}
new_members.push(struct_member(&member.name, expected_type));
}
Ok(struct_type(&st.name, new_members))
}
fn type_check_anonymous_struct_initializer(ctx: &mut TypeCheckerContext, si: &mut StructInitializer, target: &Target) -> TypeCheckResult
{
let mut new_members = Vec::with_capacity(si.member_initializers.len());
for mi in &mut si.member_initializers
{
let t = type_check_expression(ctx, mi, None, target)?;
new_members.push(struct_member("", t));
}
si.typ = struct_type("", new_members);
valid(si.typ.clone())
}
fn type_check_struct_initializer(ctx: &mut TypeCheckerContext, si: &mut StructInitializer, target: &Target) -> TypeCheckResult
{
if si.struct_name.is_empty() {
return type_check_anonymous_struct_initializer(ctx, si, target);
}
let resolved = ctx.resolve(&si.struct_name).ok_or_else(|| unknown_name(&si.span, format!("Unknown struct {}", si.struct_name)))?;
si.struct_name = resolved.name;
match resolved.typ
{
Type::Struct(ref st) => {
si.typ = type_check_struct_members_in_initializer(ctx, st, si, target)?;
valid(si.typ.clone())
},
Type::Sum(ref st) => {
let idx = st.index_of(&si.struct_name).expect("Internal Compiler Error: cannot determine index of sum type case");
let mut sum_type_cases = Vec::with_capacity(st.cases.len());
for (i, case) in st.cases.iter().enumerate()
{
let typ = if i == idx
{
match case.typ
{
Type::Struct(ref s) => type_check_struct_members_in_initializer(ctx, s, si, target)?,
Type::Int(p) => Type::Int(p),
_ => return type_error_result(&si.span, "Invalid sum type case"),
}
} else {
case.typ.clone()
};
sum_type_cases.push(sum_type_case(&case.name, typ))
}
si.typ = sum_type(&st.name, sum_type_cases);
valid(si.typ.clone())
},
Type::String => {
let string_rep = string_type_representation(target.int_size);
type_check_struct_members_in_initializer(ctx, &string_rep, si, target)?;
si.typ = Type::String;
valid(Type::String)
},
_ => type_error_result(&si.span, format!("{} is not a struct", si.struct_name)),
}
}
fn find_member_type(members: &[StructMember], member_name: &str, span: &Span) -> CompileResult<(usize, Type)>
{
members.iter()
.enumerate()
.find(|&(_, m)| m.name == *member_name)
.map(|(idx, m)| (idx, m.typ.clone()))
.ok_or_else(|| unknown_name(span, format!("Unknown struct member {}", member_name)))
}
fn member_call_to_call(left: &Expression, call: &Call, int_size: IntSize) -> Expression
{
let mut args = Vec::with_capacity(call.args.len() + 1);
let first_arg = match left.get_type(int_size)
{
Type::Pointer(_) => left.clone(),
_ => address_of(left.clone(), left.span()),
};
args.push(first_arg);
args.extend(call.args.iter().cloned());
Expression::Call(
Box::new(
Call::new(
call.callee.clone(),
args,
call.span.clone(),
)
)
)
}
fn type_check_generic_member_call(ctx: &mut TypeCheckerContext, call: &mut Call, gt: &GenericType) -> CompileResult<Type>
{
let check_interface = |interface: &Type, call: &Call| {
if let Type::Interface(ref it) = *interface {
for func in &it.functions {
if func.name == call.callee.name {
return Some(func.return_type.clone())
}
}
}
None
};
match *gt
{
GenericType::Any(ref name) => {
let interface = ctx.resolve(name)
.ok_or_else(|| type_error(&call.span, format!("Type {} is not an interface", name)))?;
call.return_type = check_interface(&interface.typ, call)
.ok_or_else(|| type_error(&call.span, format!("Interface {} has no member function named {}", interface.name, call.callee.name)))?;
Ok(call.return_type.clone())
},
GenericType::Restricted(ref interfaces) => {
for interface in interfaces {
if let Some(typ) = check_interface(interface, call) {
call.return_type = typ.clone();
return Ok(typ)
}
}
type_error_result(&call.span, format!("No member function named {}", call.callee.name))
}
}
}
fn to_static_function_call(ctx: &mut TypeCheckerContext, sma: &MemberAccess) -> Option<Call>
{
if let Expression::NameRef(ref nr) = sma.left {
if let MemberAccessType::Call(ref call) = sma.right {
let call_name = format!("{}.{}", nr.name, call.callee.name);
if let Some(rn) = ctx.resolve(&call_name) {
if let Type::Func(_) = rn.typ {
let name_span = nr.span.expanded(call.callee.span.end);
let full_span = name_span.expanded(call.span.end);
return Some(
Call::new(
NameRef::new(call_name, name_span),
call.args.clone(),
full_span,
)
)
}
}
}
}
None
}
fn type_check_member_access(ctx: &mut TypeCheckerContext, sma: &mut MemberAccess, target: &Target) -> TypeCheckResult
{
let left_type = type_check_expression(ctx, &mut sma.left, None, target)?;
// member access through pointer is the same as a normal member access
let left_type_ref = if let Type::Pointer(ref inner) = left_type {
use std::ops::Deref;
inner.deref()
} else {
&left_type
};
if let Some(call) = to_static_function_call(ctx, sma) {
return replace_by(Expression::Call(Box::new(call)))
}
let (typ, new_right) = match (&mut sma.right, left_type_ref)
{
(&mut MemberAccessType::Property(Property::Len), &Type::Slice(_)) |
(&mut MemberAccessType::Property(Property::Len), &Type::Array(_)) |
(&mut MemberAccessType::Property(Property::Len), &Type::String) =>
(target.native_uint_type.clone(), None),
(&mut MemberAccessType::Property(Property::Data), &Type::String) =>
(ptr_type(Type::UInt(IntSize::I8)), None),
(&mut MemberAccessType::Property(Property::Data), &Type::Slice(ref st)) =>
(ptr_type(st.element_type.clone()), None),
(&mut MemberAccessType::Name(ref mut field), &Type::Struct(ref st)) => {
let (member_idx, member_type) = find_member_type(&st.members, &field.name, &sma.span)?;
field.index = member_idx;
(member_type, None)
},
(&mut MemberAccessType::Name(ref mut field), &Type::Array(_)) |
(&mut MemberAccessType::Name(ref mut field), &Type::Slice(_)) |
(&mut MemberAccessType::Name(ref mut field), &Type::String) => {
if let Some((typ, member_access_type)) = left_type.get_property_type(&field.name, target) {
(typ, Some(member_access_type))
} else {
return type_error_result(
&sma.span,
format!("Type '{}' has no property named '{}'", left_type, field.name)
);
}
},
(&mut MemberAccessType::Call(ref mut call), &Type::Struct(ref st)) => {
let call_name = format!("{}.{}", st.name, call.callee.name);
call.callee.name = call_name;
return replace_by(member_call_to_call(&sma.left, call, target.int_size));
},
(&mut MemberAccessType::Call(ref mut call), &Type::Sum(ref st)) => {
let call_name = format!("{}.{}", st.name, call.callee.name);
call.callee.name = call_name;
return replace_by(member_call_to_call(&sma.left, call, target.int_size));
},
(&mut MemberAccessType::Call(ref mut call), &Type::Generic(ref gt)) => {
(type_check_generic_member_call(ctx, call, gt)?, None)
},
_ => {
return type_error_result(
&sma.span,
format!("Cannot determine type of member access ({})", left_type_ref)
);
}
};
sma.typ = typ;
if let Some(nr) = new_right {
sma.right = nr;
}
valid(sma.typ.clone())
}
fn type_check_struct_pattern(ctx: &mut TypeCheckerContext, p: &mut StructPattern, target_is_mutable: bool) -> CompileResult<()>
{
if !p.typ.is_unknown() {
return Ok(());
}
let resolved = ctx.resolve(&p.name).ok_or_else(|| unknown_name(&p.span, format!("Unknown struct {}", p.name)))?;
p.name = resolved.name.clone();
match resolved.typ
{
Type::Sum(ref st) => {
let idx = st.index_of(&p.name).expect("Internal Compiler Error: cannot determine index of sum type case");
let case = &st.cases[idx];
match case.typ
{
Type::Struct(ref s) => {
if s.members.len() != p.bindings.len() {
type_error_result(&p.span,
format!("Wrong number of bindings in pattern match (expecting {}, found {})",
s.members.len(), p.bindings.len()))
} else {
add_struct_bindings(ctx, p, s, target_is_mutable)?;
p.typ = Type::Sum(st.clone());
Ok(())
}
},
_ => type_error_result(&p.span, "Attempting to pattern match a normal sum type case with a struct"),
}
},
Type::Struct(ref st) => {
add_struct_bindings(ctx, p, st, target_is_mutable)?;
p.typ = Type::Struct(st.clone());
Ok(())
},
_ => type_error_result(&p.span, "Struct pattern is only allowed for structs and sum types containing structs")
}
}
fn type_check_block(ctx: &mut TypeCheckerContext, b: &mut Block, type_hint: Option<&Type>, target: &Target) -> TypeCheckResult
{
ctx.enter_scope(None);
let num = b.expressions.len();
for (idx, e) in b.expressions.iter_mut().enumerate()
{
let typ = type_check_expression(ctx, e, type_hint, target)?;
if idx == num - 1 {
b.typ = typ;
}
}
ctx.exit_scope();
valid(b.typ.clone())
}
fn type_check_new(ctx: &mut TypeCheckerContext, n: &mut NewExpression, type_hint: Option<&Type>, target: &Target) -> TypeCheckResult
{
let typ = type_check_expression(ctx, &mut n.inner, type_hint, target)?;
n.typ = ptr_type(typ);
valid(n.typ.clone())
}
fn type_check_delete(ctx: &mut TypeCheckerContext, d: &mut DeleteExpression, type_hint: Option<&Type>, target: &Target) -> TypeCheckResult
{
let typ = type_check_expression(ctx, &mut d.inner, type_hint, target)?;
match typ
{
Type::Pointer(_) => valid(Type::Void),
_ => type_error_result(&d.span, format!("delete expression expects a pointer argument, argument has type {}", typ)),
}
}
fn type_check_array_to_slice(ctx: &mut TypeCheckerContext, ats: &mut ArrayToSlice, type_hint: Option<&Type>, target: &Target) -> TypeCheckResult
{
let t = type_check_expression(ctx, &mut ats.inner, type_hint, target)?;
match t
{
Type::Array(at) => {
ats.slice_type = slice_type(at.element_type.clone());
valid(ats.slice_type.clone())
},
_ => type_error_result(&ats.span, "array to slice expression must have an array as input"),
}
}
fn type_check_address_of(ctx: &mut TypeCheckerContext, a: &mut AddressOfExpression, target: &Target) -> TypeCheckResult
{
let t = type_check_expression(ctx, &mut a.inner, None, target)?;
a.typ = ptr_type(t);
valid(a.typ.clone())
}
fn type_check_dereference(ctx: &mut TypeCheckerContext, a: &mut DereferenceExpression, target: &Target) -> TypeCheckResult
{
let t = type_check_expression(ctx, &mut a.inner, None, target)?;
if let Type::Pointer(inner) = t {
a.typ = inner.deref().clone();
valid(a.typ.clone())
} else {
type_error_result(&a.span, "Attempting to dereference a non pointer type expression")
}
}
fn type_check_index_operation(ctx: &mut TypeCheckerContext, iop: &mut IndexOperation, target: &Target) -> CompileResult<Type>
{
let target_type = type_check_expression(ctx, &mut iop.target, None, target)?;
let index_type = type_check_expression(ctx, &mut iop.index_expr, None, target)?;
match index_type {
Type::Int(_) | Type::UInt(_) => (),
_ => return type_error_result(&iop.span, format!("An expression of type {}, cannot be used to index something. Only integers are supported.", index_type))
}
let typ = match target_type {
Type::Pointer(ref inner) => inner.deref().clone(),
Type::Slice(ref st) => st.element_type.clone(),
Type::Array(ref at) => at.element_type.clone(),
_ => return type_error_result(&iop.span, format!("Cannot an index an expression of type {}", target_type)),
};
iop.typ = typ.clone();
Ok(typ)
}
fn to_regular_assign(a: &mut Assign, int_size: IntSize)
{
let op = match a.operator {
AssignOperator::Assign => return,
AssignOperator::Add => BinaryOperator::Add,
AssignOperator::Sub => BinaryOperator::Sub,
AssignOperator::Mul => BinaryOperator::Mul,
AssignOperator::Div => BinaryOperator::Div,
AssignOperator::And => BinaryOperator::And,
AssignOperator::Or => BinaryOperator::Or,
};
let left = match a.left {
AssignTarget::Var(ref nr) => Expression::NameRef(nr.clone()),
AssignTarget::MemberAccess(ref ma) => Expression::MemberAccess(Box::new(ma.clone())),
AssignTarget::Dereference(ref d) => Expression::Dereference(Box::new(d.clone())),
AssignTarget::IndexOperation(ref i) => Expression::IndexOperation(Box::new(i.clone())),
};
let right = bin_op_with_type(op, left, a.right.clone(), a.right.span(), a.right.get_type(int_size));
a.operator = AssignOperator::Assign;
a.right = right;
}
fn type_check_assign(ctx: &mut TypeCheckerContext, a: &mut Assign, target: &Target) -> TypeCheckResult
{
let dst_type = match a.left {
AssignTarget::Var(ref mut nr) => {
type_check_name(ctx, nr, None)?;
if !ctx.resolve(&nr.name).map(|rn| rn.mutable).unwrap_or(false) {
return type_error_result(&nr.span, format!("Attempting to modify non mutable variable {}", nr.name));
}
nr.typ.clone()
}
AssignTarget::MemberAccess(ref mut ma) => {
type_check_member_access(ctx, ma, target)?;
if !is_result_mutable(ctx, &ma.left) {
return type_error_result(&ma.span, "Attempting to modify non mutable expression");
}
ma.typ.clone()
}
AssignTarget::Dereference(ref mut d) => {
type_check_dereference(ctx, d, target)?;
if !is_result_mutable(ctx, &d.inner) {
return type_error_result(&d.span, "Attempting to modify non mutable expression");
}
d.typ.clone()
}
AssignTarget::IndexOperation(ref mut iop) => {
type_check_index_operation(ctx, iop, target)?
}
};
type_check_with_conversion(ctx, &mut a.right, &dst_type, target)?;
match a.operator {
AssignOperator::Assign => (),
AssignOperator::Add |
AssignOperator::Sub |
AssignOperator::Mul |
AssignOperator::Div => {
if !dst_type.is_numeric() {
return type_error_result(&a.span, format!("Operator {} is only supported on numeric types", a.operator));
}
}
AssignOperator::And |
AssignOperator::Or => {
if dst_type != Type::Bool {
return type_error_result(&a.span, format!("Operator {} is only supported on booleans", a.operator))
}
}
}
to_regular_assign(a, target.int_size); // Convert to a regular assign, for code generation
valid(Type::Void)
}
fn type_check_while(ctx: &mut TypeCheckerContext, w: &mut WhileLoop, target: &Target) -> TypeCheckResult
{
type_check_with_conversion(ctx, &mut w.cond, &Type::Bool, target)?;
type_check_expression(ctx, &mut w.body, None, target)?;
valid(Type::Void)
}
fn type_check_for(ctx: &mut TypeCheckerContext, f: &mut ForLoop, target: &Target) -> TypeCheckResult
{
let typ = type_check_expression(ctx, &mut f.iterable, None, target)?;
match typ
{
// Iterable
Type::String | Type::Array(_) | Type::Slice(_) => {
ctx.enter_scope(None);
let element_type = if let Some(et) = typ.get_element_type() {
et
} else {
return type_error_result(&f.span, format!("Cannot determine type of {}", f.loop_variable))
};
f.loop_variable_type = element_type.clone();
ctx.add(Symbol::new(&f.loop_variable, &element_type, false, &f.span, SymbolType::Normal))?;
type_check_expression(ctx, &mut f.body, None, target)?;
valid(Type::Void)
},
_ => type_error_result(&f.span, format!("Cannot iterate over expressions of type {}", typ)),
}
}
fn type_check_cast(ctx: &mut TypeCheckerContext, c: &mut TypeCast, target: &Target) -> TypeCheckResult
{
let inner_type = type_check_expression(ctx, &mut c.inner, None, target)?;
match (inner_type, &c.destination_type)
{
(Type::Int(_), &Type::UInt(_)) |
(Type::Int(_), &Type::Float(_)) |
(Type::UInt(_), &Type::Int(_)) |
(Type::UInt(_), &Type::Float(_)) |
(Type::Float(_), &Type::Int(_)) |
(Type::Float(_), &Type::UInt(_)) => valid(c.destination_type.clone()),
(Type::Pointer(_), &Type::Pointer(ref to)) if *to.deref() == Type::Void => valid(c.destination_type.clone()),
(Type::Pointer(ref from), &Type::Pointer(_)) if *from.deref() == Type::Void => valid(c.destination_type.clone()),
(Type::Pointer(_), &Type::Bool) => valid(Type::Bool),
(Type::Array(ref at), &Type::Pointer(ref to)) if at.element_type == *to.deref() => valid(c.destination_type.clone()),
(inner_type, _) => type_error_result(&c.span, format!("Cast from type {} to type {} is not allowed", inner_type, c.destination_type))
}
}
fn type_check_compiler_call(ctx: &mut TypeCheckerContext, cc: &mut CompilerCall, type_hint: Option<&Type>, target: &Target) -> TypeCheckResult
{
match *cc {
CompilerCall::SizeOf(ref mut typ, ref span) => {
if resolve_type(ctx, typ) == TypeResolved::No {
type_error_result(span, format!("Unable to resolve type {}", typ))
} else {
valid(target.native_uint_type.clone())
}
}
CompilerCall::Slice{ref mut data, ref mut len, ref mut typ, ref span} => {
let data_type = if let Some(&Type::Slice(ref st)) = type_hint {
let data_ptr_type = ptr_type(st.element_type.clone());
type_check_expression(ctx, data, Some(&data_ptr_type), target)?
} else {
type_check_expression(ctx, data, None, target)?
};
type_check_with_conversion(ctx, len, &target.native_uint_type, target)?;
if let Type::Pointer(ref inner) = data_type {
*typ = slice_type(inner.deref().clone());
valid(typ.clone())
} else {
type_error_result(span, format!("The first argument of @slice, must be a pointer, not a {}", data_type))
}
}
}
}
fn type_check_literal(ctx: &mut TypeCheckerContext, lit: &mut Literal, type_hint: Option<&Type>, target: &Target) -> TypeCheckResult
{
match *lit {
Literal::Array(ref mut a) => type_check_array_literal(ctx, a, target),
Literal::NullPtr(ref span, ref mut typ) => {
if let Some(&Type::Pointer(ref inner_type)) = type_hint {
*typ = inner_type.deref().clone();
valid(ptr_type(typ.clone()))
} else if *typ != Type::Unknown {
type_error_result(span, "Unable to determine type of null expression")
} else {
valid(ptr_type(typ.clone()))
}
}
_ => {
let typ = lit.get_type();
match type_hint {
None => valid(typ),
Some(expected) if typ == *expected => valid(typ),
Some(expected) => {
if let Some(new_lit) = lit.try_convert(expected) {
replace_by(Expression::Literal(new_lit))
} else {
valid(typ)
}
}
}
}
}
}
pub fn type_check_expression(ctx: &mut TypeCheckerContext, e: &mut Expression, type_hint: Option<&Type>, target: &Target) -> CompileResult<Type>
{
let type_check_result = match *e
{
Expression::UnaryOp(ref mut op) => type_check_unary_op(ctx, op, target),
Expression::BinaryOp(ref mut op) => type_check_binary_op(ctx, op, target),
Expression::Literal(ref mut lit) => type_check_literal(ctx, lit, type_hint, target),
Expression::Call(ref mut c) => type_check_call(ctx, c, target),
Expression::NameRef(ref mut nr) => type_check_name(ctx, nr, type_hint),
Expression::Match(ref mut m) => type_check_match(ctx, m, target),
Expression::Lambda(ref mut l) => type_check_lambda(ctx, l, type_hint, target),
Expression::Bindings(ref mut l) => {
for b in &mut l.bindings {
type_check_binding(ctx, b, target)?;
}
valid(Type::Void)
},
Expression::If(ref mut i) => type_check_if(ctx, i, type_hint, target),
Expression::Block(ref mut b) => type_check_block(ctx, b, type_hint, target),
Expression::StructInitializer(ref mut si) => type_check_struct_initializer(ctx, si, target),
Expression::MemberAccess(ref mut sma) => type_check_member_access(ctx, sma, target),
Expression::New(ref mut n) => type_check_new(ctx, n, type_hint, target),
Expression::Delete(ref mut d) => type_check_delete(ctx, d, type_hint, target),
Expression::ArrayToSlice(ref mut ats) => type_check_array_to_slice(ctx, ats, type_hint, target),
Expression::AddressOf(ref mut a) => type_check_address_of(ctx, a, target),
Expression::Dereference(ref mut d) => type_check_dereference(ctx, d, target),
Expression::Assign(ref mut a) => type_check_assign(ctx, a, target),
Expression::While(ref mut w) => type_check_while(ctx, w, target),
Expression::For(ref mut f) => type_check_for(ctx, f, target),
Expression::Void => valid(Type::Void),
Expression::Nil(ref mut nt) => {
if let Some(typ) = type_hint {
if let Type::Optional(_) = *typ {
nt.typ = typ.clone();
}
}
valid(nt.typ.clone())
},
Expression::OptionalToBool(ref mut inner) => {
let inner_type = type_check_expression(ctx, inner, None, target)?;
if !inner_type.is_optional() {
type_error_result(&inner.span(), "Expecting optional type")
} else {
valid(Type::Bool)
}
}
Expression::ToOptional(ref mut t) => {
type_check_expression(ctx, &mut t.inner, None, target)?;
valid(t.optional_type.clone())
},
Expression::Cast(ref mut t) => type_check_cast(ctx, t, target),
Expression::CompilerCall(ref mut cc) => type_check_compiler_call(ctx, cc, type_hint, target),
Expression::IndexOperation(ref mut iop) => valid(type_check_index_operation(ctx, iop, target)?),
Expression::Return(ref mut r) => {
if let Some(return_type) = ctx.get_function_return_type() {
type_check_with_conversion(ctx, &mut r.expression, &return_type, target)?;
valid(Type::Void)
} else {
type_error_result(&r.span, "return expression outside of a function")
}
},
};
match type_check_result
{
Ok(TypeCheckAction::Valid(typ)) => Ok(typ),
Ok(TypeCheckAction::ReplaceBy(expr)) => {
*e = expr;
type_check_expression(ctx, e, type_hint, target)
},
Err(e) => Err(e),
}
}
pub fn type_check_module(module: &mut Module, target: &Target, imports: &ImportMap) -> CompileResult<()>
{
loop {
let mut ctx = TypeCheckerContext::new(ImportSymbolResolver::ImportMap(imports));
resolve_types(&mut ctx, module, target)?;
for global in module.globals.values_mut() {
if global.typ == Type::Unknown {
global.typ = type_check_expression(&mut ctx, &mut global.init, None, target)?;
ctx.add(Symbol::new(&global.name, &global.typ, global.mutable, &global.span, SymbolType::Global))?;
}
}
for f in module.functions.values_mut() {
if !f.type_checked {
type_check_function(&mut ctx, f, target)?;
}
}
let count = module.functions.len();
instantiate_generics(module, &mut ctx, imports, target)?;
// As long as we are adding new generic functions, we need to type check the module again
if count == module.functions.len() {
break;
}
}
module.type_checked = true;
Ok(())
} | 38.368272 | 164 | 0.57232 |
17469dbb7418539b8c23faa5008a1aa889a25409 | 176 | swift | Swift | DouYuZB/Classes/Home/Model/RZZGameModel.swift | rzz09517001/dYZB | 11dc4fd06e75e67fbecb0d814aa737256f231c98 | [
"MIT"
] | null | null | null | DouYuZB/Classes/Home/Model/RZZGameModel.swift | rzz09517001/dYZB | 11dc4fd06e75e67fbecb0d814aa737256f231c98 | [
"MIT"
] | null | null | null | DouYuZB/Classes/Home/Model/RZZGameModel.swift | rzz09517001/dYZB | 11dc4fd06e75e67fbecb0d814aa737256f231c98 | [
"MIT"
] | null | null | null | //
// RZZGameModel.swift
// DouYuZB
//
// Created by 任志忠 on 2019/1/6.
// Copyright © 2019 rzz. All rights reserved.
//
import UIKit
class RZZGameModel: RZZBaseModel {
}
| 12.571429 | 46 | 0.664773 |
76c896ca19c55938155ee64f32f45a9afaf05ab7 | 356 | h | C | Chapitre 8 - Avec Assimp/PetitMoteur3D/ITargetComponentInterface.h | KeikakuB/grand-turtle-racing | b9a19ac1d9056ff582a63e2a5e4782b6fdc4d53b | [
"Apache-2.0"
] | null | null | null | Chapitre 8 - Avec Assimp/PetitMoteur3D/ITargetComponentInterface.h | KeikakuB/grand-turtle-racing | b9a19ac1d9056ff582a63e2a5e4782b6fdc4d53b | [
"Apache-2.0"
] | null | null | null | Chapitre 8 - Avec Assimp/PetitMoteur3D/ITargetComponentInterface.h | KeikakuB/grand-turtle-racing | b9a19ac1d9056ff582a63e2a5e4782b6fdc4d53b | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Meta.h"
#include "GameObject.h"
namespace PM3D
{
class ITargetComponentInterface
{
public:
virtual GameObject* GetTarget() = 0;
virtual void SetTarget(GameObject::id_type t) = 0;
virtual ~ITargetComponentInterface() = default;
};
namespace meta
{
REGISTER_INTERFACE_H_ID(ITargetComponentInterface);
}
} | 19.777778 | 55 | 0.716292 |
700f713560a9905295e45a0c01acd9601a19db93 | 585 | swift | Swift | IDFAViewer/ViewController.swift | sapphiredev/IDFAViewer | 555819a9f4d3b620d1c576b510aba8a9313d7d62 | [
"MIT"
] | null | null | null | IDFAViewer/ViewController.swift | sapphiredev/IDFAViewer | 555819a9f4d3b620d1c576b510aba8a9313d7d62 | [
"MIT"
] | null | null | null | IDFAViewer/ViewController.swift | sapphiredev/IDFAViewer | 555819a9f4d3b620d1c576b510aba8a9313d7d62 | [
"MIT"
] | null | null | null | //
// ViewController.swift
// IDFAViewer
//
// Created by DongShin Lee on 23/05/2019.
// Copyright © 2019 sapphire. All rights reserved.
//
import UIKit
import AdSupport
class ViewController: UIViewController {
@IBOutlet weak var enabledLabel: UILabel!
@IBOutlet weak var idfaText: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let m = ASIdentifierManager.shared();
enabledLabel.text = m.isAdvertisingTrackingEnabled ? "enabled" : "disabled";
idfaText.text = m.advertisingIdentifier.uuidString;
}
}
| 23.4 | 84 | 0.680342 |
6d99c249d861e4398e1ebb4295f22890b2eb75cf | 4,508 | sql | SQL | discovery-server/src/test/resources/sql/test_sales_datasource.sql | mondeique/metatron-discovery | b3a345d6bbfee062bb1530d276305b9a3b60d418 | [
"Apache-2.0"
] | 3,702 | 2018-07-27T07:55:44.000Z | 2022-03-16T09:20:26.000Z | discovery-server/src/test/resources/sql/test_sales_datasource.sql | ucrystal/metatron-discovery | 5864eab9783f993394ef1747f428e95aa9c8abf0 | [
"Apache-2.0"
] | 3,780 | 2018-08-12T06:11:41.000Z | 2022-03-31T03:02:33.000Z | discovery-server/src/test/resources/sql/test_sales_datasource.sql | ucrystal/metatron-discovery | 5864eab9783f993394ef1747f428e95aa9c8abf0 | [
"Apache-2.0"
] | 306 | 2018-08-10T08:00:08.000Z | 2022-03-17T01:39:40.000Z | INSERT INTO datasource(id, ds_name, ds_alias, ds_owner_id, ds_desc, ds_filter_at_select, ds_type, ds_conn_type, ds_granularity, ds_status, ds_published, version, created_time, created_by, modified_time, modified_by) values
('ds-sales-for-test', 'sale_02', 'sales', 'polaris', 'sales data (2011~2014)', true, 'MASTER', 'ENGINE', 'DAY', 'ENABLED', true, 1.0, NOW(), 'polaris', NOW(), 'polaris');
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037028, 'ds-sales-for-test', 0, 'OrderDate', 'TIMESTAMP', 'TIMESTAMP' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037001, 'ds-sales-for-test', 1, 'Category', 'TEXT', 'DIMENSION' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037002, 'ds-sales-for-test', 2, 'City', 'TEXT', 'DIMENSION' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037003, 'ds-sales-for-test', 3, 'Country', 'TEXT', 'DIMENSION' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037004, 'ds-sales-for-test', 4, 'CustomerName', 'TEXT', 'DIMENSION' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037005, 'ds-sales-for-test', 5, 'Discount', 'DOUBLE', 'MEASURE' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037006, 'ds-sales-for-test', 6, 'OrderID', 'TEXT', 'DIMENSION' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037007, 'ds-sales-for-test', 7, 'PostalCode', 'TEXT', 'DIMENSION' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037008, 'ds-sales-for-test', 8, 'ProductName', 'TEXT', 'DIMENSION' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037009, 'ds-sales-for-test', 9, 'Profit', 'DOUBLE', 'MEASURE' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037010, 'ds-sales-for-test', 10, 'Quantity', 'TEXT', 'DIMENSION' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037011, 'ds-sales-for-test', 11, 'Region', 'TEXT', 'DIMENSION' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037012, 'ds-sales-for-test', 12, 'Sales', 'DOUBLE', 'MEASURE' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037013, 'ds-sales-for-test', 13, 'Segment', 'TEXT', 'DIMENSION' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type, field_format ) values(11037014, 'ds-sales-for-test', 14, 'ShipDate', 'TIMESTAMP', 'DIMENSION', 'yyyy. MM. dd.');
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037015, 'ds-sales-for-test', 15, 'ShipMode', 'TEXT', 'DIMENSION' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037016, 'ds-sales-for-test', 16, 'State', 'TEXT', 'DIMENSION' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037017, 'ds-sales-for-test', 17, 'Sub-Category', 'TEXT', 'DIMENSION' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037018, 'ds-sales-for-test', 18, 'DaystoShipActual', 'DOUBLE', 'MEASURE' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037019, 'ds-sales-for-test', 19, 'SalesForecast', 'DOUBLE', 'MEASURE' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037020, 'ds-sales-for-test', 20, 'ShipStatus', 'TEXT', 'DIMENSION' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037021, 'ds-sales-for-test', 21, 'DaystoShipScheduled', 'DOUBLE', 'MEASURE' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037022, 'ds-sales-for-test', 22, 'OrderProfitable', 'TEXT', 'DIMENSION' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037023, 'ds-sales-for-test', 23, 'SalesperCustomer', 'DOUBLE', 'MEASURE' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037024, 'ds-sales-for-test', 24, 'ProfitRatio', 'DOUBLE', 'MEASURE' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037025, 'ds-sales-for-test', 25, 'SalesaboveTarget', 'TEXT', 'DIMENSION' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037026, 'ds-sales-for-test', 26, 'latitude', 'LNT', 'DIMENSION' );
INSERT INTO field(id, ds_id, seq, field_name, field_type, bi_type) values(11037027, 'ds-sales-for-test', 27, 'longitude', 'LNG', 'DIMENSION' );
| 140.875 | 222 | 0.718722 |
3a8fffe0c0787d39bfd762aabef6ecae0711be97 | 795 | dart | Dart | lib/convert.dart | TimWhiting/commons | cc9012d9246ab1c9c965425b05753ded43c6d74c | [
"Apache-2.0"
] | null | null | null | lib/convert.dart | TimWhiting/commons | cc9012d9246ab1c9c965425b05753ded43c6d74c | [
"Apache-2.0"
] | null | null | null | lib/convert.dart | TimWhiting/commons | cc9012d9246ab1c9c965425b05753ded43c6d74c | [
"Apache-2.0"
] | null | null | null | //Copyright (C) 2013 Potix Corporation. All Rights Reserved.
//History: Mon, Mar 18, 2013 11:01:44 AM
// Author: tomyeh
library rikulo_convert;
import "dart:async" show Future, Stream;
import "dart:convert";
/** Reads the entire stream as a string using the given [Encoding].
*/
Future<String> readAsString(Stream<List<int>> stream,
{Encoding encoding: utf8}) {
final List<int> result = [];
return stream.listen((data) {
result.addAll(data);
}).asFuture().then((_) {
return encoding.decode(result);
});
}
/** Reads the entire stream as a JSON string using the given [Encoding],
* and then convert to an object.
*/
Future<dynamic> readAsJson(Stream<List<int>> stream,
{Encoding encoding: utf8}) async
=> json.decode(await readAsString(stream, encoding: encoding));
| 29.444444 | 72 | 0.700629 |
455e95cdb859e8b3b043e306457c6d0bbad79af7 | 4,099 | ps1 | PowerShell | LZReview/scripts/start.ps1 | Azure/fta-landingzone | 2a02ab77eb14a18f92c56136b347d1d394d1076d | [
"MIT"
] | 9 | 2021-02-19T01:27:30.000Z | 2021-06-17T19:17:03.000Z | LZReview/scripts/start.ps1 | Azure/fta-landingzone | 2a02ab77eb14a18f92c56136b347d1d394d1076d | [
"MIT"
] | null | null | null | LZReview/scripts/start.ps1 | Azure/fta-landingzone | 2a02ab77eb14a18f92c56136b347d1d394d1076d | [
"MIT"
] | 7 | 2021-02-17T22:31:26.000Z | 2021-12-15T08:20:19.000Z | # Adapted from https://docs.microsoft.com/en-us/azure/log-analytics/log-analytics-data-collector-api
# gist used - https://gist.githubusercontent.com/taddison/d49bd8c6f7fc1d45aa8e7b0906c180ae/raw/a42445b25af483774a01af102dee763889141794/postToLogAnalytics.ps1
##### SCRIPT VARIABLES #####
##### Update as needed #####
## Subscription variables
$subscription = ""
$tenant = ""
## ALA variables
# Replace with your Workspace ID
$customerId = ""
# Replace with your Primary Key
$sharedKey = ""
# Specify the name of the record type that you'll be creating
$LogType = "CommunityWorkbook_V2"
# You can use an optional field to specify the timestamp from the data. If the time field is not specified, Azure Monitor assumes the time is the message ingestion time
$TimeStampField = ""
##### FUNCTIONS - DO NOT CHANGE #####
Function Get-LogAnalyticsSignature {
[cmdletbinding()]
Param (
$customerId,
$sharedKey,
$date,
$contentLength,
$method,
$contentType,
$resource
)
$xHeaders = "x-ms-date:" + $date
$stringToHash = $method + "`n" + $contentLength + "`n" + $contentType + "`n" + $xHeaders + "`n" + $resource
$bytesToHash = [Text.Encoding]::UTF8.GetBytes($stringToHash)
$keyBytes = [Convert]::FromBase64String($sharedKey)
$sha256 = New-Object System.Security.Cryptography.HMACSHA256
$sha256.Key = $keyBytes
$calculatedHash = $sha256.ComputeHash($bytesToHash)
$encodedHash = [Convert]::ToBase64String($calculatedHash)
$authorization = 'SharedKey {0}:{1}' -f $customerId,$encodedHash
return $authorization
}
##### FUNCTIONS - DO NOT CHANGE #####
##### FUNCTIONS - DO NOT CHANGE #####
Function Export-LogAnalytics {
[cmdletbinding()]
Param(
$customerId,
$sharedKey,
$object,
$logType,
$TimeStampField
)
$bodyAsJson = ConvertTo-Json $object
$body = [System.Text.Encoding]::UTF8.GetBytes($bodyAsJson)
$method = "POST"
$contentType = "application/json"
$resource = "/api/logs"
$rfc1123date = [DateTime]::UtcNow.ToString("r")
$contentLength = $body.Length
$signatureArguments = @{
CustomerId = $customerId
SharedKey = $sharedKey
Date = $rfc1123date
ContentLength = $contentLength
Method = $method
ContentType = $contentType
Resource = $resource
}
$signature = Get-LogAnalyticsSignature @signatureArguments
$uri = "https://" + $customerId + ".ods.opinsights.azure.com" + $resource + "?api-version=2016-04-01"
$headers = @{
"Authorization" = $signature;
"Log-Type" = $logType;
"x-ms-date" = $rfc1123date;
"time-generated-field" = $TimeStampField;
}
$response = Invoke-WebRequest -Uri $uri -Method $method -ContentType $contentType -Headers $headers -Body $body -UseBasicParsing
return $response.StatusCode
}
##### FUNCTIONS - DO NOT CHANGE #####
### Connecting to Azure Subscriptions
### Expect an auth window to appear
Connect-AzAccount -Tenant $tenant
$context = Get-AzSubscription -SubscriptionId $subscription -TenantId $tenant
Set-AzContext $context
## Tests that are run based on Folder structure
## add folders for more tests
$TestFolders = @()
$TestFolders += ".\modules\EA\"
## $TestFolders += ".\vms\" ##another sample folder
### DO NOT MODIFY ANYTHING FROM HERE DOWN - YOU WILL BREAK CODE
## Build empty array for Findings
$Findings = @()
# Browse all folders for tests
# Use folder structure and .psm1 files for tests
foreach ($Folder in $TestFolders) {
Write-Host "Exploring $Folder for modules..."
Get-ChildItem -Path $Folder -Recurse | ForEach-Object {
$File = $_
# For each module found, import it and look for all the functions contained
if ($File.Extension -eq ".psm1") {
Write-Host "Found module $($File.BaseName)"
Remove-Module -Name $File.BaseName -ErrorAction SilentlyContinue
Import-Module $File.FullName
$TestFunctions = Get-Command -Module $File.BaseName
# For each function in the module, run it and add the results to the Findings variable
foreach ($TestFunction in $TestFunctions) {
$Findings += & $TestFunction
}
}
}
} | 31.775194 | 168 | 0.688705 |
c54dfb90033f1dca2fa25001276df42a7d81a4ce | 511 | asm | Assembly | programs/oeis/025/A025710.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/025/A025710.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/025/A025710.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A025710: Index of 5^n within sequence of numbers of form 5^i*9^j.
; 1,2,4,7,10,14,19,25,31,38,46,55,64,74,85,96,108,121,135,149,164,180,197,214,232,251,271,291,312,334,356,379,403,428,453,479,506,534,562,591,621,652,683,715,748,781,815,850,886,922,959,997,1036,1075,1115,1156,1198
mov $2,$0
add $2,1
mov $6,$0
lpb $2
mov $0,$6
sub $2,1
sub $0,$2
mov $3,$0
mul $3,2
lpb $0
mov $0,0
mov $5,$3
mul $5,11
sub $5,1
div $5,30
lpe
pow $4,$7
add $4,$5
add $1,$4
lpe
mov $0,$1
| 20.44 | 214 | 0.598826 |
d247f8babffd8d5820167e4e500d3689de0cd527 | 2,032 | php | PHP | resources/views/portofolio/pengalaman/update.blade.php | ivan17051/SI_MonitoringProyek_Laravel | 84293fbe2edfbe3fe3f8f060891744ef6f8a75dc | [
"MIT"
] | null | null | null | resources/views/portofolio/pengalaman/update.blade.php | ivan17051/SI_MonitoringProyek_Laravel | 84293fbe2edfbe3fe3f8f060891744ef6f8a75dc | [
"MIT"
] | 2 | 2021-10-06T19:17:53.000Z | 2022-02-27T07:25:15.000Z | resources/views/portofolio/pengalaman/update.blade.php | ivan17051/SI_MonitoringProyek_Laravel | 84293fbe2edfbe3fe3f8f060891744ef6f8a75dc | [
"MIT"
] | null | null | null | @extends('layouts.header_footer_admin')
@section('content2')
<div class="container border rounded" style="margin-top:15vh; margin-bottom:15vh; box-shadow:0 .15rem 1.75rem 0 rgba(58,59,69,.15) !important;">
<div class="row" style="border-top:solid 5px #f39c12; border-bottom:solid 1px #bdbdbd;">
<div class="col text-center">
<h1 style="margin:30px;">Edit Pengalaman</h1>
</div>
</div>
<form action="/portofolio/pengalaman/edit/{{ $unit->id }}" method="POST" enctype="multipart/form-data">
@csrf
<div class="row" style="margin-top:30px;">
<div class="col form-group">
<label>Kategori</label>
<select class="form-control" name="kategori" placeholder="">
<option value="Pembangunan" @if($unit->kategori == "Pembangunan") selected @endif>Pembangunan</option>
<option value="Desain" @if($unit->kategori == "Desain") selected @endif>Desain</option>
<option value="Renovasi" @if($unit->kategori == "Renovasi") selected @endif>Renovasi</option>
</select>
</div>
</div>
<div class="form-group">
<label>Tahun</label>
<input type="text" class="form-control" name="tahun" value="{{ $unit->tahun }}" required>
</div>
<div class="form-group">
<label>Pengalaman</label>
<textarea class="form-control" name="pengalaman" cols="30" rows="5" required>{{ $unit->pengalaman }}</textarea>
</div>
<div class="d-flex justify-content-center">
<button style="margin: 20px; width:200px;" type="submit" name="submit" class="btn btn-primary">Update Data</button>
<a href="/portofolio/pengalaman" style="margin: 20px; width:200px;" class="btn btn-danger">Batal</a>
</div>
</form>
</div>
@endsection | 53.473684 | 148 | 0.548228 |
40f5eef3fb689ce7fddfdcdf5143473a1bea5faa | 404 | py | Python | src/experiments/visualization/bipartite_graph.py | 1997alireza/Movie-Casting-Problems | df555e57401ec1b120d8e9d3c2d51b1d3a070f21 | [
"MIT"
] | 3 | 2021-04-20T06:02:34.000Z | 2021-04-24T04:16:45.000Z | src/experiments/visualization/bipartite_graph.py | 1997alireza/Movie-Casting-Problems | df555e57401ec1b120d8e9d3c2d51b1d3a070f21 | [
"MIT"
] | null | null | null | src/experiments/visualization/bipartite_graph.py | 1997alireza/Movie-Casting-Problems | df555e57401ec1b120d8e9d3c2d51b1d3a070f21 | [
"MIT"
] | null | null | null | import matplotlib.pyplot as plt
import networkx as nx
def draw_bipartite_graph(graph, first_node_set):
pos = nx.bipartite_layout(graph, first_node_set)
# get adjacency matrix
A = nx.adjacency_matrix(graph)
A = A.toarray()
# plot adjacency matrix
plt.imshow(A, cmap='Greys')
plt.show()
# plot graph visualisation
nx.draw(graph, pos, with_labels=False)
plt.show()
| 25.25 | 52 | 0.69802 |
9e611272680d888f67ae32f2aa1e84d03c205e19 | 4,038 | swift | Swift | testingSnapchatCamera/ViewController.swift | Rudko/Tippy | 82ca9151931b86f7ca424e49653dbbdb57cb0dce | [
"Apache-2.0"
] | null | null | null | testingSnapchatCamera/ViewController.swift | Rudko/Tippy | 82ca9151931b86f7ca424e49653dbbdb57cb0dce | [
"Apache-2.0"
] | null | null | null | testingSnapchatCamera/ViewController.swift | Rudko/Tippy | 82ca9151931b86f7ca424e49653dbbdb57cb0dce | [
"Apache-2.0"
] | null | null | null | //
// ViewController.swift
// testingSnapchatCamera
//
// Created by Grigory Rudko on 9/5/16.
// Copyright © 2016 Grigory Rudko. All rights reserved.
//
import UIKit
import AVFoundation
//import Foundation
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITextFieldDelegate {
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipControl: UISegmentedControl!
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var twoPersons: UILabel!
@IBOutlet weak var threePersons: UILabel!
@IBOutlet weak var fourPersons: UILabel!
@IBOutlet weak var fivePersons: UILabel!
@IBAction func onTap(sender: AnyObject) {
self.textField.resignFirstResponder()
self.tipControl.resignFirstResponder()
}
@IBAction func calculateTip(sender: AnyObject) {
let bill = Double(billField.text!) ?? 0
/* guard tipControl.selectedSegmentIndex >= 0 else {
totalLabel.text = String(format: "$%.2f", bill)
return
} */
let tipPercentages = [0.18, 0.2, 0.25]
let tip = bill * tipPercentages[tipControl.selectedSegmentIndex]
let total = bill + tip
tipLabel.text = String(format: "$%.2f", tip)
totalLabel.text = String(format: "$%.2f", total)
let twoTip = (bill + tip) / 2
let threeTip = (bill + tip) / 3
let fourTip = (bill + tip) / 4
let fiveTip = (bill + tip) / 5
twoPersons.text = String(format: "$%.2f", twoTip)
threePersons.text = String(format: "$%.2f", threeTip)
fourPersons.text = String(format: "$%.2f", fourTip)
fivePersons.text = String(format: "$%.2f", fiveTip)
//self.view.endEditing(true)
}
var captureSession: AVCaptureSession?
var stillImageOutput: AVCaptureStillImageOutput?
var previewLayer: AVCaptureVideoPreviewLayer?
@IBOutlet weak var cameraView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
textField.becomeFirstResponder()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
previewLayer?.frame = cameraView.bounds
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
UIStatusBarStyle.LightContent
captureSession = AVCaptureSession()
captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080
let backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
var error : NSError?
var input: AVCaptureDeviceInput!
do {
input = try AVCaptureDeviceInput(device: backCamera)
} catch let error1 as NSError {
error = error1
input = nil
}
if (error == nil && captureSession?.canAddInput(input) != nil){
captureSession?.addInput(input)
stillImageOutput = AVCaptureStillImageOutput()
stillImageOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]
if (captureSession?.canAddOutput(stillImageOutput) != nil){
captureSession?.addOutput(stillImageOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
cameraView.layer.addSublayer(previewLayer!)
captureSession?.startRunning()
}
}
}
}
| 23.614035 | 127 | 0.598068 |
ea5deea1526ab236f6ab5306b37a92de2767734f | 388 | sql | SQL | apgdiff.tests/src/main/resources/cz/startnet/utils/pgdiff/modify_inherits_drop_oldparent_diff.sql | cb-deepak/pgcodekeeper | 71611194f163d37b456a6f377d97111f1cb23d65 | [
"Apache-2.0"
] | 96 | 2017-12-12T09:35:34.000Z | 2022-03-29T16:56:02.000Z | apgdiff.tests/src/main/resources/cz/startnet/utils/pgdiff/modify_inherits_drop_oldparent_diff.sql | cb-deepak/pgcodekeeper | 71611194f163d37b456a6f377d97111f1cb23d65 | [
"Apache-2.0"
] | 81 | 2017-12-13T08:03:47.000Z | 2022-03-16T08:57:23.000Z | apgdiff.tests/src/main/resources/cz/startnet/utils/pgdiff/modify_inherits_drop_oldparent_diff.sql | cb-deepak/pgcodekeeper | 71611194f163d37b456a6f377d97111f1cb23d65 | [
"Apache-2.0"
] | 16 | 2018-04-23T12:11:22.000Z | 2022-01-12T08:03:11.000Z | SET search_path = pg_catalog;
ALTER TABLE public.parenttable
DROP COLUMN id;
CREATE TABLE public.parenttable2 (
id bigserial NOT NULL
);
ALTER TABLE public.parenttable2 OWNER TO fordfrog;
ALTER TABLE public.testtable
NO INHERIT parenttable;
ALTER TABLE public.testtable
INHERIT parenttable2;
ALTER TABLE public.parenttable
ADD COLUMN field3 information_schema.cardinal_number;
| 19.4 | 54 | 0.81701 |
0b479dbf807c903d09638149ff0de16acee169e3 | 5,827 | py | Python | apis/python_interface_helpers/stk_env.py | davetrollope-fsml/sequence_toolkit | 49495f679aad1d7c134cf8a189cca1e8acc9f4bd | [
"MIT"
] | null | null | null | apis/python_interface_helpers/stk_env.py | davetrollope-fsml/sequence_toolkit | 49495f679aad1d7c134cf8a189cca1e8acc9f4bd | [
"MIT"
] | null | null | null | apis/python_interface_helpers/stk_env.py | davetrollope-fsml/sequence_toolkit | 49495f679aad1d7c134cf8a189cca1e8acc9f4bd | [
"MIT"
] | null | null | null | from stk_sequence import *
from stk_tcp_server import *
from stk_tcp_client import *
from stk_data_flow import *
from stk_options import stk_clear_cb
import time
class stk_callback:
def __init__(self):
self._caller = None
self._mapobj = None
pass
def add_callback_ref(self,caller):
self._caller = caller
def del_callback_ref(self,caller):
if self._caller:
self._caller.delCallback()
def add_callback_map_obj(self,mapobj):
self._mapobj = mapobj
def map_obj(self):
return self._mapobj
def close(self):
if self._caller:
self.del_callback_ref(self._caller)
self._caller = None
def caller(self):
return self._caller
def fd_created(self,df,fd):
pass
def fd_destroyed(self,df,fd):
pass
class stk_dispatcher_cb(stk_dispatch_cb_class):
def __init__(self,env,cbcls):
self.dispatchclass = stk_dispatch_cb_class.__init__(self)
self._cbcls = cbcls
self._env = env
def close(self):
#del self.dispatchclass
#self.dispatchclass = None
#del self.__class__.obj_map[stk_get_service_group_id(self._svcgrp)]
pass
def finddf(self,dfptr):
dfref = stk_ulong_df_to_df_ptr(dfptr)
df = stk_data_flow.find(dfptr)
if df == None:
dftype = stk_data_flow.type(dfptr)
if dftype == STK_TCP_ACCEPTED_FLOW or dftype == STK_TCP_SERVER_FLOW:
df = stk_tcp_server(self._env,None,None,None,dfref)
if dftype == STK_TCP_CLIENT_FLOW:
df = stk_tcp_client(self._env,None,None,None,dfref)
return df
def process_data(self,dfptr,seqptr):
seqref = stk_ulong_seq_to_seq_ptr(seqptr)
seq = stk_sequence.find(seqptr)
if seq == None:
seq = stk_sequence(self._env,None,None,0,0,None,seqref)
# the dfptr here is actually the C pointer converted to a ulong
df = self.finddf(dfptr)
self._cbcls.process_data(df,seq)
seq.unmap()
def process_name_response(self,dfptr,seqptr):
seqref = stk_ulong_seq_to_seq_ptr(seqptr)
seq = stk_sequence.find(seqptr)
if seq == None:
seq = stk_sequence(self._env,None,None,0,0,None,seqref)
# the dfptr here is actually the C pointer converted to a ulong
df = self.finddf(dfptr)
self._cbcls.process_name_response(df,seq)
seq.unmap()
pass
def process_monitoring_response(self,dfptr,seqptr):
pass
def fd_created(self,dfptr,fd):
# the dfptr here is actually the C pointer converted to a ulong
dfref = stk_ulong_df_to_df_ptr(dfptr)
df = stk_data_flow.find(dfptr)
if df == None:
# This sucks....
dftype = stk_data_flow.type(dfptr)
if dftype == STK_TCP_ACCEPTED_FLOW or dftype == STK_TCP_SERVER_FLOW:
df = stk_tcp_server(self._env,None,None,None,dfref)
# Err, UDP doesn't actually have connections so this really
# isn't likely to be needed - why would the app care about udp creations?
#elif dftype == STK_UDP_CLIENT_FLOW:
#df = stk_udp_client(self._env,None,None,None,dfref)
if df:
self._cbcls.fd_created(df,fd)
def fd_destroyed(self,dfptr,fd):
# the dfptr here is actually the C pointer converted to a ulong
dfref = stk_ulong_df_to_df_ptr(dfptr)
df = stk_data_flow.find(dfptr)
if df == None:
dftype = stk_data_flow.type(dfptr)
if dftype == STK_TCP_ACCEPTED_FLOW or dftype == STK_TCP_SERVER_FLOW:
df = stk_tcp_server(self._env,None,None,None,dfref)
if df:
self._cbcls.fd_destroyed(df,fd)
class stk_env:
def __init__(self,envopts):
self.caller = stk_dispatch_cb_caller()
envopts.append_dispatcher(self.caller.get_dispatcher())
self._opts = envopts
self._env = stk_create_env(envopts.ref())
self._dispatcher_stopped = False;
def close(self):
if self._env:
if self._opts:
stk_clear_cb(self._opts.ref(),"dispatcher")
if self.caller:
self.caller.detach_env(self._env)
stk_destroy_env(self._env)
if self.caller:
self.caller.close()
self.caller = None
self._env = None
def ref(self):
return self._env
def get_name_service(self):
return stk_env_get_name_service(self.ref())
def dispatch_timer_pools(self,interval):
stk_env_dispatch_timer_pools(self._env,interval)
def listening_dispatcher(self,df,svcgrp,appcb):
appcb.add_callback_ref(self.caller)
self._dispatcher_stopped = False
if self.caller.env_listening_dispatcher_add_fd(df.ref()) < 0:
return
while self._dispatcher_stopped == False:
self.caller.env_listening_dispatcher(df.ref(),stk_dispatcher_cb(self,appcb).__disown__(),200)
self.caller.env_listening_dispatcher_del_fd(df.ref())
def client_dispatcher_timed(self,appcb,timeout):
if appcb:
appcb.add_callback_ref(self.caller)
self.caller.env_client_dispatcher_timed(self._env,timeout,stk_dispatcher_cb(self,appcb).__disown__())
else:
self.caller.env_client_dispatcher_timed(self._env,timeout,None)
def stop_dispatcher(self):
self._dispatcher_stopped = True;
self.caller.env_stop_dispatching(self._env)
time.sleep(.2)
def terminate_dispatcher(self):
self.caller.env_terminate_dispatcher(self._env)
@classmethod
def append_name_server_dispatcher_cbs(cls,envopts,data_flow_group):
nsopts = envopts.find_option("name_server_options")
nsopts.update_ref(stk_append_name_server_fd_cbs(data_flow_group,nsopts.ref()))
@classmethod
def remove_name_server_dispatcher_cbs(cls,envopts,data_flow_group):
dfopts = envopts.find_option(data_flow_group + "_options")
if dfopts != None:
dfopts.remove_dispatcher_fd_cbs()
else:
envopts.remove_dispatcher_fd_cbs()
@classmethod
def append_monitoring_dispatcher_cbs(cls,envopts,data_flow_group):
envopts.update_ref(stk_append_monitoring_fd_cbs(data_flow_group,envopts.ref()))
@classmethod
def remove_monitoring_dispatcher_cbs(cls,envopts,data_flow_group):
dfopts = envopts.find_option(data_flow_group + "_options")
if dfopts != None:
dfopts.remove_dispatcher_fd_cbs()
@classmethod
def log(cls,level,message):
stk_log(level,message)
@classmethod
def debug(cls,component,message):
stk_debug(component,message)
| 34.276471 | 104 | 0.763686 |
ddcacb3ccecb7f7d143ac114138a3abca9d9c011 | 11,584 | php | PHP | app/Http/Controllers/HomeController.php | madhusanka2016/medonline | 1582f44810dc32c4ef859336d3b4c309f877cfdf | [
"MIT"
] | null | null | null | app/Http/Controllers/HomeController.php | madhusanka2016/medonline | 1582f44810dc32c4ef859336d3b4c309f877cfdf | [
"MIT"
] | null | null | null | app/Http/Controllers/HomeController.php | madhusanka2016/medonline | 1582f44810dc32c4ef859336d3b4c309f877cfdf | [
"MIT"
] | null | null | null | <?php
namespace App\Http\Controllers;
use PDF;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
//Common
public function orderinvoice(Request $request)
{
dd($request);
$order = $request->input('order');
$orderdes = DB::select("select * from orders where id='" . $order . "' ");
$details = DB::select("select * from cart where orderid='" . $order . "' ");
//dd($Jobid);
$pdf = PDF::loadView('partials.invoiceorder', array('Jobid' => $order, 'order' => $orderdes, 'details' => $details));
//dd($pdf);
return $pdf->download($order . '.pdf');
}
//USers Parts
public function indexid($id)
{
$details = DB::select("SELECT * FROM users where email='" . $id . "'");
return view('profile', ['details' => $details]);
}
public function index()
{
return view('profilelog');
}
public function shoppingcart($id)
{
$cart = DB::select("SELECT * FROM cart where user='" . $id . "' AND state='cart' ");
$order = DB::select("SELECT orderid FROM orders ");
//dd($order);
$payment = DB::select("SELECT * FROM payment where user='" . $id . "'");
$total=0;
return view('user.cart', ['id' => $id , 'total' => $total , 'cart' => $cart, 'order' => $order, 'payment' => $payment]);
}
public function deletecart(Request $request)
{
//dd($request);
$id = $request->input('item');
$user = $request->input('user');
DB::table('cart')
->where('id',$id)
->delete();
return redirect('/shoppingcart/'.$user.'');
}
public function userorder($id)
{
$orders = DB::select("SELECT * FROM orders where user='" . $id . "'");
return view('user.order', ['id' => $id, 'orders' => $orders ]);
}
public function mypayments($id)
{
$payment = DB::select("SELECT * FROM payment where user='" . $id . "'");
// $items= 5;
return view('user.payment', ['payment' => $payment]);
}
public function myprescriptions($id)
{
$pres = DB::select("SELECT * FROM prec where user='" . $id . "'");
return view('user.prescription', ['pres' => $pres]);
}
public function addpresc(Request $request)
{
//dd($request);
$topic = $request->input('topic');
$desc = $request->input('desc');
$link = $request->input('link');
$payment = $request->input('payment');
$repeat = $request->input('repeat');
$state = $request->input('state');
$user = $request->input('user');
DB::table('prec')
->Insert(['user' => $user,'topic' => $topic, 'desc' => $desc , 'link' => $link, 'payment' => $payment, 'repeat' => $repeat, 'state' => $state]);
$pres = DB::select("SELECT * FROM prec where user='" . $user . "'");
return redirect('/myprescriptions/'.$user.'');
}
public function addtocart(Request $request)
{
//dd($request);
$name = $request->input('name');
$id = $request->input('id');
$price = $request->input('price');
$qty = $request->input('qty');
$user = $request->input('user');
$cat = $request->input('cat');
$state = $request->input('state');
DB::table('cart')
->Insert(['i_name' => $name, 'user' => $user , 'i_id' => $id, 'i_qty' => $qty, 'i_price' => $price , 'state' => $state]);
$proArr = ["Prescription Medicine", "Diabetes", "Home Medicine", "First Aid", "Mother & Baby", "Wellness", "Personal Care", "Skin Care", "Health Care", "Pet Care", "Supplements"];
$catArr = ["Prescription Medicine" => 1 , "Diabetes" => 2, "Home Medicine" => 3, "First Aid" => 4, "Mother & Baby" => 5, "Wellness" =>6 , "Personal Care" => 7, "Skin Care" => 8 , "Health Care" => 9, "Pet Care" => 10 , "Supplements" => 11];
if (in_array($cat, $proArr)) {
$catno = $catArr[$cat];
$items = DB::select("SELECT * FROM item where i_cat='" . $catno . "'");
$Title=$cat;
// $items= 5;
return view('product', ['items' => $items,'Title' => $Title,'catnum' => $catno ]);
}
}
public function addpayment(Request $request)
{
dd($request);
$owner = $request->input('owner');
$type = $request->input('type');
$card = $request->input('card');
$user = $request->input('user');
$exp = $request->input('exp');
DB::table('payment')
->Insert(['user' => $user, 'type' => $type , 'card' => $card, 'owner' => $owner, 'exp' => $exp]);
return redirect('/mypayments/'.$user.'');
}
public function purchase(Request $request)
{
//dd($request);
$pay = $request->input('pay');
$order = $request->input('order');
$price = $request->input('price');
$user = $request->input('user');
$state = $request->input('state');
$oldstate = 'cart';
$newstate = 'order';
DB::table('orders')
->Insert(['user' => $user,'orderid' => $order,'price' => $price,'state' => $state,'payid' => $pay]);
DB::table('cart')
->where(['user' => $user,'state' => $oldstate])
->update(['orderid' => $order, 'state' => $newstate]);
$orders = DB::select("SELECT * FROM orders where user='" . $user . "'");
return view('user.order', ['id' => $user, 'orders' => $orders ]);
}
public function vieworderuser($id)
{
$details = DB::select("SELECT * FROM cart where orderid ='" . $id . "'");
$orders = DB::select("SELECT * FROM orders where orderid='" . $id . "'");
return view('user.vieworder', ['orders' => $orders, 'details' => $details]);
}
//Admin part
public function admin()
{
$orders = DB::select("SELECT * FROM orders ORDER BY id DESC LIMIT 5");
$items = DB::select("SELECT * FROM item ORDER BY i_qty ASC LIMIT 5");
return view('admin.index', ['items' => $items ,'orders' => $orders]);
}
public function additems()
{
return view('admin.add');
}
public function items()
{
$items = DB::select("SELECT * FROM item ");
// $items= 5;
return view('admin.items', ['items' => $items]);
}
public function recent()
{
$orders = DB::select("SELECT * FROM orders ");
return view('admin.recent', ['orders' => $orders ]);
}
public function backup()
{
return view('admin.backup');
}
public function additemdb(Request $request)
{
//dd($request);
$name = $request->input('name');
$cat = $request->input('cat');
$brand = $request->input('brand');
$desc = $request->input('desc');
$price = $request->input('price');
$qty = $request->input('qty');
$img = $request->input('img');
DB::table('item')
->Insert(['i_name' => $name, 'i_cat' => $cat , 'i_brand' => $brand, 'i_des' => $desc, 'i_qty' => $qty, 'i_price' => $price, 'i_img' => $img]);
return view('admin.add');
}
public function addqty(Request $request)
{
// dd($request);
$qty = $request->input('qty');
$stock = $request->input('stock');
$id = $request->input('item');
$newstock=$qty+$stock;
DB::table('item')
->where(['id' => $id])
->update([ 'i_qty' => $newstock]);
return redirect('/items/');
}
public function changeitem(Request $request)
{
//dd($request);
$name = $request->input('name');
$id = $request->input('id');
$cat = $request->input('cat');
$brand = $request->input('brand');
$desc = $request->input('desc');
$price = $request->input('price');
$qty = $request->input('qty');
$img = $request->input('img');
DB::table('item')
->where(['id' => $id])
->update(['i_name' => $name, 'i_cat' => $cat , 'i_brand' => $brand, 'i_des' => $desc, 'i_qty' => $qty, 'i_price' => $price, 'i_img' => $img]);
return redirect('/items/');
}
public function deleteitem(Request $request)
{
//dd($request);
$id = $request->input('item');
DB::table('item')
->where('id',$id)
->delete(); return redirect('/items/');
}
//Cashier Part
public function cashier()
{
$orders = DB::select("SELECT * FROM orders ORDER BY id DESC LIMIT 5");
$items = DB::select("SELECT * FROM item ORDER BY i_qty ASC LIMIT 5");
return view('cashier.index', ['items' => $items ,'orders' => $orders]);
}
public function uporders()
{
$orders = DB::select("SELECT * FROM orders where state='Processing'");
return view('cashier.uporders', ['orders' => $orders ]);
}
public function uppres()
{
$pres = DB::select("SELECT * FROM prec WHERE state = 'Processing'");
return view('cashier.uppres', ['pres' => $pres]);
}
public function viewpres($id)
{
$pres = DB::select("SELECT * FROM prec where id ='" . $id . "'");
$med = DB::select("SELECT * FROM item where i_cat ='1'");
$bucket = DB::select("SELECT * FROM precitem where orderid ='" . $id . "'");
return view('cashier.viewpres', ['pres' => $pres, 'med' => $med, 'id' => $id,'bucket' => $bucket ]);
}
public function cusorder()
{
return view('cashier.customorder');
}
public function addtopresc(Request $request)
{
//dd($request);
$orderid = $request->input('orderid');
$i_id = $request->input('i_id');
$name = $request->input('name');
$user = $request->input('user');
$qty = $request->input('qty');
$price = $request->input('price');
DB::table('precitem')
->Insert(['user' => $user, 'orderid' => $orderid , 'i_id' => $i_id, 'i_name' => $name, 'i_qty' => $qty, 'i_price' => $price]);
$pres = DB::select("SELECT * FROM prec where id ='" . $orderid . "'");
$med = DB::select("SELECT * FROM item where i_cat ='1'");
$bucket = DB::select("SELECT * FROM precitem where orderid ='" . $orderid . "'");
return view('cashier.viewpres', ['pres' => $pres, 'med' => $med, 'id' => $orderid ,'bucket' => $bucket ]);
}
public function processprec(Request $request)
{
//dd($request);
$order = $request->input('order');
$price = $request->input('price');
$state = $request->input('state');
;
DB::table('prec')
->where(['id' => $order])
->update(['price' => $price, 'state' => $state]);
return redirect('/uppres');
}
public function processorder(Request $request)
{
//dd($request);
$order = $request->input('order');
$state = $request->input('state');
;
DB::table('orders')
->where(['id' => $order])
->update([ 'state' => $state]);
return redirect('/uporders');
}
}
| 31.0563 | 247 | 0.506302 |
9bad46838351277ca9576f7f21213230f07e5de4 | 378 | js | JavaScript | models/product.model.js | voidzer0-development/Blueprint | f2573b64ed0ff444a618f15455105108905eafe4 | [
"MIT"
] | 1 | 2021-10-10T21:53:30.000Z | 2021-10-10T21:53:30.000Z | models/product.model.js | voidzero-development/Blueprint | f2573b64ed0ff444a618f15455105108905eafe4 | [
"MIT"
] | null | null | null | models/product.model.js | voidzero-development/Blueprint | f2573b64ed0ff444a618f15455105108905eafe4 | [
"MIT"
] | 1 | 2021-12-19T05:50:40.000Z | 2021-12-19T05:50:40.000Z | const mongoose = require('mongoose');
const Schema = mongoose.Schema;
//create schema
const productSchema = new Schema ({
name: {
type: String,
required: true
},
weightInGrams: {
type: Number,
default: 0
},
inStock: {
type: Boolean
},
}
);
//cast schema into model
module.exports = mongoose.model('productModel', productSchema); | 18 | 63 | 0.626984 |
b86bd9eaab335981f3f25f52772edc3b0b455916 | 323 | asm | Assembly | programs/oeis/323/A323229.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 22 | 2018-02-06T19:19:31.000Z | 2022-01-17T21:53:31.000Z | programs/oeis/323/A323229.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 41 | 2021-02-22T19:00:34.000Z | 2021-08-28T10:47:47.000Z | programs/oeis/323/A323229.asm | neoneye/loda | afe9559fb53ee12e3040da54bd6aa47283e0d9ec | [
"Apache-2.0"
] | 5 | 2021-02-24T21:14:16.000Z | 2021-08-09T19:48:05.000Z | ; A323229: a(n) = binomial(2*n, n+1) + 1.
; 1,2,5,16,57,211,793,3004,11441,43759,167961,646647,2496145,9657701,37442161,145422676,565722721,2203961431,8597496601,33578000611,131282408401,513791607421,2012616400081,7890371113951,30957699535777,121548660036301,477551179875953
mov $1,$0
mul $0,2
sub $1,1
bin $0,$1
add $0,1
| 35.888889 | 232 | 0.77709 |
f84ae37fb4bc1220a81e2c3037c00babd9b4435e | 6,694 | lua | Lua | transportation.lua | zerebubuth/ClearTables | 2ad941d226cfb441aebaa7a40514dd469f51d77a | [
"MIT"
] | 25 | 2016-07-08T05:44:54.000Z | 2019-10-11T21:14:05.000Z | transportation.lua | zerebubuth/ClearTables | 2ad941d226cfb441aebaa7a40514dd469f51d77a | [
"MIT"
] | 62 | 2016-07-08T08:05:41.000Z | 2018-04-14T11:12:04.000Z | transportation.lua | zerebubuth/ClearTables | 2ad941d226cfb441aebaa7a40514dd469f51d77a | [
"MIT"
] | 7 | 2016-09-28T15:19:47.000Z | 2019-10-11T11:14:27.000Z | --[[
This file is part of ClearTables
@author Paul Norman <penorman@mac.com>
@copyright 2015-2016 Paul Norman, MIT license
]]--
--[[
Code for the transportation layers. These are some of the most complex. There's a few principles
- Separate tables are needed for roads and rail
- A way might appear in both if it's both a road and rail
- Non-moterized lines are processed to avoid highway=path insanity
]]--
require "common"
local highway = {
motorway = {class="motorway", oneway="yes", motor_access="yes", bicycle="no", ramp="false"},
trunk = {class="trunk", motor_access="yes", ramp="false"},
primary = {class="primary", motor_access="yes", bicycle="yes", ramp="false"},
secondary = {class="secondary", motor_access="yes", bicycle="yes", ramp="false"},
tertiary = {class="tertiary", motor_access="yes", bicycle="yes", ramp="false"},
unclassified = {class="minor", motor_access="yes", bicycle="yes", ramp="false", area=true},
residential = {class="minor", motor_access="yes", bicycle="yes", ramp="false", area=true},
road = {class="unknown", motor_access="yes"},
living_street = {class="minor", motor_access="yes"},
motorway_link = {class="motorway", oneway="yes", motor_access="yes", ramp="true"},
trunk_link = {class="trunk", oneway="yes", motor_access="yes", ramp="true"},
primary_link = {class="primary", oneway="yes", motor_access="yes", ramp="true"},
secondary_link = {class="secondary", oneway="yes", motor_access="yes", ramp="true"},
tertiary_link = {class="tertiary", oneway="yes", motor_access="yes", ramp="true"},
service = {class="service", motor_access="yes", bicycle="yes", area=true},
track = {class="track", area=true},
pedestrian = {class="path", motor_access="no", area=true},
path = {class="path", motor_access="no", area=true},
footway = {class="path", motor_access="no", area=true},
cycleway = {class="path", motor_access="no", bicycle="yes", area=true},
steps = {class="path", motor_access="no"}
}
local railway = {
rail = {z=44, class="rail"},
narrow_gauge = {z=42, class="rail"},
preserved = {z=42, class="rail"},
funicular = {z=42, class="rail"},
subway = {z=42, class="transit"},
light_rail = {z=42, class="transit"},
monorail = {z=42, class="transit"},
tram = {z=41, class="transit"}
}
-- Some regions have the annoying habit of using values like RO:urban rather than setting the maxspeed.
-- These are the most common ones
local regional_maxspeed = {
["RO:urban"] = "50",
["RU:urban"] = "60",
["RU:rural"] = "90",
["RO:rural"] = "90",
["RO:trunk"] = "100",
["RU:living_street"] = "20"
}
--- Normalizes speed
-- @param v Speed tag value
-- @return Speed in km/h
function speed (v)
if v == nil then
return nil
end
-- speeds in km/h
if string.find(v, "^%d+%.?%d*$") then
-- Cap speed at 1000 km/h
return v and tonumber(v) < 1000 and v or nil
end
if string.find(v, "^(%d+%.?%d*) ?mph$") then
return tostring(tonumber(string.match(v, "^(%d+%.?%d*) ?mph$"))*1.609)
end
if regional_maxspeed[v] then
-- calling speed() allows the value in the table to be in mph
return speed(regional_maxspeed[v])
end
return nil
end
--- Normalizes lane tags
-- @param v The lane tag value
-- @return An integer > 0 or nil for the lane tag
function lanes (v)
return v and string.find(v, "^%d+$") and tonumber(v) < 100 and tonumber(v) > 0 and v or nil
end
function brunnel (tags)
return isset(tags["bridge"]) and "bridge" or isset(tags["tunnel"]) and "tunnel" or nil
end
function accept_road (tags)
return highway[tags["highway"]]
end
function accept_rail (tags)
return railway[tags["railway"]]
end
function accept_road_point (tags)
return tags["highway"] and (
tags["highway"] == "crossing" or
tags["highway"] == "traffic_signals" or
tags["highway"] == "motorway_junction")
end
function accept_road_area (tags)
return highway[tags["highway"]] and highway[tags["highway"]].area
end
function transform_road_point (tags)
local cols = {}
cols.type = tags["highway"]
cols.name = tags["name"]
cols.names = names(tags)
cols.ref = tags["ref"]
return cols
end
function transform_road (tags)
local cols = {}
cols.name = tags["name"]
cols.names = names(tags)
cols.refs = split_list(tags["ref"])
if highway[tags["highway"]] then
cols.class = highway[tags["highway"]]["class"]
cols.ramp = highway[tags["highway"]]["ramp"]
cols.oneway = oneway(tags["oneway"] or highway[tags["highway"]]["oneway"] or (tags["junction"] == "roundabout" and "yes") or nil)
-- Build access tags, taking the first non-nil value from the access hiarchy, or if that fails, taking a sane default
cols.motor_access = access(tags["motor_vehicle"] or
tags["vehicle"] or tags["access"] or highway[tags["highway"]]["motor_access"])
cols.bicycle_access = access(tags["bicycle"] or
tags["vehicle"] or tags["access"] or highway[tags["highway"]]["bicycle_access"])
cols.maxspeed = speed(tags["maxspeed"])
cols.brunnel = brunnel(tags)
cols.layer = layer(tags["layer"])
end
return cols
end
function transform_rail (tags)
local cols = {}
cols.name = tags["name"]
cols.names = names(tags)
if railway[tags["railway"]] then
cols.class = railway[tags["railway"]]["class"]
cols.brunnel = brunnel(tags)
cols.layer = layer(tags["layer"])
if tags["service"] == "spur" or
tags["service"] == "siding" or
tags["service"] == "yard" or
tags["service"] == "crossover" then
cols.service = tags["service"]
end
end
return cols
end
function road_ways (tags, num_keys)
return generic_line_way(tags, accept_road, transform_road)
end
function road_area_ways (tags, num_keys)
return generic_polygon_way(tags, accept_road_area, transform_road) -- uses the same transform functions as lines
end
function road_area_rel_members (tags, member_tags, member_roles, membercount)
return generic_multipolygon_members(tags, member_tags, membercount, accept_road_area, transform_road)
end
function road_points (tags, num_keys)
return generic_node(tags, accept_road_point, transform_road_point)
end
function rail_ways (tags, num_keys)
return generic_line_way(tags, accept_rail, transform_rail)
end
| 35.417989 | 137 | 0.628921 |
ebbf711859d2955233a614dfec5910a91c0ce1c0 | 11,079 | dart | Dart | rm_graphql_client/lib/src/graphql/operations.data.gql.dart | Omar8345/recipe-management-app | f7a2d6c3384b65a46b653a4333a3a4a78280cfe3 | [
"MIT"
] | null | null | null | rm_graphql_client/lib/src/graphql/operations.data.gql.dart | Omar8345/recipe-management-app | f7a2d6c3384b65a46b653a4333a3a4a78280cfe3 | [
"MIT"
] | null | null | null | rm_graphql_client/lib/src/graphql/operations.data.gql.dart | Omar8345/recipe-management-app | f7a2d6c3384b65a46b653a4333a3a4a78280cfe3 | [
"MIT"
] | null | null | null | // GENERATED CODE - DO NOT MODIFY BY HAND
import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import 'package:rm_graphql_client/src/graphql/serializers.gql.dart' as _i1;
part 'operations.data.gql.g.dart';
abstract class GFetchRecipeListData
implements Built<GFetchRecipeListData, GFetchRecipeListDataBuilder> {
GFetchRecipeListData._();
factory GFetchRecipeListData(
[Function(GFetchRecipeListDataBuilder b) updates]) =
_$GFetchRecipeListData;
static void _initializeBuilder(GFetchRecipeListDataBuilder b) =>
b..G__typename = 'query_root';
@BuiltValueField(wireName: '__typename')
String get G__typename;
BuiltList<GFetchRecipeListData_recipes> get recipes;
static Serializer<GFetchRecipeListData> get serializer =>
_$gFetchRecipeListDataSerializer;
Map<String, dynamic> toJson() =>
_i1.serializers.serializeWith(GFetchRecipeListData.serializer, this);
static GFetchRecipeListData fromJson(Map<String, dynamic> json) =>
_i1.serializers.deserializeWith(GFetchRecipeListData.serializer, json);
}
abstract class GFetchRecipeListData_recipes
implements
Built<GFetchRecipeListData_recipes,
GFetchRecipeListData_recipesBuilder> {
GFetchRecipeListData_recipes._();
factory GFetchRecipeListData_recipes(
[Function(GFetchRecipeListData_recipesBuilder b) updates]) =
_$GFetchRecipeListData_recipes;
static void _initializeBuilder(GFetchRecipeListData_recipesBuilder b) =>
b..G__typename = 'recipes';
int get id;
String get name;
@nullable
String get description;
@nullable
String get image_url;
@BuiltValueField(wireName: '__typename')
String get G__typename;
static Serializer<GFetchRecipeListData_recipes> get serializer =>
_$gFetchRecipeListDataRecipesSerializer;
Map<String, dynamic> toJson() => _i1.serializers
.serializeWith(GFetchRecipeListData_recipes.serializer, this);
static GFetchRecipeListData_recipes fromJson(Map<String, dynamic> json) =>
_i1.serializers
.deserializeWith(GFetchRecipeListData_recipes.serializer, json);
}
abstract class GFetchRecipeIngredientsData
implements
Built<GFetchRecipeIngredientsData, GFetchRecipeIngredientsDataBuilder> {
GFetchRecipeIngredientsData._();
factory GFetchRecipeIngredientsData(
[Function(GFetchRecipeIngredientsDataBuilder b) updates]) =
_$GFetchRecipeIngredientsData;
static void _initializeBuilder(GFetchRecipeIngredientsDataBuilder b) =>
b..G__typename = 'query_root';
@BuiltValueField(wireName: '__typename')
String get G__typename;
BuiltList<GFetchRecipeIngredientsData_ingredients> get ingredients;
static Serializer<GFetchRecipeIngredientsData> get serializer =>
_$gFetchRecipeIngredientsDataSerializer;
Map<String, dynamic> toJson() => _i1.serializers
.serializeWith(GFetchRecipeIngredientsData.serializer, this);
static GFetchRecipeIngredientsData fromJson(Map<String, dynamic> json) =>
_i1.serializers
.deserializeWith(GFetchRecipeIngredientsData.serializer, json);
}
abstract class GFetchRecipeIngredientsData_ingredients
implements
Built<GFetchRecipeIngredientsData_ingredients,
GFetchRecipeIngredientsData_ingredientsBuilder> {
GFetchRecipeIngredientsData_ingredients._();
factory GFetchRecipeIngredientsData_ingredients(
[Function(GFetchRecipeIngredientsData_ingredientsBuilder b)
updates]) = _$GFetchRecipeIngredientsData_ingredients;
static void _initializeBuilder(
GFetchRecipeIngredientsData_ingredientsBuilder b) =>
b..G__typename = 'ingredients';
int get id;
String get name;
int get recipe_id;
@BuiltValueField(wireName: '__typename')
String get G__typename;
static Serializer<GFetchRecipeIngredientsData_ingredients> get serializer =>
_$gFetchRecipeIngredientsDataIngredientsSerializer;
Map<String, dynamic> toJson() => _i1.serializers
.serializeWith(GFetchRecipeIngredientsData_ingredients.serializer, this);
static GFetchRecipeIngredientsData_ingredients fromJson(
Map<String, dynamic> json) =>
_i1.serializers.deserializeWith(
GFetchRecipeIngredientsData_ingredients.serializer, json);
}
abstract class GDeleteRecipeData
implements Built<GDeleteRecipeData, GDeleteRecipeDataBuilder> {
GDeleteRecipeData._();
factory GDeleteRecipeData([Function(GDeleteRecipeDataBuilder b) updates]) =
_$GDeleteRecipeData;
static void _initializeBuilder(GDeleteRecipeDataBuilder b) =>
b..G__typename = 'mutation_root';
@BuiltValueField(wireName: '__typename')
String get G__typename;
@nullable
GDeleteRecipeData_delete_recipes_by_pk get delete_recipes_by_pk;
static Serializer<GDeleteRecipeData> get serializer =>
_$gDeleteRecipeDataSerializer;
Map<String, dynamic> toJson() =>
_i1.serializers.serializeWith(GDeleteRecipeData.serializer, this);
static GDeleteRecipeData fromJson(Map<String, dynamic> json) =>
_i1.serializers.deserializeWith(GDeleteRecipeData.serializer, json);
}
abstract class GDeleteRecipeData_delete_recipes_by_pk
implements
Built<GDeleteRecipeData_delete_recipes_by_pk,
GDeleteRecipeData_delete_recipes_by_pkBuilder> {
GDeleteRecipeData_delete_recipes_by_pk._();
factory GDeleteRecipeData_delete_recipes_by_pk(
[Function(GDeleteRecipeData_delete_recipes_by_pkBuilder b) updates]) =
_$GDeleteRecipeData_delete_recipes_by_pk;
static void _initializeBuilder(
GDeleteRecipeData_delete_recipes_by_pkBuilder b) =>
b..G__typename = 'recipes';
int get id;
String get name;
@nullable
String get description;
@nullable
String get image_url;
@BuiltValueField(wireName: '__typename')
String get G__typename;
BuiltList<GDeleteRecipeData_delete_recipes_by_pk_ingredients> get ingredients;
static Serializer<GDeleteRecipeData_delete_recipes_by_pk> get serializer =>
_$gDeleteRecipeDataDeleteRecipesByPkSerializer;
Map<String, dynamic> toJson() => _i1.serializers
.serializeWith(GDeleteRecipeData_delete_recipes_by_pk.serializer, this);
static GDeleteRecipeData_delete_recipes_by_pk fromJson(
Map<String, dynamic> json) =>
_i1.serializers.deserializeWith(
GDeleteRecipeData_delete_recipes_by_pk.serializer, json);
}
abstract class GDeleteRecipeData_delete_recipes_by_pk_ingredients
implements
Built<GDeleteRecipeData_delete_recipes_by_pk_ingredients,
GDeleteRecipeData_delete_recipes_by_pk_ingredientsBuilder> {
GDeleteRecipeData_delete_recipes_by_pk_ingredients._();
factory GDeleteRecipeData_delete_recipes_by_pk_ingredients(
[Function(GDeleteRecipeData_delete_recipes_by_pk_ingredientsBuilder b)
updates]) = _$GDeleteRecipeData_delete_recipes_by_pk_ingredients;
static void _initializeBuilder(
GDeleteRecipeData_delete_recipes_by_pk_ingredientsBuilder b) =>
b..G__typename = 'ingredients';
int get id;
String get name;
int get recipe_id;
@BuiltValueField(wireName: '__typename')
String get G__typename;
static Serializer<GDeleteRecipeData_delete_recipes_by_pk_ingredients>
get serializer =>
_$gDeleteRecipeDataDeleteRecipesByPkIngredientsSerializer;
Map<String, dynamic> toJson() => _i1.serializers.serializeWith(
GDeleteRecipeData_delete_recipes_by_pk_ingredients.serializer, this);
static GDeleteRecipeData_delete_recipes_by_pk_ingredients fromJson(
Map<String, dynamic> json) =>
_i1.serializers.deserializeWith(
GDeleteRecipeData_delete_recipes_by_pk_ingredients.serializer, json);
}
abstract class GInsertRecipeData
implements Built<GInsertRecipeData, GInsertRecipeDataBuilder> {
GInsertRecipeData._();
factory GInsertRecipeData([Function(GInsertRecipeDataBuilder b) updates]) =
_$GInsertRecipeData;
static void _initializeBuilder(GInsertRecipeDataBuilder b) =>
b..G__typename = 'mutation_root';
@BuiltValueField(wireName: '__typename')
String get G__typename;
@nullable
GInsertRecipeData_insert_recipes_one get insert_recipes_one;
static Serializer<GInsertRecipeData> get serializer =>
_$gInsertRecipeDataSerializer;
Map<String, dynamic> toJson() =>
_i1.serializers.serializeWith(GInsertRecipeData.serializer, this);
static GInsertRecipeData fromJson(Map<String, dynamic> json) =>
_i1.serializers.deserializeWith(GInsertRecipeData.serializer, json);
}
abstract class GInsertRecipeData_insert_recipes_one
implements
Built<GInsertRecipeData_insert_recipes_one,
GInsertRecipeData_insert_recipes_oneBuilder> {
GInsertRecipeData_insert_recipes_one._();
factory GInsertRecipeData_insert_recipes_one(
[Function(GInsertRecipeData_insert_recipes_oneBuilder b) updates]) =
_$GInsertRecipeData_insert_recipes_one;
static void _initializeBuilder(
GInsertRecipeData_insert_recipes_oneBuilder b) =>
b..G__typename = 'recipes';
int get id;
String get name;
@nullable
String get description;
@nullable
String get image_url;
@BuiltValueField(wireName: '__typename')
String get G__typename;
BuiltList<GInsertRecipeData_insert_recipes_one_ingredients> get ingredients;
static Serializer<GInsertRecipeData_insert_recipes_one> get serializer =>
_$gInsertRecipeDataInsertRecipesOneSerializer;
Map<String, dynamic> toJson() => _i1.serializers
.serializeWith(GInsertRecipeData_insert_recipes_one.serializer, this);
static GInsertRecipeData_insert_recipes_one fromJson(
Map<String, dynamic> json) =>
_i1.serializers.deserializeWith(
GInsertRecipeData_insert_recipes_one.serializer, json);
}
abstract class GInsertRecipeData_insert_recipes_one_ingredients
implements
Built<GInsertRecipeData_insert_recipes_one_ingredients,
GInsertRecipeData_insert_recipes_one_ingredientsBuilder> {
GInsertRecipeData_insert_recipes_one_ingredients._();
factory GInsertRecipeData_insert_recipes_one_ingredients(
[Function(GInsertRecipeData_insert_recipes_one_ingredientsBuilder b)
updates]) = _$GInsertRecipeData_insert_recipes_one_ingredients;
static void _initializeBuilder(
GInsertRecipeData_insert_recipes_one_ingredientsBuilder b) =>
b..G__typename = 'ingredients';
int get id;
String get name;
int get recipe_id;
@BuiltValueField(wireName: '__typename')
String get G__typename;
static Serializer<GInsertRecipeData_insert_recipes_one_ingredients>
get serializer =>
_$gInsertRecipeDataInsertRecipesOneIngredientsSerializer;
Map<String, dynamic> toJson() => _i1.serializers.serializeWith(
GInsertRecipeData_insert_recipes_one_ingredients.serializer, this);
static GInsertRecipeData_insert_recipes_one_ingredients fromJson(
Map<String, dynamic> json) =>
_i1.serializers.deserializeWith(
GInsertRecipeData_insert_recipes_one_ingredients.serializer, json);
}
| 40.434307 | 80 | 0.784096 |
40087ff6975d48cfe5a328743753504358b14a3e | 5,176 | py | Python | widgets/Config.py | channolanp/QtScript | 7c7f39b7018194b92c1b191bf0ccff3212d3ee53 | [
"MIT"
] | null | null | null | widgets/Config.py | channolanp/QtScript | 7c7f39b7018194b92c1b191bf0ccff3212d3ee53 | [
"MIT"
] | null | null | null | widgets/Config.py | channolanp/QtScript | 7c7f39b7018194b92c1b191bf0ccff3212d3ee53 | [
"MIT"
] | null | null | null | from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
import json
class QConfigWidget(QWidget):
"""A widget that allows adding of QtWidgets into a QFormLayout where the
left column will always be a label matching the name supplied when adding
widgets to the right column. The values of all the QtWidgets added to this
widget using AddWidget can be saved to a JSON file, or loaded from a JSON
file. You can also grab a dictionary of UI element values using GetConfig.
Args:
parent (QWidget): PyQt5 QWidget.
Attributes:
_config (dict): The protected dict containing keys of the user suppplied
labels as names and values of the QWidget in its respective row.
_layout (QLayout): The protected layout that widgets can be added to
using AddWidget
get_mapping (static dict): Allows polymorphic behavior for getting
values from various QWidgets
set_mapping (static dict): Allows polymorphic behavior for setting
values to various QWidgets
"""
get_mapping = {
QLineEdit: QLineEdit.text,
QSpinBox: QSpinBox.value,
QDoubleSpinBox: QDoubleSpinBox.value,
QCheckBox: QCheckBox.isChecked,
QComboBox: QComboBox.currentText,
QSlider: QSlider.value,
QListWidget: QListWidget.currentItem
}
set_mapping = {
QLineEdit: QLineEdit.setText,
QSpinBox: QSpinBox.setValue,
QDoubleSpinBox: QDoubleSpinBox.setValue,
QCheckBox: QCheckBox.setChecked,
QComboBox: QComboBox.setCurrentText,
QSlider: QSlider.value,
QListWidget: QListWidget.setCurrentItem
}
def __init__(self, parent = None):
"""Create a simple Config Widget that handles a QFormLayout where
left column is a QLabel representing the name of the configuration
parameter, and the right column is a QWidget that is its value.
Args:
parent (QWidget): Required for QWidget inheritance.
Returns:
None
"""
super().__init__(parent)
self._config = {}
#Build the save/load button and connect signals
saveButton = QPushButton("Save Config")
saveButton.clicked.connect(self._save)
loadButton = QPushButton("Load Config")
loadButton.clicked.connect(self._load)
#Setup the main layout that will have items added to externally
self._layout = QFormLayout()
self._layout.addRow(saveButton, loadButton)
#Set this widget's layout to the form
self.setLayout(self._layout)
def AddWidget(self, name, control):
"""Add a row of widgets to the form layout.
Args:
name (str): The name that will be shown as a QLabel on the left
column of the form. This format is used for saving/loading config
to/from JSON as well as GetConfig and SetConfig.
control (type): Description of parameter `control`.
Returns:
None
"""
label = QLabel(name)
self._layout.addRow(label,control)
self._config[name] = control
def GetConfig(self):
"""Returns the current values from the UI elements added to this widget.
Returns:
dict{str:dynamic}: Current UI values as UI element string name and
its value depending on widget type
"""
config = {}
for key in self._config:
widget = self._config[key]
config[key] = self.get_mapping[type(widget)](widget)
return config
def SetConfig(self, config):
"""Sets values for all UI elements suppplied in config.
Args:
config (dict{str:dynamic}): A dictionary containing UI element names
and the desired value for each. The value types of the widget must
be respected.
Returns:
None
"""
for key in config:
if key in self._config:
widget = self._config[key]
self.set_mapping[type(widget)](widget, config[key])
else:
print(f'Missing Key {key}, will not add')
def _save(self):
"""This method slots to the save button click signal to open a file
dialog used to save self.GetConfig into a JSON format
Returns:
None: Saves a file on the desktop
"""
filePath,_ = QFileDialog().getSaveFileName(self, 'Save File','','JSON config (*.json)')
if filePath:
with open(filePath, 'w') as f:
json.dump(self.GetConfig(),f, indent=4)
def _load(self):
"""This method slots to the load button click signal to open a file
dialog used to load the configuration from a JSON format and write to
our UI elements using self.SetConfig
Returns:
None
"""
dialog = QFileDialog()
filePath, _ = dialog.getOpenFileName(filter="JSON Config (*.json)")
if filePath:
config = None
with open(filePath, 'r') as f:
config = json.load(f)
self.SetConfig(config)
| 34.972973 | 95 | 0.62442 |
b2ca95eb1885e978f15d93cd274fcde44708c42a | 3,779 | swift | Swift | BMOT_T/Controllers/Juegos/SituacionesViewController.swift | RekonxCarloz/Mobile-App-For-Emotion-Managment-In-Elementary-School-Children | c0286dd0d3970c07a8037c6c0b0c88c7c002e394 | [
"MIT"
] | null | null | null | BMOT_T/Controllers/Juegos/SituacionesViewController.swift | RekonxCarloz/Mobile-App-For-Emotion-Managment-In-Elementary-School-Children | c0286dd0d3970c07a8037c6c0b0c88c7c002e394 | [
"MIT"
] | null | null | null | BMOT_T/Controllers/Juegos/SituacionesViewController.swift | RekonxCarloz/Mobile-App-For-Emotion-Managment-In-Elementary-School-Children | c0286dd0d3970c07a8037c6c0b0c88c7c002e394 | [
"MIT"
] | null | null | null | //
// SituacionesViewController.swift
// BMOT_T
//
// Created by Jonathan Garcica on 05/12/21.
//
import AVKit
import AVFoundation
import Firebase
import UIKit
class SituacionesViewController: UIViewController {
var nombrePerfil:String?
var situacion: Int = 1
var player_item = AVPlayer()
var player_layer = AVPlayerLayer()
var player_repeat = AVQueuePlayer()
var playerLooper : AVPlayerLooper?
var player_itemR : AVPlayerItem?
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
let randomInt = Int.random(in: 1..<5)
situacion = randomInt
print("Numero ramdom: \(randomInt)")
print("Numero situacion: \(randomInt)")
player_item = AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: String(situacion), ofType: "mp4")!))
player_layer = AVPlayerLayer(player: player_item)
player_layer.frame = view.bounds
player_layer.videoGravity = .resizeAspect
view.layer.addSublayer(player_layer)
player_item.play()
}
/*
// MARK: - Metodo para la función de cada botón
*/
//Funcion para mostrar otro video al azar
@IBAction func otroVideoAction(_ sender: UIButton) {
var randomInt = Int.random(in: 1..<5)
print("Numero ramdom otro video: \(randomInt)")
print("Numero situacion otro video: \(randomInt)")
while situacion == randomInt {
randomInt = Int.random(in: 1..<5)
}
situacion = randomInt
//situacion = randomInt
player_item = AVPlayer(url: URL(fileURLWithPath: Bundle.main.path(forResource: String(situacion), ofType: "mp4")!))
player_layer = AVPlayerLayer(player: player_item)
player_layer.frame = view.bounds
player_layer.videoGravity = .resizeAspect
view.layer.addSublayer(player_layer)
player_item.play()
}
//Funcion para repetir video
@IBAction func repetirAction(_ sender: UIButton) {
player_layer = AVPlayerLayer(player: player_repeat)
player_itemR = AVPlayerItem(url: URL(fileURLWithPath: Bundle.main.path(forResource: String(situacion), ofType: "mp4")!))
self.playerLooper = AVPlayerLooper(player: player_repeat, templateItem: player_itemR!)
player_layer.frame = view.bounds
player_layer.videoGravity = .resizeAspect
view.layer.addSublayer(player_layer)
player_repeat.play()
NotificationCenter.default.addObserver(self,
selector: #selector(playerItemDidReachEnd),
name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
object: nil) // Add observer
}
// Notification Handling
@objc func playerItemDidReachEnd(notification: NSNotification) {
player_repeat.seek(to: CMTime.zero)
//player_repeat.play()
player_repeat.pause()
}
// Remove Observer
deinit {
NotificationCenter.default.removeObserver(self)
}
@IBAction func PasarAljuegoAction(_ sender: UIButton) {
performSegue(withIdentifier: K.Segues.gamesSegues.emotionPizza, sender: self)
}
/*
// MARK: - Metodo para la función de enviar los datos a otra vista.
*/
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == K.Segues.gamesSegues.emotionPizza{
let vc = segue.destination as! PizzaGameViewController
vc.nombrePerfil = nombrePerfil
}
}
}
| 34.045045 | 128 | 0.629267 |
2659cc8011690e6cfcab07e87b941fcff60c3e8b | 798 | java | Java | designpatterncomponent/src/main/java/com/bilibili/designpatterncomponent/strategy/Test.java | Chihiro23333/ChidoriX | 7e57171085f4230611cd51db594d3fc619a02603 | [
"Apache-2.0"
] | 2 | 2018-08-31T09:59:20.000Z | 2019-05-29T07:43:31.000Z | designpatterncomponent/src/main/java/com/bilibili/designpatterncomponent/strategy/Test.java | Chihiro23333/ChidoriX | 7e57171085f4230611cd51db594d3fc619a02603 | [
"Apache-2.0"
] | null | null | null | designpatterncomponent/src/main/java/com/bilibili/designpatterncomponent/strategy/Test.java | Chihiro23333/ChidoriX | 7e57171085f4230611cd51db594d3fc619a02603 | [
"Apache-2.0"
] | null | null | null | package com.bilibili.designpatterncomponent.strategy;
public class Test {
/**
* Strategy Pattern
* 策略模式
*
* 定义了算法族,分别封装起来,让他们之间ke可以相互替换,
* 此模式让算法独立于算法的客户
* * @param args
*/
public static void main(String[] args){
Duck redHeadDuck = new RedHeadDuck();
Duck noLifeDuck = new NoLifeDuck();
redHeadDuck.display();
redHeadDuck.swim();
redHeadDuck.fly();
redHeadDuck.quack();
noLifeDuck.display();
noLifeDuck.swim();
noLifeDuck.fly();
noLifeDuck.quack();
//用set方法可以改变不同鸭子的行为,不能飞的木鸭子在替换行为之后能叫和飞行
noLifeDuck.setQuackBehavior(new GuaGuaQuack());
noLifeDuck.setFlyBehavior(new FlyWithWings());
noLifeDuck.quack();
noLifeDuck.fly();
}
}
| 23.470588 | 55 | 0.602757 |
2a235dcd4a7941ea85783bb66e5b2bd7f0966999 | 107 | java | Java | src/org/nasa/posicion/IPosicion.java | felipecardozo/marsexplorer | c399bd0f38b7b726d4a68ae6af6c95ad635b1158 | [
"Apache-2.0"
] | null | null | null | src/org/nasa/posicion/IPosicion.java | felipecardozo/marsexplorer | c399bd0f38b7b726d4a68ae6af6c95ad635b1158 | [
"Apache-2.0"
] | null | null | null | src/org/nasa/posicion/IPosicion.java | felipecardozo/marsexplorer | c399bd0f38b7b726d4a68ae6af6c95ad635b1158 | [
"Apache-2.0"
] | null | null | null | package org.nasa.posicion;
/**
* @author fcardozo
* @version 1.0
*
*/
public interface IPosicion {
}
| 9.727273 | 28 | 0.64486 |
dde21437f5bdd25d44beb1d355bdf89e00710281 | 994 | php | PHP | app/Models/Blog.php | ayao1917/lazy-back | a1a46347ec3c96d8700097f18b14315c2e09a1c5 | [
"MIT"
] | null | null | null | app/Models/Blog.php | ayao1917/lazy-back | a1a46347ec3c96d8700097f18b14315c2e09a1c5 | [
"MIT"
] | null | null | null | app/Models/Blog.php | ayao1917/lazy-back | a1a46347ec3c96d8700097f18b14315c2e09a1c5 | [
"MIT"
] | null | null | null | <?php
/**
* Created by Reliese Model.
* Date: Thu, 01 Nov 2018 09:47:17 +0000.
*/
namespace lazyworker\Models;
use Reliese\Database\Eloquent\Model as Eloquent;
/**
* Class Blog
*
* @property int $id
* @property int $product_id
* @property string $title
* @property string $content
* @property string $author
* @property \Carbon\Carbon $publish_date
* @property \Carbon\Carbon $created
* @property \Carbon\Carbon $modified
*
* @property \Illuminate\Database\Eloquent\Collection $blog_content_images
*
* @package App\Models
*/
class Blog extends Eloquent
{
protected $table = 'blog';
public $timestamps = false;
protected $casts = [
'product_id' => 'int'
];
protected $dates = [
'publish_date',
'created',
'modified'
];
protected $fillable = [
'product_id',
'title',
'content',
'author',
'publish_date',
'created',
'modified'
];
public function blog_content_images()
{
return $this->hasMany(\App\Models\BlogContentImage::class);
}
}
| 17.137931 | 74 | 0.672032 |
0484113a25e0228df319daba9fcc896f2aa1403b | 841 | java | Java | src/main/java/com/ziggeo/ZiggeoWebhooks.java | Ziggeo/ZiggeoJavaSdk | 3deb8caf66ba1796356512825c06181918051047 | [
"Apache-2.0"
] | 1 | 2021-06-07T08:40:31.000Z | 2021-06-07T08:40:31.000Z | src/main/java/com/ziggeo/ZiggeoWebhooks.java | Ziggeo/ZiggeoJavaSdk | 3deb8caf66ba1796356512825c06181918051047 | [
"Apache-2.0"
] | 2 | 2015-06-26T13:30:53.000Z | 2019-04-22T12:27:11.000Z | src/main/java/com/ziggeo/ZiggeoWebhooks.java | Ziggeo/ZiggeoJavaSdk | 3deb8caf66ba1796356512825c06181918051047 | [
"Apache-2.0"
] | 6 | 2015-06-26T12:42:56.000Z | 2019-04-22T08:14:07.000Z | package com.ziggeo;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class ZiggeoWebhooks {
private Ziggeo application;
public ZiggeoWebhooks(Ziggeo application) {
this.application = application;
}
public InputStream create(JSONObject data) throws IOException, JSONException {
return this.application.connect().post("/v1/api/hook", data);
}
public InputStream confirm(JSONObject data) throws IOException, JSONException {
return this.application.connect().post("/v1/api/confirmhook", data);
}
public InputStream delete(JSONObject data) throws IOException, JSONException {
return this.application.connect().post("/v1/api/removehook", data);
}
}
| 26.28125 | 83 | 0.726516 |
f77f1d4055822a66cb9f7d2b1c9b712869829cf8 | 1,241 | c | C | hist.c | dfjdejulio/misc | 4d5f24cfd520dd2e2ec154e312d7996a3df96a97 | [
"MIT"
] | 1 | 2017-06-24T21:22:42.000Z | 2017-06-24T21:22:42.000Z | hist.c | dfjdejulio/misc | 4d5f24cfd520dd2e2ec154e312d7996a3df96a97 | [
"MIT"
] | null | null | null | hist.c | dfjdejulio/misc | 4d5f24cfd520dd2e2ec154e312d7996a3df96a97 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <strings.h>
int
main(int argc,
char *argv[])
{
int counts[256];
int i, c;
char *name;
bzero(counts, sizeof(int) * 256);
switch (argc) {
case 2:
if (!freopen(argv[1], "r", stdin)) {
fprintf(stderr, "%s: can't open %s for reading.\n",
argv[0], argv[1]);
return 34;
}
case 1:
break;
default:
fprintf(stderr,
"usage: %s [infile]\n",
argv[0]);
return 17;
}
while ((c=getchar()) != EOF) {
counts[c]++;
}
for (i=0; i<256; i++) {
if (counts[i]) {
printf("0x%02X", i);
if (i > 0x20 && i < 0x7f) {
printf(" (%c)", i);
} else {
switch (i) {
case 0x09:
name = " (tab)";
break;
case 0x0A:
name = " (newline)";
break;
case 0x20:
name = " (space)";
break;
case 0x1B:
name = " (escape)";
break;
case 0x1C:
name = " (field separator)";
break;
case 0x1D:
name = " (group separator)";
break;
case 0x1E:
name = " (record separator)";
break;
case 0x1F:
name = " (unit esparator)";
break;
case 0x7f:
name = " (del)";
break;
default:
name = "";
}
fputs(name, stdout);
}
printf(": %d\n", counts[i]);
}
}
return 0;
}
| 15.5125 | 57 | 0.500403 |
04dbef5ae9099c4f00570ee7e2dc7006063169fb | 1,572 | java | Java | dataverse-persistence/src/main/java/edu/harvard/iq/dataverse/persistence/group/AllUsers.java | CeON/dataverse | 6e657572cf000532a8660f57e5484817f0d016c4 | [
"Apache-2.0"
] | 7 | 2019-12-13T22:30:06.000Z | 2021-12-28T20:38:48.000Z | dataverse-persistence/src/main/java/edu/harvard/iq/dataverse/persistence/group/AllUsers.java | CeON/dataverse | 6e657572cf000532a8660f57e5484817f0d016c4 | [
"Apache-2.0"
] | 1,294 | 2019-01-08T18:55:57.000Z | 2022-03-31T09:47:19.000Z | dataverse-persistence/src/main/java/edu/harvard/iq/dataverse/persistence/group/AllUsers.java | CeON/dataverse | 6e657572cf000532a8660f57e5484817f0d016c4 | [
"Apache-2.0"
] | 5 | 2020-02-22T14:30:40.000Z | 2020-02-27T18:07:02.000Z | package edu.harvard.iq.dataverse.persistence.group;
import edu.harvard.iq.dataverse.common.BundleUtil;
import edu.harvard.iq.dataverse.persistence.user.RoleAssigneeDisplayInfo;
/**
* A group containing all the users in the system - including the guest user.
* So, basically, everyone.
*
* <b>NOTE</b> this group is a singleton, as there's no point in having more than one. Get the instance
* using {@link #get()}.
*
* @author michael
*/
public final class AllUsers implements Group {
public static final String GROUP_TYPE = "builtin";
public static final AllUsers instance = new AllUsers();
private final String identifier = ":AllUsers";
public static final AllUsers get() {
return instance;
}
/**
* Prevent instance creation
*/
private AllUsers() {
}
@Override
public boolean isEditable() {
return false;
}
@Override
public String getIdentifier() {
return identifier;
}
@Override
public RoleAssigneeDisplayInfo getDisplayInfo() {
return new RoleAssigneeDisplayInfo(BundleUtil.getStringFromBundle("permission.everyone"), null);
}
@Override
public String getAlias() {
return GROUP_TYPE + Group.PATH_SEPARATOR + "all-users";
}
@Override
public String getDisplayName() {
return "All Users";
}
@Override
public String getDescription() {
return "All users, including guests";
}
@Override
public String toString() {
return "[AllUsers " + getIdentifier() + "]";
}
}
| 22.782609 | 104 | 0.655852 |
2f7057ec3f644d6ea4636835e8c7c1691c6fafac | 9,383 | php | PHP | src/Controller/MenuController.php | twin-elements/menu-bundle | e906d4d9ed9cc1cbfcc9f86c3724eb8c4f2d535d | [
"MIT"
] | null | null | null | src/Controller/MenuController.php | twin-elements/menu-bundle | e906d4d9ed9cc1cbfcc9f86c3724eb8c4f2d535d | [
"MIT"
] | null | null | null | src/Controller/MenuController.php | twin-elements/menu-bundle | e906d4d9ed9cc1cbfcc9f86c3724eb8c4f2d535d | [
"MIT"
] | null | null | null | <?php
namespace TwinElements\MenuBundle\Controller;
use Symfony\Component\Cache\Adapter\AdapterInterface;
use TwinElements\Component\CrudLogger\CrudLogger;
use TwinElements\Component\CrudLogger\CrudLoggerInterface;
use TwinElements\SortableBundle\Entity\PositionInterface;
use TwinElements\AdminBundle\Helper\Breadcrumbs;
use TwinElements\AdminBundle\Model\CrudControllerTrait;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use TwinElements\AdminBundle\Role\AdminUserRole;
use TwinElements\Component\AdminTranslator\AdminTranslator;
use TwinElements\Component\Flashes\Flashes;
use TwinElements\MenuBundle\Entity\Menu;
use TwinElements\MenuBundle\Entity\MenuCategory;
use TwinElements\MenuBundle\Form\MenuType;
use TwinElements\MenuBundle\MenuCacheUtilities;
use TwinElements\MenuBundle\Repository\MenuCategoryRepository;
use TwinElements\MenuBundle\Repository\MenuRepository;
/**
* @Route("menu")
*/
class MenuController extends AbstractController
{
/**
* @var AdapterInterface $cache
*/
private $cache;
use CrudControllerTrait {
CrudControllerTrait::__construct as private __crudConstruct;
}
public function __construct(Breadcrumbs $breadcrumbs, Flashes $flashes, CrudLoggerInterface $crudLogger, AdminTranslator $translator, AdapterInterface $cache)
{
$this->__crudConstruct($breadcrumbs, $flashes, $crudLogger, $translator);
$this->cache = $cache;
}
/**
* @Route("/", name="menu_index", methods={"GET"})
*/
public function indexAction(Request $request, MenuRepository $menuRepository, MenuCategoryRepository $menuCategoryRepository)
{
if (!$request->query->has('category')) {
throw new \Exception('Category ID not found');
}
$categoryId = $request->query->getInt('category');
$menuItems = $menuRepository->findIndexListItems($categoryId);
$menuCategory = $menuCategoryRepository->find($categoryId);
$this->breadcrumbs->setItems([
$this->adminTranslator->translate('menu_category.menu_categories') => $this->generateUrl('menucategory_index'),
$menuCategory->getTitle() => null
]);
$responseParameters = [
'menus' => $menuItems,
'menu_category' => $menuCategory
];
if ((new \ReflectionClass(Menu::class))->implementsInterface(PositionInterface::class)) {
$responseParameters['sortable'] = Menu::class;
}
return $this->render('@TwinElementsMenu/menu/index.html.twig', $responseParameters);
}
/**
* @Route("/new", name="menu_new", methods={"GET", "POST"})
*/
public function newAction(Request $request, AdapterInterface $cache)
{
$this->denyAccessUnlessGranted(AdminUserRole::ROLE_ADMIN);
$categoryId = (int)$request->get('category');
$menuCategory = $this->getDoctrine()->getRepository(MenuCategory::class)->find($categoryId);
$menuCategoryDefaultTitle = $menuCategory->getTitle();
$menu = new Menu();
$menu->setCurrentLocale($request->getLocale());
$form = $this->createForm(MenuType::class, $menu, ['category' => $categoryId]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
try {
$menu->setCategory($menuCategory);
$em = $this->getDoctrine()->getManager();
$em->persist($menu);
$menu->mergeNewTranslations();
$em->flush();
if ($menuCategory->isCached()) {
$this->removeCache($menuCategory->getId(), $request->getLocale());
}
$this->flashes->successMessage($this->adminTranslator->translate('admin.success_operation'));;
$this->crudLogger->createLog(Menu::class, CrudLogger::CreateAction, $menu->getId());
} catch (\Exception $exception) {
$this->flashes->errorMessage($exception->getMessage());
return $this->redirectToRoute('menu_index', array('category' => $menuCategory->getId()));
}
if ('save' === $form->getClickedButton()->getName()) {
return $this->redirectToRoute('menu_edit', array('id' => $menu->getId(), 'category' => $menuCategory->getId()));
} else {
return $this->redirectToRoute('menu_index', array('category' => $menuCategory->getId()));
}
}
$this->breadcrumbs->setItems([
$this->adminTranslator->translate('menu_category.menu_categories') => $this->generateUrl('menucategory_index'),
$menuCategoryDefaultTitle => $this->generateUrl('menu_index', [
'category' => $categoryId
]),
'Dodawanie nowej pozycji' => null
]);
return $this->render('@TwinElementsMenu/menu/new.html.twig', array(
'menu' => $menu,
'menu_category' => $menuCategory,
'form' => $form->createView(),
'menu_category_default_locale_title' => $menuCategoryDefaultTitle
));
}
/**
* @Route("/{id}/edit", name="menu_edit", methods={"GET", "POST"})
*/
public function editAction(Request $request, Menu $menu, AdapterInterface $cache)
{
$this->denyAccessUnlessGranted(AdminUserRole::ROLE_ADMIN);
$categoryId = (int)$request->get('category');
$menuCategory = $menu->getCategory();
$deleteForm = $this->createDeleteForm($menu);
$editForm = $this->createForm(MenuType::class, $menu, ['category' => $categoryId]);
$editForm->handleRequest($request);
if ($editForm->isSubmitted() && $editForm->isValid()) {
try {
$menu->mergeNewTranslations();
$this->getDoctrine()->getManager()->flush();
if ($menuCategory->isCached()) {
$this->removeCache($menuCategory->getId(), $request->getLocale());
}
$this->flashes->successMessage($this->adminTranslator->translate('admin.success_operation'));;
$this->crudLogger->createLog(Menu::class, CrudLogger::EditAction, $menu->getId());
} catch (\Exception $exception) {
$this->flashes->errorMessage($exception->getMessage());
}
if ('save' === $editForm->getClickedButton()->getName()) {
return $this->redirectToRoute('menu_edit', array('id' => $menu->getId(), 'category' => $menuCategory->getId()));
} else {
return $this->redirectToRoute('menu_index', array('category' => $menuCategory->getId()));
}
}
$this->breadcrumbs->setItems([
$this->adminTranslator->translate('menu_category.menu_categories') => $this->generateUrl('menucategory_index'),
$menu->getCategory()->getTitle() => $this->generateUrl('menu_index', [
'category' => $categoryId
]),
$menu->getTitle() => null
]);
return $this->render('@TwinElementsMenu/menu/edit.html.twig', array(
'entity' => $menu,
'menu_category' => $menuCategory,
'form' => $editForm->createView(),
'delete_form' => $deleteForm->createView()
));
}
/**
* Deletes a menu entity.
*
* @Route("/{id}", name="menu_delete", methods={"DELETE"})
*/
public function deleteAction(Request $request, Menu $menu)
{
$this->denyAccessUnlessGranted(AdminUserRole::ROLE_ADMIN);
$form = $this->createDeleteForm($menu);
$form->handleRequest($request);
$category = $menu->getCategory()->getId();
if ($form->isSubmitted() && $form->isValid()) {
try {
$id = $menu->getId();
$title = $menu->getTitle();
$em = $this->getDoctrine()->getManager();
$em->remove($menu);
$em->flush();
$this->removeCache($category, $request->getLocale());
$this->crudLogger->createLog(Menu::class, CrudLogger::DeleteAction, $menu->getId());
$this->flashes->successMessage($this->adminTranslator->translate('menu.the_menu_item_has_been_deleted'));
} catch (\Exception $exception) {
$this->flashes->errorMessage($exception->getMessage());
}
}
return $this->redirectToRoute('menu_index', ['category' => $category]);
}
/**
* Creates a form to delete a menu entity.
*
* @param Menu $menu The menu entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm(Menu $menu)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('menu_delete', array('id' => $menu->getId(), 'category' => $menu->getCategory()->getId())))
->setMethod('DELETE')
->getForm();
}
private function removeCache(int $id, string $locale)
{
if ($this->cache->hasItem(MenuCacheUtilities::getCacheName($id, $locale))) {
$this->cache->deleteItem(MenuCacheUtilities::getCacheName($id, $locale));
}
}
}
| 36.509728 | 162 | 0.600554 |
52fe166637a36d12e255b1686508e0aaf1e2c5ef | 9,771 | asm | Assembly | gxboot/vbr/entry.asm | madd-games/glidix | 1510d9c3f159bee9d4aa942e715aedc78b7f827c | [
"BSD-2-Clause"
] | 98 | 2015-08-05T22:20:19.000Z | 2022-03-11T08:49:24.000Z | gxboot/vbr/entry.asm | madd-games/glidix | 1510d9c3f159bee9d4aa942e715aedc78b7f827c | [
"BSD-2-Clause"
] | 5 | 2016-02-23T12:49:24.000Z | 2019-10-11T18:09:47.000Z | gxboot/vbr/entry.asm | madd-games/glidix | 1510d9c3f159bee9d4aa942e715aedc78b7f827c | [
"BSD-2-Clause"
] | 11 | 2015-12-02T05:01:28.000Z | 2021-06-25T16:54:18.000Z | ; Glidix bootloader (gxboot)
;
; Copyright (c) 2014-2017, Madd Games.
; All rights reserved.
;
; Redistribution and use in source and binary forms, with or without
; modification, are permitted provided that the following conditions are met:
;
; * Redistributions of source code must retain the above copyright notice, this
; list of conditions and the following disclaimer.
;
; * Redistributions in binary form must reproduce the above copyright notice,
; this list of conditions and the following disclaimer in the documentation
; and/or other materials provided with the distribution.
;
; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
; entry code for GXFS boot
extern vbr_end
extern bmain
global boot_disk
global part_start
global _start
global biosRead
global dap
global sectorBuffer
global biosGetMap
global go64
global vbeInfoBlock
global vbeModeInfo
global vbeGetModeInfo
global vbeSwitchMode
section .entry_text
bits 16
%ifdef GXBOOT_FS_GXFS
_start:
cli
; figure out the size in sectors
mov eax, [size]
shr eax, 9
inc eax
mov [dap.count], ax
; load starting from the second sector
mov eax, [si+8]
mov [part_start], eax
inc eax
mov [dap.lba], eax
; save the disk number
mov [boot_disk], dl
; set up a new stack
mov sp, 0x7C00
; enable interrupts now
sti
; load the rest of the VBR
mov ah, 0x42
mov si, dap
int 0x13
jc boot_failed
%endif
; this is the starting point for El Torito. the first stage already loaded the whole VBR,
; now we just need to go to protected mode and stuff. but we do still need to switch the stack
; and save the disk number
%ifdef GXBOOT_FS_ELTORITO
mov [boot_disk], dl
mov sp, 0x7C00
%endif
; enable A20
mov ax, 0x2401
int 0x15
; get VBE information
mov ax, 0x4F00
mov di, vbeInfoBlock
int 0x10
test ah, ah
jnz boot_failed
; disable interrupts again, we're going to PMode
cli
; load GDT
lgdt [GDT32.Pointer]
; enable protected mode
mov eax, cr0
or eax, 1
mov cr0, eax
; jump to 32-bit segment
jmp 0x08:goto32
size dd vbr_end - 0x7C00
boot_failed:
int 0x18
dap:
db 0x10 ; size
db 0 ; unused
.count dw 0 ; number of sectors to read
.offset dw 0x7E00 ; destination offset (512 bytes past first sector)
dw 0 ; destination segment
.lba dd 0 ; LBA to read from
dd 0 ; high 32 bits of LBA, unused
boot_disk db 0
part_start dd 0
vbeInfoBlock:
db 'VBE2' ; needed, apparently?
resb 512
vbeModeInfo:
resb 256
_biosRead_rm:
; disable protected mode
mov eax, cr0
and eax, ~1
mov cr0, eax
; go to real mode
jmp 0:_biosRead_switch
_biosRead_switch:
; load real mode segments
xor ax, ax
mov ds, ax
mov es, ax
mov ss, ax
; call the BIOS
sti
mov ah, 0x42
mov dl, [boot_disk]
mov si, dap
int 0x13
jc boot_failed
cli
; enable protected mode again
mov eax, cr0
or eax, 1
mov cr0, eax
; jump to the protected mode part
jmp 0x08:_biosRead_pm
_vbeGetModeInfo_rm:
; disable protected mode
mov eax, cr0
and eax, ~1
mov cr0, eax
; go to real mode
jmp 0:_vbeGetModeInfo_switch
_vbeGetModeInfo_switch:
; load real mode segments
xor ax, ax
mov ds, ax
mov es, ax
mov ss, ax
; call the BIOS
sti
mov ax, 0x4F01
; mode already in CX
mov di, vbeModeInfo
int 0x10
xor ecx, ecx
mov cl, ah ; preserve return value in CL
cli
; enable protected mode again
mov eax, cr0
or eax, 1
mov cr0, eax
; jump to the protected mode part
jmp 0x08:_vbeGetModeInfo_pm
_vbeSwitchMode_rm:
; disable protected mode
mov eax, cr0
and eax, ~1
mov cr0, eax
; go to real mode
jmp 0:_vbeSwitchMode_switch
_vbeSwitchMode_switch:
; load real mode segments
xor ax, ax
mov ds, ax
mov es, ax
mov ss, ax
; call the BIOS
sti
mov ax, 0x4F02
mov bx, cx
or bx, (1 << 14)
int 0x10
xor ecx, ecx
mov cl, ah ; preserve return value in CL
cli
; enable protected mode again
mov eax, cr0
or eax, 1
mov cr0, eax
; jump to the protected mode part
jmp 0x08:_vbeSwitchMode_pm
_biosGetMap_rm:
; disable protected mode
mov eax, cr0
and eax, ~1
mov cr0, eax
; go to real mode
jmp 0:_biosGetMap_switch
_biosGetMap_switch:
; load real mode segments
xor ax, ax
mov ds, ax
mov es, ax
mov ss, ax
; preserve destination, ok pointer
push dx
; call the BIOS
sti
mov di, mmapBuffer
mov edx, 0x534D4150
mov eax, 0xE820
mov ecx, 24
int 0x15
cli
; if carry flag is set, we change "ok" to 0 and return whatever,
; otherwise just normally return to protected mode
pop di
jnc .no_carry
xor eax, eax
mov [di], eax
.no_carry:
mov eax, ebx
; enable protected mode again
mov ecx, cr0
or ecx, 1
mov cr0, ecx
; jump back to the protected mode part
jmp 0x08:_biosGetMap_pm
mmapBuffer:
times 24 db 0
bits 32
GDT32: ; Global Descriptor Table (32-bit).
.Null: equ $ - GDT32
dw 0 ; Limit (low).
dw 0 ; Base (low).
db 0 ; Base (middle)
db 0 ; Access.
db 0 ; Granularity.
db 0 ; Base (high).
.Code: equ $ - GDT32 ; The code descriptor.
dw 0xFFFF ; Limit (low).
dw 0 ; Base (low).
db 0 ; Base (middle)
db 10011000b ; Access.
db 11001111b ; Granularity.
db 0 ; Base (high).
.Data: equ $ - GDT32 ; The data descriptor.
dw 0xFFFF ; Limit (low).
dw 0 ; Base (low).
db 0 ; Base (middle)
db 10010010b ; Access.
db 10001111b ; Granularity.
db 0 ; Base (high).
.Code16: equ $ - GDT32
dw 0xFFFF ; Limit (low).
dw 0 ; Base (low).
db 0 ; Base (middle)
db 10011000b ; Access.
db 00001111b ; Granularity.
db 0 ; Base (high).
.Code64: equ $ - GDT32 ; The code descriptor.
dw 0 ; Limit (low).
dw 0 ; Base (low).
db 0 ; Base (middle)
db 10011000b ; Access.
db 00100000b ; Granularity.
db 0 ; Base (high).
.Data64: equ $ - GDT32 ; The data descriptor.
dw 0 ; Limit (low).
dw 0 ; Base (low).
db 0 ; Base (middle)
db 10010000b ; Access.
db 00000000b ; Granularity.
db 0 ; Base (high).
.Pointer: ; The GDT-pointer.
dw $ - GDT32 - 1 ; Limit.
.Addr: dd GDT32 ; Base.
goto32:
mov ax, 0x10
mov ds, ax
mov es, ax
mov ss, ax
mov fs, ax
mov gs, ax
mov esp, 0x7C00
cld
call bmain
crash_loop:
cli
hlt
jmp crash_loop
sectorBuffer:
times 4096 db 0
biosRead:
; preserve registers
push ebp
push ebx
push esi
push edi
; go to 16-bit protected mode
jmp 0x18:_biosRead_rm
_biosRead_pm:
; load protected mode segments
mov ax, 0x10
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
mov ss, ax
; restore registers
pop edi
pop esi
pop ebx
pop ebp
; return
cld
ret
_vbeGetModeInfo_pm:
; load protected mode segments
mov ax, 0x10
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
mov ss, ax
; restore registers
pop edi
pop esi
pop ebx
pop ebp
; restore the VBE return value in EAX
mov eax, ecx
; return
cld
ret
_vbeSwitchMode_pm:
; load protected mode segments
mov ax, 0x10
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
mov ss, ax
; restore registers
pop edi
pop esi
pop ebx
pop ebp
; restore the VBE return value in EAX
mov eax, ecx
; return
cld
ret
biosGetMap:
push ebp
mov ebp, esp
push ebx
push esi
push edi
mov ebx, [ebp+8] ; index into EBX
mov esi, [ebp+12] ; destination into ESI
mov edx, [ebp+16] ; ok pointer into EDX
push esi
; go to 16-bit protected mode
jmp 0x18:_biosGetMap_rm
vbeGetModeInfo:
push ebp
mov ebp, esp
push ebx
push esi
push edi
mov ecx, [ebp+8] ; mode into ECX
; go to 16-bit protected mode
jmp 0x18:_vbeGetModeInfo_rm
vbeSwitchMode:
push ebp
mov ebp, esp
push ebx
push esi
push edi
mov ecx, [ebp+8] ; mode into ECX (for now)
; go to 16-bit protected mode
jmp 0x18:_vbeSwitchMode_rm
_biosGetMap_pm:
; restore 32-bit segments
mov bx, 0x10
mov ds, bx
mov ss, bx
mov es, bx
mov fs, bx
mov gs, bx
pop edi
mov esi, mmapBuffer
mov ecx, 20
rep movsb
pop edi
pop esi
pop ebx
pop ebp
cld
ret
go64:
; edit segment selector 0x08 to be 64-bit
mov esi, GDT32 + 0x20
mov edi, GDT32 + 0x08
mov ecx, 8
rep movsb
mov esi, [esp+4]
; load the PML4
mov eax, [esi+0x18]
mov cr3, eax
; enable PAE
mov eax, cr4
or eax, 1 << 5
mov cr4, eax
; enable long mode
mov ecx, 0xC0000080
rdmsr
or eax, 1 << 8
wrmsr
; enable paging and write-protect
mov eax, cr0
or eax, 1 << 31
or eax, 1 << 16
mov cr0, eax
; go to 64-bit mode
jmp 0x08:_entry64
_entry64:
incbin "stub64.bin"
| 18.646947 | 94 | 0.640876 |
7fc723c811fa785137115d43810f5fdee33dbeae | 6,226 | swift | Swift | Eskaera/Source/HTTPRequestQueue.swift | victorrodri04/eskaera | a8d399a879c3375cd2cc2c4c059630a00c1e0def | [
"MIT"
] | null | null | null | Eskaera/Source/HTTPRequestQueue.swift | victorrodri04/eskaera | a8d399a879c3375cd2cc2c4c059630a00c1e0def | [
"MIT"
] | null | null | null | Eskaera/Source/HTTPRequestQueue.swift | victorrodri04/eskaera | a8d399a879c3375cd2cc2c4c059630a00c1e0def | [
"MIT"
] | null | null | null | //
// HTTPRequestQueue.swift
// Eskaera
//
// Created by Victor on 08/06/2016.
// Copyright © 2016 Victor Rodriguez Reche. All rights reserved.
//
import Foundation
open class Request: NSObject, NSCoding {
var task: Task?
var taskDictionary: JSON?
convenience init(task: Task) {
self.init()
self.task = task
}
@objc public required convenience init(coder decoder: NSCoder) {
self.init()
self.taskDictionary = decoder.decodeObject(forKey: "taskDictionary") as? JSON
}
@objc open func encode(with coder: NSCoder) {
let dictionary = task?.json ?? taskDictionary
coder.encode(dictionary, forKey: "taskDictionary")
}
}
open class HTTPRequestQueue: TasksQueueProtocol {
open static let sharedInstance = HTTPRequestQueue(httpClient: HTTPClient.sharedInstance)
fileprivate typealias Queue = [Request]
fileprivate let queueKey = "persistentQueue"
open var httpClient: HTTPClient
fileprivate lazy var pendingQueue: Queue = {
return self.getQueue()
}()
fileprivate var inProgressRequests = [String: Request]()
public init(httpClient: HTTPClient) {
self.httpClient = httpClient
}
open func addTask(_ task: Task) {
if task.persist {
persistTask(task)
}
let request = Request(task: task)
return appendRequest(request)
}
fileprivate func persistTask(_ task: Task) {
let request = Request(task: task)
saveRequest(request)
}
open func executeTask(_ task: Task) {
addTask(task)
executeTasks()
}
open func executeTasks() {
executeTasks(withQueue: pendingQueue)
}
fileprivate func appendRequest(_ request: Request) {
let append = !requestsQueue(pendingQueue, containsRequest: request)
if append {
pendingQueue.append(request)
}
}
fileprivate func requestsQueue(_ queue: Queue, containsRequest request: Request) -> Bool {
return queue.contains {
if let newQueueTask = $0.task, let requestTask = request.task {
return newQueueTask.identifier == requestTask.identifier
} else if let newQueueTaskToken = $0.taskDictionary?[TaskConstants.identifier.rawValue] as? String,
let requestTaskToken = request.taskDictionary?[TaskConstants.identifier.rawValue] as? String {
return newQueueTaskToken == requestTaskToken
} else {
return false
}
}
}
fileprivate func executeTasks(withQueue queue: Queue) {
if queue.count < 1 { return }
var tasksQueue = Queue()
tasksQueue.append(contentsOf: queue)
var tasksQueueCopy = Queue()
tasksQueueCopy.append(contentsOf: queue)
var nextRequest: Request?
for request in tasksQueueCopy {
if let identifier = request.task?.identifier ?? request.taskDictionary?[TaskConstants.identifier.rawValue] as? String,
inProgressRequests[identifier] == nil {
nextRequest = request
if let index = tasksQueue.index(of: request) {
tasksQueue.remove(at: index)
}
break
} else {
if let index = tasksQueue.index(of: request) {
tasksQueue.remove(at: index)
}
}
}
guard
let request = nextRequest,
let token = request.task?.identifier ?? request.taskDictionary?[TaskConstants.identifier.rawValue] as? String
else {
return
}
inProgressRequests[token] = request
httpClient.request(request) { response in
self.inProgressRequests.removeValue(forKey: token)
var overridePersistedQueue = false
switch response {
case .success(_):
overridePersistedQueue = true
break
case .failure(let error):
if case .resquest(let data) = error, let task = request.task as? ErrorSkipable {
guard let data = data else { break }
// If the task should be persisted do not override the persisted queue to not loose the task
if task.shoulPersistTask(with: data) {
overridePersistedQueue = false
}
}
}
if overridePersistedQueue {
let _ = self.persist(queue: tasksQueue)
}
request.task?.completed(with: response)
self.executeTasks(withQueue: tasksQueue)
}
}
fileprivate func getQueue() -> Queue {
let filePath = FileManager.path(withFileName: queueKey)
guard let data = FileManager.data(fromFilePath: filePath),
let queue = data as? Queue else {
return Queue()
}
return queue
}
fileprivate func saveRequest(_ request: Request) {
var newQueue = pendingQueue
var dictionary:JSON?
if let task = request.task {
dictionary = task.json
} else if let taskDictionary = request.taskDictionary,
let persist = taskDictionary[TaskConstants.persist.rawValue] as? Bool , persist {
dictionary = taskDictionary
}
guard
let taskDictionary = dictionary,
let identifier = taskDictionary[TaskConstants.identifier.rawValue] as? String
else {
return
}
if !newQueue.contains { $0.task?.identifier == identifier } {
newQueue.append(request)
pendingQueue = persist(queue: newQueue) ? newQueue : pendingQueue
}
}
fileprivate func persist(queue: Queue) -> Bool {
let data = NSKeyedArchiver.archivedData(withRootObject: queue)
return FileManager.save(data: data, path: FileManager.path(withFileName: queueKey))
}
}
| 32.259067 | 130 | 0.578702 |
7165218ebe9900fdea08ff4aae26d066c8135ebb | 413 | ts | TypeScript | node_modules/angular2/ts/render.ts | cobaltutby/dev0 | d15471b25d4c2c135d313797ab77aa17a096665e | [
"MIT"
] | null | null | null | node_modules/angular2/ts/render.ts | cobaltutby/dev0 | d15471b25d4c2c135d313797ab77aa17a096665e | [
"MIT"
] | null | null | null | node_modules/angular2/ts/render.ts | cobaltutby/dev0 | d15471b25d4c2c135d313797ab77aa17a096665e | [
"MIT"
] | null | null | null | /**
* @module
* @description
* This module provides advanced support for extending dom strategy.
*/
export {
RenderDirectiveMetadata,
DomRenderer,
RenderEventDispatcher,
Renderer,
RenderElementRef,
RenderViewRef,
RenderProtoViewRef,
RenderFragmentRef,
RenderViewWithFragments,
ViewDefinition,
DOCUMENT,
APP_ID,
MAX_IN_MEMORY_ELEMENTS_PER_TEMPLATE
} from './src/core/render/render';
| 18.772727 | 68 | 0.762712 |
c3441ecc5ed4c9f4e535f0c13b48d90794e2212e | 71 | go | Go | simulation/util/package.go | andrew-edgar/auction | 79c3e4eefd43c8039fa5171a58f7d51add4bbac6 | [
"Apache-2.0"
] | 16 | 2016-08-02T01:01:12.000Z | 2021-09-04T18:34:52.000Z | simulation/util/package.go | andrew-edgar/auction | 79c3e4eefd43c8039fa5171a58f7d51add4bbac6 | [
"Apache-2.0"
] | 4 | 2015-01-01T21:26:48.000Z | 2016-01-07T15:40:58.000Z | simulation/util/package.go | andrew-edgar/auction | 79c3e4eefd43c8039fa5171a58f7d51add4bbac6 | [
"Apache-2.0"
] | 10 | 2017-08-03T06:55:37.000Z | 2020-12-10T14:43:02.000Z | package util // import "code.cloudfoundry.org/auction/simulation/util"
| 35.5 | 70 | 0.802817 |
37e65ca0fa7b8859b97bc23fd9b07c760741f8fd | 1,203 | sql | SQL | HealthCheck/Scripts_2014/TablesManyIndexes.sql | jonlabelle/HealthCheck | 37bc312631a87c5c2567eb895b6bef9cf075cc0d | [
"MIT"
] | 30 | 2015-11-18T15:23:02.000Z | 2022-01-14T20:20:03.000Z | HealthCheck/Scripts_2014/TablesManyIndexes.sql | jonlabelle/HealthCheck | 37bc312631a87c5c2567eb895b6bef9cf075cc0d | [
"MIT"
] | 3 | 2015-11-30T15:31:03.000Z | 2021-09-03T09:32:03.000Z | HealthCheck/Scripts_2014/TablesManyIndexes.sql | jonlabelle/HealthCheck | 37bc312631a87c5c2567eb895b6bef9cf075cc0d | [
"MIT"
] | 20 | 2015-11-19T02:58:42.000Z | 2020-12-29T15:40:37.000Z | /********************************************************************
Filename: TablesManyIndexes.sql
Author: Omid Afzalalghom
Date: 11/09/15
Comments: Returns a list of tables with more than five indexes
and an index count greater than half the column count.
Revisions:
********************************************************************/
SET NOCOUNT ON;
SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
WITH IndexColCount
AS (
SELECT
SCHEMA_NAME(t.schema_id) AS 'Schema_Name'
,OBJECT_NAME(i.object_id) AS 'Table_Name'
,COUNT(DISTINCT i.index_id) AS 'Index_Count'
,(SELECT COUNT(*) FROM sys.columns c WHERE c.object_id = i.object_id) 'Cols_Count'
,COALESCE((
SELECT SUM(s.rows)
FROM sys.partitions s
WHERE s.object_id = i.object_id
AND s.index_id < 2
), 0) 'Rows'
FROM sys.indexes i
INNER JOIN sys.tables t ON i.object_id = t.object_id
WHERE i.index_id >= 1
GROUP BY
t.object_id
,t.schema_id
,i.object_id
HAVING COUNT(*) >= 5
)
SELECT
[Schema_Name]
,[Table_Name]
,[Index_Count]
,[Cols_Count]
FROM IndexColCount
WHERE [Cols_Count]/[Index_Count] < 2
ORDER BY [Index_Count] DESC
,[Cols_Count];
| 26.152174 | 84 | 0.60931 |
b1833680c551ca9f1b7904ba75e7dc329b89d837 | 730 | c | C | components/zigbee/utils/crc.c | panjikuai/IoT_Gateway | 44f7c386d3428d06468d29b3d42b51d20b96b20c | [
"Apache-2.0"
] | 2 | 2020-02-16T08:07:58.000Z | 2020-08-11T15:13:18.000Z | components/zigbee/utils/crc.c | panjikuai/IoT_Gateway | 44f7c386d3428d06468d29b3d42b51d20b96b20c | [
"Apache-2.0"
] | null | null | null | components/zigbee/utils/crc.c | panjikuai/IoT_Gateway | 44f7c386d3428d06468d29b3d42b51d20b96b20c | [
"Apache-2.0"
] | 1 | 2022-02-07T12:18:57.000Z | 2022-02-07T12:18:57.000Z | #include "stdint.h"
const uint8_t crctable[16] = {0,0x07,0x0E,0x09, 0x1c,0x1b,0x12,0x15, 0x38,0x3F,0x36,0x31, 0x24,0x23,0x2A,0x2D};
const uint8_t crctable2[16] = {0,0x70,0xE0,0x90, 0xC1,0xB1,0x21,0x51, 0x83,0xF3,0x63,0x13, 0x42,0x32,0xA2,0xD2};
uint8_t FastCRC(uint8_t LastCRC, uint8_t newbyte)
{
uint8_t index;
index = newbyte;
index ^= LastCRC;
index >>= 4;
LastCRC &= 0x0F;
LastCRC ^= crctable2[index];
index = LastCRC;
index ^= newbyte;
index &= 0x0F;
LastCRC &= 0xF0;
LastCRC ^= crctable[index];
return(LastCRC);
}
/* calculate crc8 */
uint8_t calculate_crc8(uint8_t *p,uint8_t len)
{
uint8_t crc_value = 0;
uint8_t i;
for(i=0;i<len;i++){
crc_value = FastCRC(crc_value,p[i]);
}
return crc_value;
}
| 21.470588 | 112 | 0.689041 |
3bc353b554ce0d861ed68ed4aaf10ffe65cdbca2 | 1,526 | h | C | shared/src/shared/pixelboost/maths/matrixHelpers.h | pixelballoon/pixelboost | 085873310050ce62493df61142b7d4393795bdc2 | [
"MIT"
] | 6 | 2015-04-21T11:30:52.000Z | 2020-04-29T00:10:04.000Z | shared/src/shared/pixelboost/maths/matrixHelpers.h | pixelballoon/pixelboost | 085873310050ce62493df61142b7d4393795bdc2 | [
"MIT"
] | null | null | null | shared/src/shared/pixelboost/maths/matrixHelpers.h | pixelballoon/pixelboost | 085873310050ce62493df61142b7d4393795bdc2 | [
"MIT"
] | null | null | null | #pragma once
#include "glm/gtc/matrix_transform.hpp"
#include "glm/glm.hpp"
namespace pb
{
enum RotationOrder
{
kRotationOrder_XYZ,
};
inline glm::mat4x4 CreateTranslateMatrix(glm::vec3 translate, glm::mat4x4 transform = glm::mat4x4())
{
return glm::translate(transform, translate);
}
inline glm::mat4x4 CreateRotateMatrix(RotationOrder rotationOrder, glm::vec3 rotation, glm::mat4x4 transform = glm::mat4x4())
{
switch (rotationOrder)
{
case kRotationOrder_XYZ:
if (rotation.x != 0)
{
transform = glm::rotate(transform, rotation.x, glm::vec3(1,0,0));
}
if (rotation.y != 0)
{
transform = glm::rotate(transform, rotation.y, glm::vec3(0,1,0));
}
if (rotation.z != 0)
{
transform = glm::rotate(transform, rotation.z, glm::vec3(0,0,1));
}
break;
}
return transform;
}
inline glm::mat4x4 CreateScaleMatrix(glm::vec3 scale, glm::mat4x4 transform = glm::mat4x4())
{
if (scale == glm::vec3(1,1,1))
{
return transform;
}
return glm::scale(transform, scale);
}
inline glm::mat4x4 CreateTransformMatrix(RotationOrder rotationOrder, glm::vec3 translate, glm::vec3 rotate, glm::vec3 scale, glm::mat4x4 transform = glm::mat4x4())
{
transform = CreateTranslateMatrix(translate, transform);
transform = CreateRotateMatrix(rotationOrder, rotate, transform);
transform = CreateScaleMatrix(scale, transform);
return transform;
}
}
| 24.612903 | 164 | 0.63827 |
8a3fed88ce6d506b8820fb6c25804b5422806a61 | 104 | ps1 | PowerShell | build.ps1 | jasonchester/PSGremlin | a7ffaf37384c3b0654dc9791926d55bb51dc9231 | [
"MIT"
] | 2 | 2018-10-31T13:50:33.000Z | 2021-09-28T15:49:07.000Z | build.ps1 | jasonchester/PSGremlin | a7ffaf37384c3b0654dc9791926d55bb51dc9231 | [
"MIT"
] | 10 | 2019-05-08T05:55:15.000Z | 2021-07-26T10:18:15.000Z | build.ps1 | jasonchester/PSGremlin | a7ffaf37384c3b0654dc9791926d55bb51dc9231 | [
"MIT"
] | 1 | 2020-08-18T11:13:30.000Z | 2020-08-18T11:13:30.000Z | #!/usr/bin/env pwsh
Push-Location $PSScriptRoot/src
dotnet publish -o ../publish/PSGremlin
Pop-Location | 20.8 | 38 | 0.778846 |
3d5978334495d5e1eea098bed468cbc20117e722 | 224 | kt | Kotlin | arrow-libs/fx/arrow-fx/src/main/kotlin/arrow/fx/typeclasses/Environment.kt | clojj/arrow | 5eae605bbaeb2b911f69a5bccf3fa45c42578416 | [
"Apache-2.0"
] | null | null | null | arrow-libs/fx/arrow-fx/src/main/kotlin/arrow/fx/typeclasses/Environment.kt | clojj/arrow | 5eae605bbaeb2b911f69a5bccf3fa45c42578416 | [
"Apache-2.0"
] | null | null | null | arrow-libs/fx/arrow-fx/src/main/kotlin/arrow/fx/typeclasses/Environment.kt | clojj/arrow | 5eae605bbaeb2b911f69a5bccf3fa45c42578416 | [
"Apache-2.0"
] | null | null | null | package arrow.fx.typeclasses
import arrow.Kind
import arrow.fx.IODeprecation
@Deprecated(IODeprecation)
interface Environment<F> {
fun dispatchers(): Dispatchers<F>
fun handleAsyncError(e: Throwable): Kind<F, Unit>
}
| 18.666667 | 51 | 0.776786 |
40f9f69f8b49ffe50c47db5e99af1b0ccbfa8349 | 660 | py | Python | tests/test_server_protocol.py | PHT-Medic/aggregation-protocol | 44c04c692bb6ba5c180e2cd3e87ea823c6361739 | [
"MIT"
] | null | null | null | tests/test_server_protocol.py | PHT-Medic/aggregation-protocol | 44c04c692bb6ba5c180e2cd3e87ea823c6361739 | [
"MIT"
] | null | null | null | tests/test_server_protocol.py | PHT-Medic/aggregation-protocol | 44c04c692bb6ba5c180e2cd3e87ea823c6361739 | [
"MIT"
] | null | null | null | from protocol import ServerProtocol
from protocol.models.client_keys import ClientKeys
from protocol.models.server_messages import BroadCastClientKeys, ServerKeyBroadcast
def test_server_protocol_broadcast_keys():
protocol = ServerProtocol()
# generate key broadcasts
broadcasts = []
for i in range(5):
keys = ClientKeys()
broadcast_in = keys.key_broadcast()
client_broadcast = BroadCastClientKeys(
user_id=i,
broadcast=broadcast_in
)
broadcasts.append(client_broadcast)
broadcast = protocol.broadcast_keys(broadcasts)
assert isinstance(broadcast, ServerKeyBroadcast)
| 30 | 83 | 0.725758 |
048c5dbfd991b2f9c0fd259a5e0592315ef9984c | 1,196 | java | Java | src/test/java/serpapi/LocationApiTest.java | albertcoder/google-search-results-java | 0f103416fe173ddf73aa0fe65a2bca1fdea52b02 | [
"MIT"
] | 15 | 2018-04-24T09:15:02.000Z | 2022-02-09T13:54:34.000Z | src/test/java/serpapi/LocationApiTest.java | albertcoder/google-search-results-java | 0f103416fe173ddf73aa0fe65a2bca1fdea52b02 | [
"MIT"
] | 1 | 2021-01-05T23:27:19.000Z | 2021-01-05T23:27:19.000Z | src/test/java/serpapi/LocationApiTest.java | albertcoder/google-search-results-java | 0f103416fe173ddf73aa0fe65a2bca1fdea52b02 | [
"MIT"
] | 14 | 2018-07-02T10:53:26.000Z | 2021-12-26T16:22:43.000Z | package serpapi;
import com.google.gson.JsonArray;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentMatchers;
import java.nio.file.Paths;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class LocationApiTest {
@Before
public void setUp() throws Exception {
if (System.getenv("API_KEY") != null) {
GoogleSearch.serp_api_key_default = System.getenv("API_KEY");
}
}
// @Test
// public void getLocation() throws Exception {
// // mock response if run on github
// GoogleSearch search = new GoogleSearch();
// if (GoogleSearch.serp_api_key_default == null) {
// SerpApiHttpClient stub = mock(SerpApiHttpClient.class);
// when(stub.getResults(ArgumentMatchers.<String, String>anyMap()))
// .thenReturn(ReadJsonFile.readAsJson(Paths.get("src/test/java/serpapi/data/location.json")).toString());
// search.search = stub;
// }
// // search.search = search;
// JsonArray location = search.getLocation("Austin", 3);
// System.out.println(location.toString());
// assertEquals("Austin, TX", location.get(0).getAsJsonObject().get("name").getAsString());
// }
} | 31.473684 | 116 | 0.682274 |
f9f6df35ac6478504d3594ad61c3daf65deca69d | 2,628 | go | Go | pkg/ruler/compat_test.go | jbvmio/cortex | 8045f6f8d7ba4e65cab5f8ea4a14a7fa0ecf2c9a | [
"Apache-2.0"
] | null | null | null | pkg/ruler/compat_test.go | jbvmio/cortex | 8045f6f8d7ba4e65cab5f8ea4a14a7fa0ecf2c9a | [
"Apache-2.0"
] | null | null | null | pkg/ruler/compat_test.go | jbvmio/cortex | 8045f6f8d7ba4e65cab5f8ea4a14a7fa0ecf2c9a | [
"Apache-2.0"
] | null | null | null | package ruler
import (
"context"
"math"
"testing"
"time"
"github.com/prometheus/prometheus/pkg/value"
"github.com/prometheus/prometheus/promql/parser"
"github.com/stretchr/testify/require"
"github.com/cortexproject/cortex/pkg/cortexpb"
)
type fakePusher struct {
request *cortexpb.WriteRequest
response *cortexpb.WriteResponse
}
func (p *fakePusher) Push(ctx context.Context, r *cortexpb.WriteRequest) (*cortexpb.WriteResponse, error) {
p.request = r
return p.response, nil
}
func TestPusherAppendable(t *testing.T) {
pusher := &fakePusher{}
pa := &PusherAppendable{
pusher: pusher,
userID: "user-1",
}
for _, tc := range []struct {
name string
series string
evalDelay time.Duration
value float64
expectedTS int64
}{
{
name: "tenant without delay, normal value",
series: "foo_bar",
value: 1.234,
expectedTS: 120_000,
},
{
name: "tenant without delay, stale nan value",
series: "foo_bar",
value: math.Float64frombits(value.StaleNaN),
expectedTS: 120_000,
},
{
name: "tenant with delay, normal value",
series: "foo_bar",
value: 1.234,
expectedTS: 120_000,
evalDelay: time.Minute,
},
{
name: "tenant with delay, stale nan value",
value: math.Float64frombits(value.StaleNaN),
expectedTS: 60_000,
evalDelay: time.Minute,
},
{
name: "ALERTS without delay, normal value",
series: `ALERTS{alertname="boop"}`,
value: 1.234,
expectedTS: 120_000,
},
{
name: "ALERTS without delay, stale nan value",
series: `ALERTS{alertname="boop"}`,
value: math.Float64frombits(value.StaleNaN),
expectedTS: 120_000,
},
{
name: "ALERTS with delay, normal value",
series: `ALERTS{alertname="boop"}`,
value: 1.234,
expectedTS: 60_000,
evalDelay: time.Minute,
},
{
name: "ALERTS with delay, stale nan value",
series: `ALERTS_FOR_STATE{alertname="boop"}`,
value: math.Float64frombits(value.StaleNaN),
expectedTS: 60_000,
evalDelay: time.Minute,
},
} {
t.Run(tc.name, func(t *testing.T) {
ctx := context.Background()
pa.rulesLimits = &ruleLimits{
evalDelay: tc.evalDelay,
}
lbls, err := parser.ParseMetric(tc.series)
require.NoError(t, err)
pusher.response = &cortexpb.WriteResponse{}
a := pa.Appender(ctx)
_, err = a.Append(0, lbls, 120_000, tc.value)
require.NoError(t, err)
require.NoError(t, a.Commit())
require.Equal(t, tc.expectedTS, pusher.request.Timeseries[0].Samples[0].TimestampMs)
})
}
}
| 23.256637 | 107 | 0.637747 |
476c3d8a4f6aa133dc060b68d81d124d0d89f7b3 | 279 | swift | Swift | hw-2/hw-2/hw-2/Place.swift | tylerbrockett/cse394-principles-of-mobile-applications | 4645d3691b2433b1c1f2585c8229d84c12c307e1 | [
"MIT"
] | null | null | null | hw-2/hw-2/hw-2/Place.swift | tylerbrockett/cse394-principles-of-mobile-applications | 4645d3691b2433b1c1f2585c8229d84c12c307e1 | [
"MIT"
] | null | null | null | hw-2/hw-2/hw-2/Place.swift | tylerbrockett/cse394-principles-of-mobile-applications | 4645d3691b2433b1c1f2585c8229d84c12c307e1 | [
"MIT"
] | null | null | null | //
// Place.swift
// hw-2
//
// Created by Tyler Brockett on 2/24/16.
// Copyright © 2016 Tyler Brockett. All rights reserved.
//
import Foundation
import CoreData
class Place: NSManagedObject {
// Insert code here to add functionality to your managed object subclass
}
| 15.5 | 72 | 0.713262 |
265a5f7f637d7456a9fa6814804e0b85e92fc00b | 781 | java | Java | client/src/main/java/io/pravega/keycloak/client/KeycloakConfigurationException.java | addprs/pravega-keycloak | c1bb25ae1d24b12e0c64da8931e73819c789978b | [
"Apache-2.0"
] | 4 | 2020-01-16T01:29:24.000Z | 2022-01-06T06:23:42.000Z | client/src/main/java/io/pravega/keycloak/client/KeycloakConfigurationException.java | addprs/pravega-keycloak | c1bb25ae1d24b12e0c64da8931e73819c789978b | [
"Apache-2.0"
] | 47 | 2019-10-26T21:35:59.000Z | 2022-01-06T06:25:35.000Z | client/src/main/java/io/pravega/keycloak/client/KeycloakConfigurationException.java | addprs/pravega-keycloak | c1bb25ae1d24b12e0c64da8931e73819c789978b | [
"Apache-2.0"
] | 10 | 2020-01-15T15:21:07.000Z | 2021-10-21T20:33:19.000Z | /**
* Copyright (c) 2019 Dell Inc., or its subsidiaries. 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
*/
package io.pravega.keycloak.client;
/**
* Represents a problem related to Keycloak client configuration.
*/
public class KeycloakConfigurationException extends RuntimeException {
public KeycloakConfigurationException(String message, Throwable e) {
super(message, e);
}
public KeycloakConfigurationException(String message) {
super(message);
}
public KeycloakConfigurationException(Throwable e) {
super(e);
}
}
| 26.931034 | 74 | 0.706786 |
f901323c9eb097202df047bcc55c9bdedbeb7ccc | 2,995 | swift | Swift | ios/Classes/custom/uicustomization/IdenfyConfirmationViewUISettingsV2.swift | andreiavornic/idenfy | cc22848ec2969a9914db561b39aab1f3aec6ebc0 | [
"BSD-3-Clause"
] | null | null | null | ios/Classes/custom/uicustomization/IdenfyConfirmationViewUISettingsV2.swift | andreiavornic/idenfy | cc22848ec2969a9914db561b39aab1f3aec6ebc0 | [
"BSD-3-Clause"
] | null | null | null | ios/Classes/custom/uicustomization/IdenfyConfirmationViewUISettingsV2.swift | andreiavornic/idenfy | cc22848ec2969a9914db561b39aab1f3aec6ebc0 | [
"BSD-3-Clause"
] | 1 | 2022-02-03T09:41:14.000Z | 2022-02-03T09:41:14.000Z | //
// IdenfyConfirmationViewUISettings.swift
// idenfyviews
//
// Created by Viktor Vostrikov on 2020-02-10.
// Copyright © 2020 Apple. All rights reserved.
//
import Foundation
import UIKit
@objc open class IdenfyConfirmationViewUISettingsV2: NSObject {
// Idenfy Confirmation View Colors
public static var idenfyDocumentConfirmationViewBackgroundColor = IdenfyCommonColors.idenfyBackgroundColorV2
public static var idenfyDocumentConfirmationViewTitleTextColor = IdenfyCommonColors.idenfySecondColorV2
public static var idenfyDocumentConfirmationViewDescriptionTextColor = IdenfyCommonColors.idenfySecondColorV2
public static var idenfyDocumentConfirmationViewDescriptionHighlightedTextColor = IdenfyCommonColors.idenfyMainColorV2
public static var idenfyDocumentConfirmationViewBeginIdentificationButtonTextColor = IdenfyCommonColors.idenfyWhite
public static var idenfyDocumentConfirmationViewDocumentStepTitleTextColor = IdenfyCommonColors.idenfySecondColorV2
public static var idenfyDocumentConfirmationViewDocumentStepTitleHighlightedTextColor = IdenfyCommonColors.idenfyMainColorV2
public static var idenfyDocumentConfirmationViewUploadDocumentPhotoTitleTextColor = IdenfyCommonColors.idenfySecondColorV2
public static var idenfyDocumentConfirmationViewDocumentStepCellNumberTextColor = IdenfyCommonColors.idenfyWhite
public static var idenfyDocumentConfirmationViewDocumentStepCellTitleTextColor = IdenfyCommonColors.idenfySecondColorV2
public static var idenfyDocumentConfirmationViewContentMaskForegroundColor = IdenfyCommonColors.idenfyBackgroundColorV2.withAlphaComponent(0.9)
public static var idenfyDocumentConfirmationViewUploadIconTintColor: UIColor? = IdenfyCommonColors.idenfyMainColorV2
public static var idenfyDocumentConfirmationViewDocumentStepCircleTintColor: UIColor? = IdenfyCommonColors.idenfyMainColorV2
// Idenfy Confirmation View Fonts
public static var idenfyDocumentConfirmationViewTitleFont = UIFont(name: ConstsIdenfyFonts.idenfyFontBoldV2, size: 22)
public static var idenfyDocumentConfirmationViewDescriptionFont = UIFont(name: ConstsIdenfyFonts.idenfyFontRegularV2, size: 13)
public static var idenfyDocumentConfirmationViewDescriptionHighlightedFont = UIFont(name: ConstsIdenfyFonts.idenfyFontBoldV2, size: 13)
public static var idenfyDocumentConfirmationViewDocumentStepTitleFont = UIFont(name: ConstsIdenfyFonts.idenfyFontBoldV2, size: 13)
public static var idenfyDocumentConfirmationViewUploadTitleFont = UIFont(name: ConstsIdenfyFonts.idenfyFontRegularV2, size: 13)
public static var idenfyDocumentConfirmationViewDocumentStepNumberFont = UIFont(name: ConstsIdenfyFonts.idenfyFontBoldV2, size: 11)
public static var idenfyDocumentConfirmationViewDocumentStepFont = UIFont(name: ConstsIdenfyFonts.idenfyFontRegularV2, size: 13)
// Idenfy Confirmation View Style
public static var idenfyDocumentConfirmationViewDocumentStepCellHeight = CGFloat(30)
}
| 71.309524 | 147 | 0.859766 |
a9ece78764a7acc79f5ba4124577569a8cbfbebe | 1,226 | swift | Swift | iOS/CIFilter.io/NonFatalManager.swift | regularberry/cifilter.io | 5e517658dd580f86a3eb8988bcea5d8ef27c019f | [
"MIT"
] | 206 | 2019-03-16T18:48:18.000Z | 2022-03-05T01:14:26.000Z | iOS/CIFilter.io/NonFatalManager.swift | RobMackintosh/cifilter.io | 8d6e4c4f02f8b4b49642f0c2938761fc640544f9 | [
"MIT"
] | 81 | 2019-03-16T17:42:18.000Z | 2022-02-26T10:06:11.000Z | iOS/CIFilter.io/NonFatalManager.swift | RobMackintosh/cifilter.io | 8d6e4c4f02f8b4b49642f0c2938761fc640544f9 | [
"MIT"
] | 19 | 2019-04-03T23:14:31.000Z | 2022-03-11T05:14:27.000Z | //
// NonFatalManager.swift
// CIFilter.io
//
// Created by Noah Gilmore on 3/23/19.
// Copyright © 2019 Noah Gilmore. All rights reserved.
//
import Foundation
import Sentry
import Mixpanel
final class NonFatalManager {
static let shared = NonFatalManager()
func log(_ identifier: String, data: Properties = [:]) {
print("WARNING!! \(identifier)")
var mixpanelData = data
mixpanelData["identifier"] = identifier
AnalyticsManager.shared.track(event: "nonfatal", properties: mixpanelData)
let sentry = Client.shared!
sentry.snapshotStacktrace {
let event = Event(level: .error)
event.message = identifier
event.extra = data
sentry.appendStacktrace(to: event)
sentry.send(event: event)
}
}
// pecker:ignore (this is only used in release builds)
func breadcrumb(_ category: String, data: [String: Any]? = nil) {
let sentry = Client.shared!
print("Breadcrumb: \(category)")
let breadcrumb = Breadcrumb(level: .info, category: category)
if let data = data {
breadcrumb.data = data
}
sentry.breadcrumbs.add(breadcrumb)
}
}
| 28.511628 | 82 | 0.619902 |
600f44334cbdf880cf7e329c8effdfcbf7a76aa3 | 5,019 | swift | Swift | IOS/ProView/ProView/loginPage.swift | sashafromlibertalia/ICT-Hack-2 | 79a0e1173680ab06b02e6b74dc9e87608f7cf07f | [
"Apache-2.0"
] | null | null | null | IOS/ProView/ProView/loginPage.swift | sashafromlibertalia/ICT-Hack-2 | 79a0e1173680ab06b02e6b74dc9e87608f7cf07f | [
"Apache-2.0"
] | null | null | null | IOS/ProView/ProView/loginPage.swift | sashafromlibertalia/ICT-Hack-2 | 79a0e1173680ab06b02e6b74dc9e87608f7cf07f | [
"Apache-2.0"
] | null | null | null | //
// loginPage.swift
// ProView
//
// Created by Patrik Duksin on 2021-05-09.
//
import SwiftUI
let lightGreyColor = Color(red: 239.0/255.0, green: 243.0/255.0, blue: 244.0/255.0, opacity: 1.0)
let storedUsername = ""
let storedPassword = ""
struct loginPage: View {
@EnvironmentObject var viewRouter: ViewRouter
@State private var username: String = ""
@State private var password: String = ""
@State var authenticationDidFail: Bool = false
@State var authenticationDidSucceed: Bool = false
var body: some View {
ZStack {
VStack {
welcomeText()
welcomeImage()
usernameTextField(username: $username)
passwordTextField(password: $password)
if authenticationDidFail {
Text("the information not correct. Try again.")
.offset(y: -10)
.foregroundColor(.red)
}
if authenticationDidSucceed {
Text("Login succeeded!")
.font(.headline)
.frame(width: 250, height: 80)
.background(Color.green)
.cornerRadius(20.0)
.foregroundColor(.white)
.animation(Animation.default)
}
Button(action: {
if self.username == storedUsername && self.password == storedPassword {
self.authenticationDidSucceed = true
self.authenticationDidFail = false
UIApplication.shared.endEditing()
withAnimation {
viewRouter.currentPage = .generalPage
}
} else {
self.authenticationDidFail = true
}
}){ loginButtonContent() }
}
.padding()
.background(bubble, alignment: .topLeading)
.background(bubble.rotationEffect(Angle(degrees: 180)), alignment: .bottomTrailing)
.ignoresSafeArea()
}
}
@State private var startAnimation: Bool = false
var bubble: some View {
ZStack {
Circle()
.fill(Color(red: 104 / 255, green: 222 / 255, blue: 201 / 255, opacity: 0.55))
.frame(width: 300, height: 300, alignment: .topLeading)
.padding(.top, 600)
.offset(x: startAnimation ? -110 : -100, y: startAnimation ? -180 : -150)
Circle()
.fill(Color(red: 248 / 255, green: 64 / 255, blue: 97 / 255, opacity: 0.80))
.frame(width: 300, height: 300, alignment: .topLeading)
.padding(.top, 600)
.offset(x: startAnimation ? -180 : -150, y: startAnimation ? -90 : -100)
}
.onAppear() { startAnimation = true }
.animation(.easeInOut(duration: 3.0).repeatForever(autoreverses: true))
}
}
struct welcomeText: View {
var body: some View {
Text("Welcome!")
.font(.largeTitle)
.fontWeight(.semibold)
.padding(.bottom, 20)
}
}
struct welcomeImage: View {
var body: some View {
Image("inputLogo")
.resizable()
.aspectRatio(contentMode: .fill)
.frame(width: 100, height: 100)
.clipped()
.cornerRadius(100)
.padding(.bottom, 32)
}
}
struct loginButtonContent: View {
var body: some View {
Text("LOGIN")
.font(.headline)
.foregroundColor(.white)
.padding()
.frame(width: 220, height: 60)
.background(Color(red: 25 / 255, green: 99 / 255, blue: 168 / 255, opacity: 1))
.cornerRadius(15.0)
.shadow(color: Color.black.opacity(0.4), radius: 20, x: /*@START_MENU_TOKEN@*/0.0/*@END_MENU_TOKEN@*/, y: 10)
.shadow(color: Color.black.opacity(0.4), radius: 5, x: /*@START_MENU_TOKEN@*/0.0/*@END_MENU_TOKEN@*/, y: 5)
}
}
struct usernameTextField: View {
@Binding var username: String
var body: some View {
TextField("Username", text: $username)
.padding()
.background(lightGreyColor)
.cornerRadius(5.0)
.padding(.bottom, 20)
}
}
struct passwordTextField: View {
@Binding var password: String
var body: some View {
SecureField("Password", text: $password)
.padding()
.background(lightGreyColor)
.cornerRadius(5.0)
.padding(.bottom, 20)
}
}
struct loginPage_Previews: PreviewProvider {
static var previews: some View {
loginPage().environmentObject(ViewRouter())
}
}
extension UIApplication {
func endEditing() {
sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
}
| 33.46 | 121 | 0.524407 |
d074b1021655165c3d3349cc2d6ba5a238074797 | 1,417 | css | CSS | public/backend/assets/css/menu.css | thecaonguyen/webgiay | ab21eb8acd2908a26db43ee453effbcd96716efd | [
"MIT"
] | null | null | null | public/backend/assets/css/menu.css | thecaonguyen/webgiay | ab21eb8acd2908a26db43ee453effbcd96716efd | [
"MIT"
] | 2 | 2021-02-03T01:51:02.000Z | 2021-04-30T12:27:53.000Z | public/backend/assets/css/menu.css | thecaonguyen/webgiay | ab21eb8acd2908a26db43ee453effbcd96716efd | [
"MIT"
] | null | null | null |
ul { list-style-type: none; }
a {
color: #b63b4d;
text-decoration: none;
}
/** =======================
* Contenedor Principal
===========================*/
h1 {
color: #FFF;
font-size: 24px;
font-weight: 400;
text-align: center;
margin-top: 80px;
}
h1 a {
color: #c12c42;
font-size: 16px;
}
.accordion {
width: 100%;
max-width: 600px;
margin: 30px auto 20px;
background: #ebedf0;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.accordion .link,.link2 {
cursor: pointer;
display: block;
padding: 5px 15px 5px 42px;
color: #4D4D4D;
font-size: 14px;
font-weight: 700;
border-bottom: 1px solid #CCC;
position: relative;
-webkit-transition: all 0.4s ease;
-o-transition: all 0.4s ease;
transition: all 0.4s ease;
}
.accordion li i {
position: absolute;
top: 16px;
left: 12px;
font-size: 18px;
color: #595959;
-webkit-transition: all 0.4s ease;
-o-transition: all 0.4s ease;
transition: all 0.4s ease;
}
.accordion li i.fa-chevron-down {
font-size: 16px;
}
.link{ background-color: white; }
.accordion li.open .link,.link2 { color: #b63b4d; }
.accordion li.open i { color: #b63b4d; }
.accordion li.open i.fa-chevron-down {
-webkit-transform: rotate(180deg);
-ms-transform: rotate(180deg);
-o-transform: rotate(180deg);
transform: rotate(180deg);
}
/**
* Submenu
-----------------------------*/
| 16.869048 | 51 | 0.61115 |
84348094265125821ac22dcbfdd1b9955c5670f6 | 3,202 | kt | Kotlin | android/src/main/kotlin/mingsin/fzxing/CaptureActivity.kt | trevorwang/flutter-zxing | 324473504e57d7173d5784c81e973a3c189a4aa3 | [
"MIT"
] | 26 | 2018-08-12T05:36:36.000Z | 2020-11-17T03:59:15.000Z | android/src/main/kotlin/mingsin/fzxing/CaptureActivity.kt | GlomGlom/project_final | c000533d9bf18ee5da25a131a307c2825db1647a | [
"MIT"
] | 13 | 2019-02-11T18:29:19.000Z | 2019-12-19T09:45:41.000Z | android/src/main/kotlin/mingsin/fzxing/CaptureActivity.kt | GlomGlom/project_final | c000533d9bf18ee5da25a131a307c2825db1647a | [
"MIT"
] | 7 | 2018-12-05T13:52:54.000Z | 2021-05-27T04:58:22.000Z | package mingsin.fzxing
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import com.google.zxing.ResultPoint
import com.google.zxing.client.android.BeepManager
import com.google.zxing.client.android.Intents
import com.journeyapps.barcodescanner.BarcodeCallback
import com.journeyapps.barcodescanner.BarcodeResult
import com.journeyapps.barcodescanner.DecoratedBarcodeView
class CaptureActivity : Activity() {
private var lastBarcode = "INVALID_STRING_STATE"
private lateinit var scannerView: DecoratedBarcodeView
private val list = arrayListOf<String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_capture)
val isContinuous = intent.extras[keyIsContinuous] as Boolean
val isBeep = intent.getBooleanExtra(Intents.Scan.BEEP_ENABLED, true)
val interval = intent.extras[keyContinuousInterval] as? Int ?: 1000
var lastTime = System.currentTimeMillis()
val beepManager = BeepManager(this)
scannerView = findViewById(R.id.scanner_view)
scannerView.setStatusText("")
list.clear()
if (isContinuous) {
scannerView.decodeContinuous(object : BarcodeCallback {
override fun barcodeResult(result: BarcodeResult?) {
result?.text?.let {
val now = System.currentTimeMillis()
if (now - lastTime < interval && lastBarcode == it) {
return
}
if (isBeep) {
beepManager.playBeepSound()
}
lastBarcode = it
list.add(it)
lastTime = System.currentTimeMillis()
}
}
override fun possibleResultPoints(resultPoints: List<ResultPoint>) {
}
})
} else {
scannerView.decodeSingle(object : BarcodeCallback {
override fun barcodeResult(result: BarcodeResult?) {
result?.text?.let {
if (isBeep) {
beepManager.playBeepSound()
}
list.add(it)
setResult()
finish()
}
}
override fun possibleResultPoints(resultPoints: List<ResultPoint>) {
}
})
}
}
private fun setResult() {
val data = Intent()
data.putExtra("result", list)
setResult(RESULT_OK, data)
}
override fun onBackPressed() {
setResult()
super.onBackPressed()
}
override fun onResume() {
super.onResume()
scannerView.resume()
}
override fun onPause() {
super.onPause()
scannerView.pause()
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
return scannerView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event)
}
} | 33.354167 | 87 | 0.568395 |
64fd7822f3a7c969e89f33b4befff2e4101fc354 | 1,870 | java | Java | filelogger/src/main/java/fr/clementbesnier/filelogger/FLoggerWrapTagged.java | clemsciences/android-filelogger | fb42ca0c1b014b2306c57229f988302d0b882304 | [
"Apache-2.0"
] | null | null | null | filelogger/src/main/java/fr/clementbesnier/filelogger/FLoggerWrapTagged.java | clemsciences/android-filelogger | fb42ca0c1b014b2306c57229f988302d0b882304 | [
"Apache-2.0"
] | null | null | null | filelogger/src/main/java/fr/clementbesnier/filelogger/FLoggerWrapTagged.java | clemsciences/android-filelogger | fb42ca0c1b014b2306c57229f988302d0b882304 | [
"Apache-2.0"
] | null | null | null | package fr.clementbesnier.filelogger;
/**
* A logger with a hard coded tag that send logs to the supplied FLogger
*/
public class FLoggerWrapTagged {
protected final String tag;
protected final FLogger logger;
/**
* method called for every log call in case the file logger wasn't ready before
*
* @param level
*/
protected void assertLogger(FLogLevel level) {}
public FLoggerWrapTagged(FLogger logger, String tag) {
assertLogger(FLogLevel.V);
this.tag = tag;
this.logger = logger;
}
public int v(String message) {
assertLogger(FLogLevel.V);
logger.v(tag, message);
return 0;
}
public int v(String message, Throwable tr) {
assertLogger(FLogLevel.V);
logger.v(tag, message, tr);
return 0;
}
public int d(String message) {
assertLogger(FLogLevel.D);
logger.d(tag, message);
return 0;
}
public int d(String message, Throwable tr) {
assertLogger(FLogLevel.D);
logger.d(tag, message, tr);
return 0;
}
public int i(String message) {
assertLogger(FLogLevel.I);
logger.i(tag, message);
return 0;
}
public int i(String message, Throwable tr) {
assertLogger(FLogLevel.I);
logger.i(tag, message, tr);
return 0;
}
public int w(String message) {
assertLogger(FLogLevel.W);
logger.w(tag, message);
return 0;
}
public int w(String message, Throwable tr) {
assertLogger(FLogLevel.W);
logger.w(tag, message, tr);
return 0;
}
public int e(String message) {
assertLogger(FLogLevel.E);
logger.e(tag, message);
return 0;
}
public int e(String message, Throwable tr) {
assertLogger(FLogLevel.E);
logger.e(tag, message, tr);
return 0;
}
public int wtf(String message) {
assertLogger(FLogLevel.WTF);
logger.wtf(tag, message);
return 0;
}
public int wtf(String message, Throwable tr) {
assertLogger(FLogLevel.WTF);
logger.wtf(tag, message, tr);
return 0;
}
}
| 19.479167 | 80 | 0.689305 |
64f5152e87fc235a9a0a9d64bc61f2d7b313bff6 | 807 | java | Java | src/kh75/day1908010/soso/index/Index.java | jsc520/KH75 | 9f2f1776877c79ffbd6a8976d7a4ccb9be955f02 | [
"Apache-2.0"
] | 2 | 2019-09-23T06:31:11.000Z | 2019-09-23T06:31:13.000Z | src/kh75/day1908010/soso/index/Index.java | jsc520/KH75 | 9f2f1776877c79ffbd6a8976d7a4ccb9be955f02 | [
"Apache-2.0"
] | null | null | null | src/kh75/day1908010/soso/index/Index.java | jsc520/KH75 | 9f2f1776877c79ffbd6a8976d7a4ccb9be955f02 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright © 2019 金聖聰. All rights reserved.
*
* 功能描述:
* @Package: kh75.day1908010.soso.index
* @author: 金聖聰
* @date: 2019年8月11日 下午8:05:55
*/
package kh75.day1908010.soso.index;
import org.junit.Test;
import kh75.day1908010.soso.uis.MainUI;
/**
* Copyright: Copyright (c) 2019 金聖聰
*
* @ClassName: Index.java
* @Description: 该类的功能描述
*
* @version: v1.0.0
* @author: 金聖聰
* @date: 2019年8月11日 下午8:05:55
*
* Modification History:
* Date Author Version Description
*---------------------------------------------------------*
* 2019年8月11日 金聖聰 v1.0.0 修改原因
*/
public class Index {
/*public static void main(String[] args) {
new MainUI().mainUI();
}*/
@Test
public void test01() throws Exception {
new MainUI().mainUI();
}
}
| 20.692308 | 61 | 0.570012 |
5be72881754853ffcc07a4d0d2c8960217192bd4 | 2,261 | h | C | IvmpDotNet.Proxy/SDK/Shared/Network/CNetClientInterface.h | purm/IvmpDotNet | 8ec3b7819aba9d806f9a95b2b87e4375fdfdefe2 | [
"MIT"
] | 1 | 2021-01-26T05:52:04.000Z | 2021-01-26T05:52:04.000Z | IvmpDotNet.Proxy/SDK/Shared/Network/CNetClientInterface.h | purm/IvmpDotNet | 8ec3b7819aba9d806f9a95b2b87e4375fdfdefe2 | [
"MIT"
] | null | null | null | IvmpDotNet.Proxy/SDK/Shared/Network/CNetClientInterface.h | purm/IvmpDotNet | 8ec3b7819aba9d806f9a95b2b87e4375fdfdefe2 | [
"MIT"
] | null | null | null | //============== IV: Multiplayer - http://code.iv-multiplayer.com ==============
//
// File: CNetClientInterface.h
// Project: Shared
// Author(s): jenksta
// License: See LICENSE in root directory
//
//==============================================================================
#pragma once
#include "CNetStats.h"
#include "CPacket.h"
#include "CBitStream.h"
#include "PacketPriorities.h"
#include "PacketReliabilities.h"
#include "PacketChannels.h"
#include "RPCIdentifiers.h"
enum eConnectionAttemptResult
{
CONNECTION_ATTEMPT_STARTED,
INVALID_PARAMETER,
CANNOT_RESOLVE_DOMAIN_NAME,
ALREADY_CONNECTED_TO_ENDPOINT,
CONNECTION_ATTEMPT_ALREADY_IN_PROGRESS,
SECURITY_INITIALIZATION_FAILED,
NO_HOST_SET,
};
typedef void (* PacketHandler_t)(CPacket * pPacket);
class CNetClientInterface
{
public:
virtual ~CNetClientInterface() { }
virtual bool Startup() = 0;
virtual void Shutdown(int iBlockDuration) = 0;
virtual eConnectionAttemptResult Connect() = 0;
virtual void Disconnect() = 0;
virtual void Process() = 0;
virtual void SetPassword(String strPassword) = 0;
virtual const char * GetPassword() = 0;
virtual unsigned int Send(CBitStream * pBitStream, ePacketPriority priority, ePacketReliability reliability, char cOrderingChannel = PACKET_CHANNEL_DEFAULT) = 0;
virtual unsigned int RPC(RPCIdentifier rpcId, CBitStream * pBitStream, ePacketPriority priority, ePacketReliability reliability, char cOrderingChannel = PACKET_CHANNEL_DEFAULT) = 0;
virtual void SetHost(String strHost) = 0;
virtual const char * GetHost() = 0;
virtual void SetPort(unsigned short usPort) = 0;
virtual unsigned short GetPort() = 0;
virtual bool IsConnected() = 0;
virtual void SetPacketHandler(PacketHandler_t pfnPacketHandler) = 0;
virtual PacketHandler_t GetPacketHandler() = 0;
virtual CPlayerSocket * GetServerSocket() = 0;
virtual CNetStats * GetNetStats() = 0;
virtual int GetLastPing() = 0;
virtual int GetAveragePing() = 0;
};
| 38.322034 | 194 | 0.630252 |
ceb352a1af576d91f4cbea9f919acd65a730fd75 | 137 | kt | Kotlin | fuzzer/src/main/kotlin/ru/au/kotlinfuzzer/ast/entities/misc_interfaces.kt | ItsLastDay/KotlinFuzzer | 56f50fc307709443bb0c53972d0c239e709ce8f2 | [
"MIT"
] | 11 | 2017-12-16T15:21:37.000Z | 2021-09-30T14:02:36.000Z | fuzzer/src/main/kotlin/ru/au/kotlinfuzzer/ast/entities/misc_interfaces.kt | ItsLastDay/KotlinFuzzer | 56f50fc307709443bb0c53972d0c239e709ce8f2 | [
"MIT"
] | 1 | 2022-01-04T16:31:34.000Z | 2022-01-04T16:31:34.000Z | fuzzer/src/main/kotlin/ru/au/kotlinfuzzer/ast/entities/misc_interfaces.kt | ItsLastDay/KotlinFuzzer | 56f50fc307709443bb0c53972d0c239e709ce8f2 | [
"MIT"
] | 1 | 2018-08-01T07:16:22.000Z | 2018-08-01T07:16:22.000Z | package ru.au.kotlinfuzzer.ast.entities
import ru.au.kotlinfuzzer.ast.ASTNode
interface WithReceiver {
val receiverType: ASTNode?
} | 19.571429 | 39 | 0.79562 |