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
1d1164d05f61ab39e7cb1c0411f04d2daccd2009
184
ps1
PowerShell
addNetworkPrintersBack.ps1
vincentsirois/psDriverAndPrinterRemover
4a6eb3e04210f8f24c62d463cb2cc4833e7c1886
[ "MIT" ]
2
2019-02-06T13:25:33.000Z
2021-11-01T23:02:29.000Z
addNetworkPrintersBack.ps1
vincentsirois/psDriverAndPrinterRemover
4a6eb3e04210f8f24c62d463cb2cc4833e7c1886
[ "MIT" ]
null
null
null
addNetworkPrintersBack.ps1
vincentsirois/psDriverAndPrinterRemover
4a6eb3e04210f8f24c62d463cb2cc4833e7c1886
[ "MIT" ]
null
null
null
echo "Adding printers back..." $printers = (cat C:\temp\printDriversLog.txt) ForEach ($printer in $printers) { rundll32 printui.dll,PrintUIEntry /in /n$($printer) | Out-Null }
26.285714
64
0.690217
fc18e84d7988fe2b031007df485924b31bae861b
60
sql
SQL
fixtures/doctests/ddl/041_alter_column_type/input.sql
SKalt/pg_sql_parser_tests
1e22b4bf2ccecfe0544692e93a6e63113c9db054
[ "BSD-3-Clause" ]
null
null
null
fixtures/doctests/ddl/041_alter_column_type/input.sql
SKalt/pg_sql_parser_tests
1e22b4bf2ccecfe0544692e93a6e63113c9db054
[ "BSD-3-Clause" ]
null
null
null
fixtures/doctests/ddl/041_alter_column_type/input.sql
SKalt/pg_sql_parser_tests
1e22b4bf2ccecfe0544692e93a6e63113c9db054
[ "BSD-3-Clause" ]
null
null
null
ALTER TABLE products ALTER COLUMN price TYPE numeric(10,2);
30
59
0.8
507e279098175d9122f182fd0400d28174d607aa
400
swift
Swift
native/mac/mac/Views/ObservableNavigator.swift
eneim/Press
ad47aa174f6e8350b457591c8c5aa224b721d101
[ "Apache-2.0" ]
1,514
2019-12-11T22:49:41.000Z
2022-03-24T01:53:26.000Z
native/mac/mac/Views/ObservableNavigator.swift
eneim/Press
ad47aa174f6e8350b457591c8c5aa224b721d101
[ "Apache-2.0" ]
51
2019-12-12T01:01:25.000Z
2022-03-20T22:27:17.000Z
native/mac/mac/Views/ObservableNavigator.swift
eneim/Press
ad47aa174f6e8350b457591c8c5aa224b721d101
[ "Apache-2.0" ]
94
2019-12-12T01:47:25.000Z
2022-02-09T05:58:13.000Z
// // Created by Saket Narayan on 11/1/20. // Copyright (c) 2020 Saket Narayan. All rights reserved. // import Foundation import Combine import shared class ObservableNavigator: Navigator { @Published var screenKey: ScreenKey? = nil func lfg(screen: ScreenKey) { screenKey = screen } func listen<T>(_ type: T.Type) -> AnyPublisher<T, Never> { return $screenKey.ofType(type) } }
19.047619
60
0.6975
0a35397a3f56051a07c66d6e52ca766779f08396
102
ts
TypeScript
packages/react/src/providers/index.ts
WWNorton/design-system
0bbd5db6a04d285071a43dadbd13d55eb3bb52e0
[ "MIT" ]
17
2020-07-22T16:04:29.000Z
2022-03-29T18:39:31.000Z
packages/react/src/providers/index.ts
WWNorton/design-system
0bbd5db6a04d285071a43dadbd13d55eb3bb52e0
[ "MIT" ]
258
2020-07-31T22:04:31.000Z
2022-03-31T23:03:40.000Z
packages/react/src/providers/index.ts
WWNorton/design-system
0bbd5db6a04d285071a43dadbd13d55eb3bb52e0
[ "MIT" ]
9
2020-11-25T19:25:46.000Z
2022-03-19T17:05:25.000Z
// All public configuration providers export * from './AppProvider'; export * from './ThemeProvider';
25.5
37
0.735294
b9586c7a9f88d879450de4744c585aac3e8b2623
2,444
dart
Dart
lib/app/global/custom_dio/auth_interceptors.dart
murilinhoPs/flutter_api_bt
f64db6a389685d6bb0ff564c482b01694c99853f
[ "MIT" ]
null
null
null
lib/app/global/custom_dio/auth_interceptors.dart
murilinhoPs/flutter_api_bt
f64db6a389685d6bb0ff564c482b01694c99853f
[ "MIT" ]
null
null
null
lib/app/global/custom_dio/auth_interceptors.dart
murilinhoPs/flutter_api_bt
f64db6a389685d6bb0ff564c482b01694c99853f
[ "MIT" ]
null
null
null
import 'package:challenge_bt_app/app/global/custom/api_consts.dart'; import 'package:challenge_bt_app/app/global/custom_dio/custom_dio.dart'; import 'package:challenge_bt_app/app/global/services/local_db_service.dart'; import 'package:dio/dio.dart'; import 'package:get/get.dart'; class AuthInterceptors implements InterceptorsWrapper { String token; String refresh; @override Future onRequest(RequestOptions options) async { final globalDio = Get.find<GlobalDio>(); final localDb = Get.find<LocalDatabase>(); token = await localDb.getItem(ACCESSTOKEN); refresh = await localDb.getItem(REFRESHTOKEN); Map<String, dynamic> customHeaders = {'Authorization': token, REFRESHTOKENHEADER: refresh}; if (token != null) { globalDio.dio.lock(); print(token); print(refresh); options.headers.addAll(customHeaders); globalDio.dio.unlock(); print("RequestAuth: ${options.method} -> Path: ${options.path}"); return options; } print("RequestAuth: ${options.method} -> Path: ${options.path}"); return options; } @override Future onResponse(Response response) async { print("ResponseAuth: ${response.statusCode} -> Path: ${response.data}"); if (!(response.data is List)) if (response.data['refreshAccess'] != null) { final globalDio = Get.find<GlobalDio>(); final localDb = Get.find<LocalDatabase>(); print(response.data['refreshAccess']); RequestOptions options = response.request; globalDio.dio.lock(); globalDio.dio.interceptors.responseLock.lock(); globalDio.dio.interceptors.errorLock.lock(); localDb.setItemString(ACCESSTOKEN, response.data['accessToken']); options.headers['Authorization'] = await localDb.getItem(ACCESSTOKEN); print(options.headers); globalDio.dio.unlock(); globalDio.dio.interceptors.responseLock.unlock(); globalDio.dio.interceptors.errorLock.unlock(); return globalDio.dio.request(options.path, options: options); } print(response); return response; } @override Future onError(DioError err) async { print('''ErrorAuth: ${err.response?.statusCode} -> Data: ${err.response?.data}-> Path: ${err.message}'''); if (!(err.response.data is List)) if (err.response.data['message'] == 'Refresh token errado ou inválido. Faça login novamente') Get.toNamed('/login'); return err; } }
28.091954
95
0.684124
4aa84017ebee8b9c58e8b251eba346ec93a940ef
978
cs
C#
GuitarStore/GuitarStore.ApiGateway/MiddleWares/ExceptionsMiddleware.cs
Kamil9223/GuitarStore
571a1243626a463a5ee495fa1806fb8b5c000216
[ "MIT" ]
null
null
null
GuitarStore/GuitarStore.ApiGateway/MiddleWares/ExceptionsMiddleware.cs
Kamil9223/GuitarStore
571a1243626a463a5ee495fa1806fb8b5c000216
[ "MIT" ]
null
null
null
GuitarStore/GuitarStore.ApiGateway/MiddleWares/ExceptionsMiddleware.cs
Kamil9223/GuitarStore
571a1243626a463a5ee495fa1806fb8b5c000216
[ "MIT" ]
null
null
null
using Application.Exceptions; using Newtonsoft.Json; using System.Net; namespace GuitarStore.ApiGateway.MiddleWares; public class ExceptionsMiddleware : IMiddleware { public async Task InvokeAsync(HttpContext context, RequestDelegate next) { try { await next(context); } catch (Exception ex) { await HandleException(ex, context); } } private async Task HandleException(Exception ex, HttpContext context) { var responseModel = ex switch { ValidationException => new ResponseModel(HttpStatusCode.BadRequest, ex.Message, null), _ => new ResponseModel(HttpStatusCode.InternalServerError, ex.Message, null) }; context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)responseModel.HttpStatusCode; await context.Response.WriteAsync(JsonConvert.SerializeObject(responseModel)); } }
27.942857
98
0.667689
e8eedebb919e5d37cf8c9784ea6066d77842d262
4,757
py
Python
create_cpu_config.py
ttungl/HeteroArchGen4M2S
85752243dc38b3d44207b6b200d6ebc88c2be8ea
[ "MIT" ]
5
2018-04-29T15:33:01.000Z
2021-11-17T11:41:45.000Z
create_cpu_config.py
berwingan/HeteroArchGen4M2S
4922711cdfe20d120dc525a6c7cb8cd2230cba09
[ "MIT" ]
null
null
null
create_cpu_config.py
berwingan/HeteroArchGen4M2S
4922711cdfe20d120dc525a6c7cb8cd2230cba09
[ "MIT" ]
7
2017-07-28T02:29:59.000Z
2021-11-20T12:01:40.000Z
#!/usr/bin/env python # =========================================================================== # Copyright 2017 `Tung Thanh Le` # Email: ttungl at gmail dot com # Heterogeneous Architecture Configurations Generator for Multi2Sim simulator # (aka, `HeteroArchGen4M2S`) # `HeteroArchGen4M2S` is free software, which is freely to be # redistributed and modified it under the terms of # the GNU General Public License as published by # the Free Software Foundation. # For more details `http://www.gnu.org/licenses` # `HeteroArchGen4M2S` is written to help you configure M2S # easily, but non-warranty and non-mechantability. # ============================================================================ # # `create_cpuconfig` is part of M2S configuration files. # ========================================================== # Description: This generates `x86_cpuconfig` file for M2S # Input: # Output: # Note: Each core can contain several threads. # ========================================================== # E.g., # num_of_cores = 16 : number of cores in the CPUs # num_of_threads = 1 : number of threads in each core # ROB_size = 128 : number of in-flight instructions allowed # pipelines_size = 4: decode/dispatch/issue/commit width # bimod_size = 4096 : Size of local predictor (larger size means less aliasing in history table) # bpred_size = 1024 : Size of global predictor (larger size means longer global history register) # ========================================================== import math # to roundup the float numbers. # benchmark, fast_forward: binary flag, enables fastforward past sequential portion of benchmark def create_cpuconfig( num_of_cores, cpu_frequency, num_of_threads, ROB_size, pipelines_size, bimod_size, bpred_size): # Check inputs validation assert(num_of_cores>=4), "Error! Number of CPU cores must be at least 4." assert(num_of_threads>=0), "Error! Number of threads should be at least zero." # Adapted the additional parameters from M2StoMcPAT of Caleb (Univ. Maryland College Park) IQ_ratio = 0.4; # size of instruction (issue) queue w.r.t. ROB LSQ_ratio = 0.5; # size of LSQ w.r.t. ROB RF_ratio = 1; # size of register file w.r.t. ROB RF_int_ratio = 0.666666;# (2/3) ratio of int vs FP regissters in the RF Fetch_Queue_size = 64; # queue holding instructions fetched from I$ waiting to be decoded history_size = 8; # size of the local histroy table entries # File name f = open('configs/x86_cpuconfig', 'w'); # General f.write("[ General ]\n"); f.write(" Cores = %0.f\n" % num_of_cores); f.write(" Threads = %0.f\n" % num_of_threads); f.write(" Frequency = %0.f\n" % cpu_frequency); f.write("\n"); # Pipeline f.write("[ Pipeline ]\n"); f.write(" DecodeWidth = %0.f\n" % pipelines_size); f.write(" DispatchWidth = %0.f\n" % pipelines_size); f.write(" IssueWidth = %0.f\n" % pipelines_size); f.write(" CommitWidth = %0.f\n" % pipelines_size); f.write("\n"); # Queues f.write("[ Queues ]\n"); f.write(" FetchQueueSize = %0.f\n" % Fetch_Queue_size); f.write(" RobSize = %0.f\n" % ROB_size); f.write(" IqSize = %0.f\n" % (IQ_ratio*ROB_size)); f.write(" LsqSize = %0.f\n" % (LSQ_ratio*ROB_size)); f.write(" RfIntSize = %0.f\n" % (RF_ratio*(RF_int_ratio)*ROB_size)); f.write(" RfFpSize = %0.f\n" % (RF_ratio*(1-RF_int_ratio)*ROB_size)); f.write("\n"); # FunctionalUnits f.write("[ FunctionalUnits ]\n"); f.write(" IntAdd.Count = %0.f\n" % pipelines_size); f.write(" IntMult.Count = %0.f\n" % (pipelines_size/4)); f.write(" IntDiv.Count = %0.f\n" % math.ceil(pipelines_size/8+0.55)); # added 0.55 to roundup the float number. f.write(" EffAddr.Count = %0.f\n" % pipelines_size); f.write(" Logic.Count = %0.f\n" % pipelines_size); f.write(" FpSimple.Count = %0.f\n" % pipelines_size); f.write(" FpAdd.Count = %0.f\n" % pipelines_size); f.write(" FpMult.Count = %0.f\n" % (pipelines_size/4)); f.write(" FpDiv.Count = %0.f\n" % math.ceil(pipelines_size/8+0.55)); # added 0.55 to roundup the float number. f.write(" FpComplex.Count = %0.f\n" % math.ceil(pipelines_size/8+0.55)); # added 0.55 to roundup the float number. f.write("\n"); # BranchPredictor f.write("[ BranchPredictor ]\n"); f.write(" Kind = Combined\n"); f.write(" Bimod.Size = %0.f\n" % bimod_size); f.write(" Choice.Size = %0.f\n" % bimod_size); f.write(" TwoLevel.L1Size = %0.f\n" % bpred_size); f.write(" TwoLevel.L2Size = 1\n"); f.write(" TwoLevel.HistorySize = %0.f\n" % history_size); f.write(" BTB.Sets = 1024\n"); f.write(" BTB.Assoc = 1"); # close f.close(); ## Tested # def main(): # create_cpuconfig(16, 1, 128, 4, 4096, 1024, 1); # print "This %s file is just executed!" % __file__ # if __name__ == "__main__": main()
41.008621
115
0.634433
ce70e6060e526b4865f802a31a5d3e36d6c51bdb
1,291
kt
Kotlin
src/main/kotlin/org/jetbrains/fortran/lang/stubs/FortranFileStub.kt
LChernigovskaya/fortran-plugin
6750933e79c5bf420937160aecedc39b142ca5f6
[ "Apache-2.0" ]
76
2016-12-01T23:39:49.000Z
2022-03-21T09:25:56.000Z
src/main/kotlin/org/jetbrains/fortran/lang/stubs/FortranFileStub.kt
LChernigovskaya/fortran-plugin
6750933e79c5bf420937160aecedc39b142ca5f6
[ "Apache-2.0" ]
75
2017-01-05T15:08:03.000Z
2021-12-08T12:59:42.000Z
src/main/kotlin/org/jetbrains/fortran/lang/stubs/FortranFileStub.kt
LChernigovskaya/fortran-plugin
6750933e79c5bf420937160aecedc39b142ca5f6
[ "Apache-2.0" ]
20
2017-03-06T20:56:51.000Z
2021-04-22T19:06:46.000Z
package org.jetbrains.fortran.lang.stubs import com.intellij.lang.ASTNode import com.intellij.psi.PsiFile import com.intellij.psi.StubBuilder import com.intellij.psi.stubs.* import com.intellij.psi.tree.IStubFileElementType import org.jetbrains.fortran.FortranLanguage import org.jetbrains.fortran.lang.parser.FortranFileParser import org.jetbrains.fortran.lang.psi.FortranFile class FortranFileStub(file: FortranFile?) : PsiFileStubImpl<FortranFile>(file) { override fun getType() = Type object Type : IStubFileElementType<FortranFileStub>(FortranLanguage) { override fun parseContents(chameleon: ASTNode): ASTNode? { return FortranFileParser.parse(this, chameleon) } override fun getStubVersion(): Int = 2 override fun getBuilder(): StubBuilder = object : DefaultStubBuilder() { override fun createStubForFile(file: PsiFile): StubElement<*> = FortranFileStub(file as FortranFile) } override fun serialize(stub: FortranFileStub, dataStream: StubOutputStream) { } override fun deserialize(dataStream: StubInputStream, parentStub: StubElement<*>?): FortranFileStub { return FortranFileStub(null) } override fun getExternalId(): String = "Fortran.file" } }
35.861111
112
0.728892
71d5ccd3fdd55de8c133ab2a2ad4efb49c934d5c
668
tsx
TypeScript
src/components/common/Layout/Layout.tsx
solaris-protocol/solaris-automations-ui
e3db8ae78ac31b74d6b61d4500dd519500f40790
[ "Apache-2.0" ]
null
null
null
src/components/common/Layout/Layout.tsx
solaris-protocol/solaris-automations-ui
e3db8ae78ac31b74d6b61d4500dd519500f40790
[ "Apache-2.0" ]
null
null
null
src/components/common/Layout/Layout.tsx
solaris-protocol/solaris-automations-ui
e3db8ae78ac31b74d6b61d4500dd519500f40790
[ "Apache-2.0" ]
null
null
null
import React, { FC } from 'react'; import { styled } from '@linaria/react'; import { SideBar } from './SideBar'; export const Wrapper = styled.div` display: flex; min-width: 100%; height: 100%; `; export const Content = styled.div` position: relative; flex: 1; padding: 20px; &::before { position: absolute; top: 0; right: 0; bottom: 0; left: 0; z-index: -1; background: url('./lines.svg') no-repeat -200px 0; background-size: 2244px 686px; content: ''; } `; export const Layout: FC = ({ children }) => { return ( <Wrapper> <SideBar /> <Content>{children}</Content> </Wrapper> ); };
15.904762
54
0.576347
457369241eeac2c1950a432c4fbb8e47e9bf8c53
724
dart
Dart
lib/src/domain/entities/shopping_list.dart
Gonzaa25/compras_app
c8f7ed9fcbd6df48b871ee9d3640c222a61d1fa5
[ "MIT" ]
null
null
null
lib/src/domain/entities/shopping_list.dart
Gonzaa25/compras_app
c8f7ed9fcbd6df48b871ee9d3640c222a61d1fa5
[ "MIT" ]
null
null
null
lib/src/domain/entities/shopping_list.dart
Gonzaa25/compras_app
c8f7ed9fcbd6df48b871ee9d3640c222a61d1fa5
[ "MIT" ]
null
null
null
import 'package:compras_app/src/domain/entities/item.dart'; class ShoppingList { ShoppingList({ required this.id, required this.createdAt, required this.name, required this.items, }); final int? id; final DateTime? createdAt; final String? name; final List<Item>? items; @override String toString() { return 'ShoppingList(id: $id, createdAt: $createdAt' ',name: $name, items: $items)'; } ShoppingList copyWith({ int? id, DateTime? createdAt, String? name, List<Item>? items, }) { return ShoppingList( id: id ?? this.id, createdAt: createdAt ?? this.createdAt, name: name ?? this.name, items: items ?? this.items, ); } }
20.111111
59
0.621547
23ee616fcbee7d5211b9ac86f40cc766fe8bed2a
203
sql
SQL
students/y2337/Artamonov_Artyom/laboratory_works/L3_sqlite+postgresql/Pr3_1sqlite/MyCommands.sql
ArtyomArtamonov/ITMO_FSPO_DataBases_2020-2021
b75a9038c1949c175e77cb6051a60716c05ba0dc
[ "MIT" ]
1
2021-05-03T18:42:59.000Z
2021-05-03T18:42:59.000Z
students/y2337/Artamonov_Artyom/laboratory_works/L3_sqlite+postgresql/Pr3_1sqlite/MyCommands.sql
ArtyomArtamonov/ITMO_FSPO_DataBases_2020-2021
b75a9038c1949c175e77cb6051a60716c05ba0dc
[ "MIT" ]
null
null
null
students/y2337/Artamonov_Artyom/laboratory_works/L3_sqlite+postgresql/Pr3_1sqlite/MyCommands.sql
ArtyomArtamonov/ITMO_FSPO_DataBases_2020-2021
b75a9038c1949c175e77cb6051a60716c05ba0dc
[ "MIT" ]
null
null
null
insert into Movie(title, year, director) values("Space Odyssey", 1969, "Stanley Cubrik"); update Movie set title = "2001: A Space Odyssey" where mID = 3; delete from Movie where title = "Space Odyssey";
50.75
89
0.73399
e3926bad1c3164b51df8a058a2a7e0ac68ca54c0
7,842
asm
Assembly
Transynther/x86/_processed/NONE/_xt_/i9-9900K_12_0xca_notsx.log_21829_665.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/NONE/_xt_/i9-9900K_12_0xca_notsx.log_21829_665.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/NONE/_xt_/i9-9900K_12_0xca_notsx.log_21829_665.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
3
2020-07-14T17:07:07.000Z
2022-03-21T01:12:22.000Z
.global s_prepare_buffers s_prepare_buffers: push %r14 push %r15 push %r9 push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_D_ht+0xe741, %rsi lea addresses_WC_ht+0xf1b5, %rdi clflush (%rsi) xor %r14, %r14 mov $39, %rcx rep movsw nop nop nop xor $31614, %rdx lea addresses_WT_ht+0xc703, %rsi lea addresses_normal_ht+0x1b4ce, %rdi nop nop nop nop and $3135, %rbp mov $6, %rcx rep movsq nop nop nop sub %rcx, %rcx lea addresses_A_ht+0x9e1b, %rsi nop nop nop sub $15760, %r15 movl $0x61626364, (%rsi) nop nop add %rdi, %rdi lea addresses_WC_ht+0x12135, %rsi lea addresses_UC_ht+0xa635, %rdi clflush (%rsi) nop nop nop cmp %rbp, %rbp mov $58, %rcx rep movsb nop xor %rbp, %rbp lea addresses_WT_ht+0x6e35, %rdi clflush (%rdi) nop nop and $5815, %rsi mov (%rdi), %ebp nop nop nop nop xor $6112, %rsi lea addresses_A_ht+0x11335, %r14 nop nop nop nop nop cmp $33526, %rbp movl $0x61626364, (%r14) nop sub $59800, %rsi lea addresses_UC_ht+0x15135, %r15 clflush (%r15) nop nop nop nop nop and $42025, %rdx movw $0x6162, (%r15) dec %rbp lea addresses_A_ht+0x1dde9, %rdx nop nop nop cmp %rbp, %rbp mov $0x6162636465666768, %rcx movq %rcx, (%rdx) nop nop nop sub %r14, %r14 lea addresses_D_ht+0x1cac5, %rcx nop nop add $25041, %rdi movups (%rcx), %xmm2 vpextrq $1, %xmm2, %r15 nop nop nop nop nop dec %rdx lea addresses_normal_ht+0x19455, %rdx nop nop nop nop nop and %r14, %r14 movb $0x61, (%rdx) nop nop nop nop nop sub %rdi, %rdi lea addresses_WT_ht+0xc435, %rsi lea addresses_WT_ht+0x1c235, %rdi nop nop sub $1395, %r9 mov $47, %rcx rep movsl nop nop nop nop add %r14, %r14 lea addresses_A_ht+0x7235, %rsi lea addresses_UC_ht+0x7c55, %rdi nop nop cmp $16371, %rdx mov $55, %rcx rep movsb nop nop nop nop add $50767, %r9 lea addresses_WT_ht+0x148b5, %r15 nop xor $6253, %rbp mov (%r15), %rdi nop nop and $19601, %rbp lea addresses_WT_ht+0xa35, %rsi lea addresses_A_ht+0x7835, %rdi nop nop sub %r14, %r14 mov $114, %rcx rep movsl nop nop cmp $18934, %rdi lea addresses_normal_ht+0x7635, %rbp nop nop nop inc %r9 mov $0x6162636465666768, %rdx movq %rdx, (%rbp) nop nop nop nop and %rcx, %rcx pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r9 pop %r15 pop %r14 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r8 push %r9 push %rdx push %rsi // Faulty Load lea addresses_PSE+0x11a35, %rsi nop nop nop add %r11, %r11 mov (%rsi), %r12d lea oracles, %r11 and $0xff, %r12 shlq $12, %r12 mov (%r11,%r12,1), %r12 pop %rsi pop %rdx pop %r9 pop %r8 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_PSE', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 0}} [Faulty Load] {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_PSE', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'same': False, 'congruent': 1, 'type': 'addresses_D_ht'}, 'dst': {'same': False, 'congruent': 5, 'type': 'addresses_WC_ht'}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 1, 'type': 'addresses_WT_ht'}, 'dst': {'same': False, 'congruent': 0, 'type': 'addresses_normal_ht'}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 1}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 8, 'type': 'addresses_WC_ht'}, 'dst': {'same': False, 'congruent': 10, 'type': 'addresses_UC_ht'}} {'OP': 'LOAD', 'src': {'same': True, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 10}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 5}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_UC_ht', 'NT': False, 'AVXalign': False, 'size': 2, 'congruent': 8}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_A_ht', 'NT': False, 'AVXalign': True, 'size': 8, 'congruent': 1}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_D_ht', 'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 3}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 2}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 9, 'type': 'addresses_WT_ht'}, 'dst': {'same': False, 'congruent': 11, 'type': 'addresses_WT_ht'}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 10, 'type': 'addresses_A_ht'}, 'dst': {'same': False, 'congruent': 3, 'type': 'addresses_UC_ht'}} {'OP': 'LOAD', 'src': {'same': False, 'type': 'addresses_WT_ht', 'NT': False, 'AVXalign': True, 'size': 8, 'congruent': 6}} {'OP': 'REPM', 'src': {'same': False, 'congruent': 11, 'type': 'addresses_WT_ht'}, 'dst': {'same': False, 'congruent': 7, 'type': 'addresses_A_ht'}} {'OP': 'STOR', 'dst': {'same': False, 'type': 'addresses_normal_ht', 'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 9}} {'33': 21829} 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 */
32.94958
2,999
0.658633
bcd5709a6179f7e84a0585ff08884fb26d4e59f4
3,799
tab
SQL
parser/src/main/resources/parser/dicts/iso639/language-native.tab
Gustibimo/backend
f642e9a8cae5195586d300f6e63458a4838d12f2
[ "Apache-2.0" ]
6
2020-03-14T12:25:02.000Z
2022-03-17T20:26:46.000Z
parser/src/main/resources/parser/dicts/iso639/language-native.tab
Gustibimo/backend
f642e9a8cae5195586d300f6e63458a4838d12f2
[ "Apache-2.0" ]
647
2017-10-23T14:28:28.000Z
2020-03-12T17:41:47.000Z
parser/src/main/resources/parser/dicts/iso639/language-native.tab
Gustibimo/backend
f642e9a8cae5195586d300f6e63458a4838d12f2
[ "Apache-2.0" ]
9
2020-04-17T16:02:43.000Z
2022-03-26T15:57:07.000Z
ISO english native abk Abkhazian Abkhazian aar Afar Afar afr Afrikaans Afrikaans aka Akan Akan sqi Albanian shqip amh Amharic Amharic ara Arabic العربية arg Aragonese Aragonese hye Armenian Armenian asm Assamese Assamese ava Avaric Avaric ave Avestan Avestan aym Aymara Aymara aze Azerbaijani Azerbaijani bam Bambara Bambara bak Bashkir Bashkir eus Basque Basque bel Belarusian беларускі ben Bengali Bengali bih Bihari Bihari bis Bislama Bislama bos Bosnian Bosnian bre Breton Breton bul Bulgarian български mya Burmese Burmese cat Catalan català cha Chamorro Chamorro che Chechen Chechen zho Chinese 中文 chu Church Slavic Church Slavic chv Chuvash Chuvash cor Cornish Cornish cos Corsican Corsican cre Cree Cree hrv Croatian hrvatski ces Czech čeština dan Danish Dansk div Divehi Divehi nld Dutch Nederlands dzo Dzongkha Dzongkha eng English English epo Esperanto Esperanto est Estonian Eesti ewe Ewe Ewe fao Faroese Faroese fij Fijian Fijian fin Finnish suomi fra French français fry Frisian Frisian ful Fulah Fulah glg Gallegan Gallegan lug Ganda Ganda kat Georgian Georgian deu German Deutsch ell Greek Ελληνικά kal Greenlandic Greenlandic grn Guarani Guarani guj Gujarati Gujarati hat Haitian Haitian hau Hausa Hausa heb Hebrew עברית her Herero Herero hin Hindi हिंदी hmo Hiri Motu Hiri Motu hun Hungarian magyar isl Icelandic íslenska ido Ido Ido ibo Igbo Igbo ind Indonesian Bahasa Indonesia ina Interlingua Interlingua ile Interlingue Interlingue iku Inuktitut Inuktitut ipk Inupiaq Inupiaq gle Irish Gaeilge ita Italian italiano jpn Japanese 日本語 jav Javanese Javanese kan Kannada Kannada kau Kanuri Kanuri kas Kashmiri Kashmiri kaz Kazakh Kazakh khm Khmer Khmer kik Kikuyu Kikuyu kin Kinyarwanda Kinyarwanda kir Kirghiz Kirghiz kom Komi Komi kon Kongo Kongo kor Korean 한국어 kur Kurdish Kurdish kua Kwanyama Kwanyama lao Lao Lao lat Latin Latin lav Latvian Latviešu lim Limburgish Limburgish lin Lingala Lingala lit Lithuanian Lietuvių lub Luba-Katanga Luba-Katanga ltz Luxembourgish Luxembourgish mkd Macedonian македонски mlg Malagasy Malagasy msa Malay Bahasa Melayu mal Malayalam Malayalam mlt Maltese Malti glv Manx Manx mri Maori Maori mar Marathi Marathi mah Marshallese Marshallese mol Moldavian Moldavian mon Mongolian Mongolian nau Nauru Nauru nav Navajo Navajo ndo Ndonga Ndonga nep Nepali Nepali nde North Ndebele North Ndebele sme Northern Sami Northern Sami nob Norwegian Bokmål Norwegian Bokmål nno Norwegian Nynorsk Norwegian Nynorsk nor Norwegian norsk nya Nyanja Nyanja oci Occitan Occitan oji Ojibwa Ojibwa ori Oriya Oriya orm Oromo Oromo oss Ossetian Ossetian pli Pali Pali pan Panjabi Panjabi fas Persian Persian pol Polish polski por Portuguese português pus Pushto Pushto que Quechua Quechua roh Raeto-Romance Raeto-Romance ron Romanian română run Rundi Rundi rus Russian русский smo Samoan Samoan sag Sango Sango san Sanskrit Sanskrit srd Sardinian Sardinian gla Scottish Gaelic Scottish Gaelic srp Serbian Српски sna Shona Shona iii Sichuan Yi Sichuan Yi snd Sindhi Sindhi sin Sinhalese Sinhalese slk Slovak Slovenčina slv Slovenian Slovenščina som Somali Somali nbl South Ndebele South Ndebele sot Southern Sotho Southern Sotho spa Spanish español sun Sundanese Sundanese swa Swahili Swahili ssw Swati Swati swe Swedish svenska tgl Tagalog Tagalog tah Tahitian Tahitian tgk Tajik Tajik tam Tamil Tamil tat Tatar Tatar tel Telugu Telugu tha Thai ไทย bod Tibetan Tibetan tir Tigrinya Tigrinya ton Tonga Tonga tso Tsonga Tsonga tsn Tswana Tswana tur Turkish Türkçe tuk Turkmen Turkmen twi Twi Twi uig Uighur Uighur ukr Ukrainian українська urd Urdu Urdu uzb Uzbek Uzbek ven Venda Venda vie Vietnamese Tiếng Việt vol Volapük Volapük wln Walloon Walloon cym Welsh Welsh wol Wolof Wolof xho Xhosa Xhosa yid Yiddish Yiddish yor Yoruba Yoruba zha Zhuang Zhuang zul Zulu Zulu
20.315508
39
0.845222
b26dadf290261146620c3ecfc6df51d77094a282
7,515
kt
Kotlin
app/src/main/kotlin/com/goofy/goober/composelab/lists/animations/SlideItemVisibilityZStack.kt
drinkthestars/compose-lab
43de36417f86404d5c86a69e452426792a058eda
[ "Apache-2.0" ]
5
2021-12-05T20:01:03.000Z
2022-01-27T13:06:25.000Z
app/src/main/kotlin/com/goofy/goober/composelab/lists/animations/SlideItemVisibilityZStack.kt
drinkthestars/compose-lab
43de36417f86404d5c86a69e452426792a058eda
[ "Apache-2.0" ]
null
null
null
app/src/main/kotlin/com/goofy/goober/composelab/lists/animations/SlideItemVisibilityZStack.kt
drinkthestars/compose-lab
43de36417f86404d5c86a69e452426792a058eda
[ "Apache-2.0" ]
null
null
null
package com.goofy.goober.composelab.lists.animations import androidx.annotation.DrawableRes import androidx.compose.animation.EnterExitState import androidx.compose.animation.core.animateFloat import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentHeight import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import com.goofy.goober.composelab.R import com.goofy.goober.composelab.animations.Direction import com.goofy.goober.composelab.animations.SlideAnimatedVisibilityLab import com.goofy.goober.composelab.animations.SlideAnimatedVisibilityState import java.util.UUID private const val RotationDeg = 90f @Composable fun SlideItemVisibilityZStack() { Box(modifier = Modifier.fillMaxSize()) { val list = remember { VinylImages.map { ListItem(painterRes = it) } } ZStack(list, modifier = Modifier.align(Alignment.Center)) Controls(list, modifier = Modifier.align(Alignment.BottomCenter)) } } @Composable private fun ZStack(list: List<ListItem>, modifier: Modifier = Modifier) { Box( modifier = modifier, contentAlignment = Alignment.Center ) { list.forEachIndexed { index, item -> key(item.id) { SlideAnimatedVisibilityLab( modifier = Modifier .align(Alignment.Center) .offset(y = 16.dp * -index), state = item.visibilityState ) { val animatedRotZ by transition.animateFloat(label = "z rotation") { enterExitState -> rotationDegrees(enterExitState, item.visibilityState) } Image( modifier = Modifier .width(200.dp) .aspectRatio(1f) .graphicsLayer { rotationZ = animatedRotZ }, painter = painterResource(item.painterRes), contentDescription = "", contentScale = ContentScale.FillWidth ) } } } } } @Composable private fun Controls( list: List<ListItem>, modifier: Modifier = Modifier ) { var topIndex by remember { mutableStateOf(list.size - 1) } InfoAndControls( list[topIndex].visibilityState, onRemoveClick = { list[topIndex].visibilityState.apply { visibility.targetState = false } topIndex = (topIndex - 1).coerceAtLeast(0) }, onRestoreClick = { topIndex = (topIndex + 1).coerceAtMost(list.size - 1) list.getOrNull(topIndex)?.visibilityState?.apply { visibility.targetState = true } }, onDirectionChange = { list[topIndex].visibilityState.apply { inDirection.value = inDirection.value.next() outDirection.value = outDirection.value.next() } }, modifier = modifier ) } @Composable private fun InfoAndControls( state: SlideAnimatedVisibilityState, onRemoveClick: () -> Unit, onRestoreClick: () -> Unit, onDirectionChange: () -> Unit, modifier: Modifier = Modifier ) { Column( modifier .fillMaxWidth() .wrapContentHeight(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Spacer(modifier = Modifier.height(100.dp)) Row( Modifier .fillMaxWidth() .wrapContentSize() .padding(12.dp) .background(Color.Transparent) ) { Column(Modifier.wrapContentSize()) { Button(onClick = onRemoveClick) { Text("remove") } Spacer(modifier = Modifier.height(12.dp)) Button(onClick = onRestoreClick) { Text("restore") } } Spacer(modifier = Modifier.width(60.dp)) Button(onClick = onDirectionChange) { Text("toggle removal direction") } } Spacer(modifier = Modifier.height(40.dp)) Text( text = "in=${state.inDirection.value.javaClass.simpleName} " + "out=${state.outDirection.value.javaClass.simpleName}" ) Spacer(modifier = Modifier.height(80.dp)) } } @Composable private fun rotationDegrees( enterExitState: EnterExitState, state: SlideAnimatedVisibilityState ) = when (enterExitState) { EnterExitState.PreEnter -> { when (state.inDirection.value) { Direction.In.Left -> -RotationDeg Direction.In.Right -> RotationDeg Direction.In.Up -> 0f Direction.In.Down -> 0f } } EnterExitState.Visible -> 0f EnterExitState.PostExit -> { when (state.outDirection.value) { Direction.Out.Left -> -RotationDeg Direction.Out.Right -> RotationDeg Direction.Out.Up -> 0f Direction.Out.Down -> 0f } } } @Stable private fun Direction.In.next(): Direction.In { return when (this) { Direction.In.Left -> Direction.In.Right Direction.In.Right -> Direction.In.Up Direction.In.Up -> Direction.In.Down Direction.In.Down -> Direction.In.Left } } @Stable private fun Direction.Out.next(): Direction.Out { return when (this) { Direction.Out.Left -> Direction.Out.Right Direction.Out.Right -> Direction.Out.Up Direction.Out.Up -> Direction.Out.Down Direction.Out.Down -> Direction.Out.Left } } @Immutable private data class ListItem( val visibilityState: SlideAnimatedVisibilityState = SlideAnimatedVisibilityState(), val id: String = UUID.randomUUID().toString(), @DrawableRes val painterRes: Int ) private val VinylImages = listOf( R.drawable.vinyl1, R.drawable.vinyl2, R.drawable.vinyl3, R.drawable.vinyl4, R.drawable.vinyl5 )
33.851351
105
0.640852
80af8ed325f0dac0f89ac35f906febaa0481992e
1,139
java
Java
Mage/src/main/java/mage/game/command/emblems/LilianaOfTheDarkRealmsEmblem.java
amc8391/mage
dfaf9e0a51b4ac81f513cea4f235345d7eb4fb50
[ "MIT" ]
1,444
2015-01-02T00:25:38.000Z
2022-03-31T13:57:18.000Z
Mage/src/main/java/mage/game/command/emblems/LilianaOfTheDarkRealmsEmblem.java
amc8391/mage
dfaf9e0a51b4ac81f513cea4f235345d7eb4fb50
[ "MIT" ]
6,180
2015-01-02T19:10:09.000Z
2022-03-31T21:10:44.000Z
Mage/src/main/java/mage/game/command/emblems/LilianaOfTheDarkRealmsEmblem.java
arcox/mage
2cc88718e8d0aadb32897227d8d94bd938aebdc5
[ "MIT" ]
1,001
2015-01-01T01:15:20.000Z
2022-03-30T20:23:04.000Z
package mage.game.command.emblems; import mage.Mana; import mage.abilities.Ability; import mage.abilities.common.SimpleStaticAbility; import mage.abilities.costs.common.TapSourceCost; import mage.abilities.effects.common.continuous.GainAbilityControlledEffect; import mage.abilities.mana.SimpleManaAbility; import mage.constants.Duration; import mage.constants.SubType; import mage.constants.Zone; import mage.filter.common.FilterLandPermanent; import mage.game.command.Emblem; /** * * @author spjspj */ public final class LilianaOfTheDarkRealmsEmblem extends Emblem { private static final FilterLandPermanent filter = new FilterLandPermanent("Swamps"); static { filter.add(SubType.SWAMP.getPredicate()); } public LilianaOfTheDarkRealmsEmblem() { this.setName("Emblem Liliana"); SimpleManaAbility manaAbility = new SimpleManaAbility(Zone.BATTLEFIELD, Mana.BlackMana(4), new TapSourceCost()); Ability ability = new SimpleStaticAbility(Zone.COMMAND, new GainAbilityControlledEffect(manaAbility, Duration.WhileOnBattlefield, filter)); this.getAbilities().add(ability); } }
32.542857
147
0.776997
5943b2db7829020466ae02b646592e373f18dc08
29,377
cpp
C++
LongUI/RichED/ed_undoredo.cpp
hempflower/RedstoneLauncher
7a00c61d8f197c2a9f8d8309e86baa5bf9cb4b70
[ "MIT" ]
174
2015-05-30T08:02:19.000Z
2022-03-12T12:23:46.000Z
LongUI/RichED/ed_undoredo.cpp
hempflower/RedstoneLauncher
7a00c61d8f197c2a9f8d8309e86baa5bf9cb4b70
[ "MIT" ]
6
2017-09-16T07:30:57.000Z
2021-07-25T01:39:35.000Z
LongUI/RichED/ed_undoredo.cpp
hempflower/RedstoneLauncher
7a00c61d8f197c2a9f8d8309e86baa5bf9cb4b70
[ "MIT" ]
44
2016-03-14T03:19:51.000Z
2022-02-21T01:10:58.000Z
#include "ed_txtdoc.h" #include "ed_txtplat.h" #include "ed_undoredo.h" #include <cstring> #include <cstdlib> #include <type_traits> #include <algorithm> enum : uint32_t { RED_ENDIAN_CODE = 0x00010203, RED_REV1_CODE = 0x00000000, RED_REV2_CODE = 0xffffffff, }; /// <summary> /// Reds the magic code. /// </summary> /// <returns></returns> static inline uint32_t red_magic_code() noexcept { union { uint32_t code; uint8_t u8[4]; } data; data.u8[0] = 0x64; data.u8[1] = 0x75; data.u8[2] = 0x73; data.u8[3] = 0x74; return data.code; } namespace RichED { /// <summary> /// Undoes the redo idle. /// </summary> /// <param name="doc">The document.</param> /// <param name="op">The op.</param> /// <returns></returns> void UndoRedoIdle(CEDTextDocument& doc, TrivialUndoRedo& op) noexcept { } // init callback void InitCallback(TrivialUndoRedo& op) noexcept; // private impl struct CEDTextDocument::UndoPri { // set caret data static void AnchorCaret(CEDTextDocument& doc, TrivialUndoRedo& op) noexcept; // set riched static bool SetRichED(CEDTextDocument&, DocPoint, DocPoint, uint32_t, uint32_t, const void*, bool) noexcept; // set flags static bool SetFlagS(CEDTextDocument&, DocPoint, DocPoint, uint16_t, uint32_t) noexcept; }; } /// <summary> /// Sets the rich ed. /// </summary> /// <param name="a">a.</param> /// <param name="b">The b.</param> /// <param name="c">The c.</param> /// <param name="d">The d.</param> /// <param name="e">The e.</param> /// <param name="f">The f.</param> /// <param name="g">if set to <c>true</c> [g].</param> /// <returns></returns> bool RichED::CEDTextDocument::UndoPri::SetRichED( CEDTextDocument&a, DocPoint b, DocPoint c, uint32_t d, uint32_t e, const void * f, bool g) noexcept { return a.set_riched(b, c, d, e, f, g); } /// <summary> /// Sets the flag s. /// </summary> /// <param name="a">a.</param> /// <param name="b">The b.</param> /// <param name="c">The c.</param> /// <param name="d">The d.</param> /// <param name="e">The e.</param> /// <returns></returns> bool RichED::CEDTextDocument::UndoPri::SetFlagS( CEDTextDocument & a, DocPoint b, DocPoint c, uint16_t d, uint32_t e) noexcept { return a.set_flags(b, c, d, e); } /// <summary> /// Initializes a new instance of the <see cref="CEDUndoRedo"/> class. /// </summary> /// <param name="max_deep">The maximum deep.</param> RichED::CEDUndoRedo::CEDUndoRedo(uint32_t max_deep) noexcept : max_deep(max_deep) { // 处理Cell节点 m_head.prev = nullptr; m_head.next = &m_tail; m_tail.prev = &m_head; m_tail.next = nullptr; #ifndef NDEBUG std::memset(m_dbgBuffer, 233, sizeof(m_dbgBuffer)); #endif static_assert(std::is_trivial<TrivialUndoRedo>::value == true, "Trivial!"); } /// <summary> /// Clears this instance. /// </summary> /// <returns></returns> void RichED::CEDUndoRedo::Clear() noexcept { auto node = m_head.next; while (node != &m_tail) { const auto ptr = node; node = node->next; RichED::Free(ptr); } m_head.next = m_pStackTop = &m_tail; m_tail.prev = &m_head; m_cCurrent = 0; } /// <summary> /// Undoes the specified document. /// </summary> /// <param name="doc">The document.</param> /// <returns></returns> bool RichED::CEDUndoRedo::Undo(CEDTextDocument& doc) noexcept { auto node = m_pStackTop; // 撤销栈为空 if (node == &m_tail) return false; TrivialUndoRedo* last = nullptr; while (true) { const auto op = static_cast<TrivialUndoRedo*>(node); last = op; op->undo(doc, *op); if (!op->decorator) break; node = node->next; } doc.SetAnchorCaret(last->anchor, last->caret); m_pStackTop = node->next; return true; } /// <summary> /// Redoes the specified document. /// </summary> /// <param name="doc">The document.</param> /// <returns></returns> bool RichED::CEDUndoRedo::Redo(CEDTextDocument & doc) noexcept { auto node = m_pStackTop; const auto first = m_head.next; // 撤销栈已满 if (node == first) return false; TrivialUndoRedo* last = nullptr; while (true) { node = node->prev; const auto op = static_cast<TrivialUndoRedo*>(node); last = op; op->redo(doc, *op); // 到头了 if (op == first) break; // 或者下(其实是上) 一个是非装饰操作 if (!static_cast<TrivialUndoRedo*>(node->prev)->decorator) break; } doc.SetAnchorCaret(last->anchor, last->caret); m_pStackTop = node; return true; } /// <summary> /// Anchors the caret. /// </summary> /// <param name="doc">The document.</param> /// <param name="op">The op.</param> /// <returns></returns> void RichED::CEDTextDocument::UndoPri::AnchorCaret( CEDTextDocument & doc, TrivialUndoRedo & op) noexcept { op.anchor = doc.m_dpAnchor; op.caret = doc.m_dpCaret; } /// <summary> /// Adds the op. /// </summary> /// <param name="doc">The document.</param> /// <param name="op">The op.</param> /// <returns></returns> void RichED::CEDUndoRedo::AddOp(CEDTextDocument& doc, TrivialUndoRedo& op) noexcept { CEDTextDocument::UndoPri::AnchorCaret(doc, op); // 释放HEAD -> TOP while (m_head.next != m_pStackTop) { const auto ptr = m_head.next; //const auto obj = static_cast<TrivialUndoRedo*>(ptr); m_head.next = m_head.next->next; RichED::Free(ptr); } RichED::InitCallback(op); RichED::InsertAfterFirst(m_head, op); m_pStackTop = m_head.next; } // ---------------------------------------------------------------------------- // Object // ---------------------------------------------------------------------------- namespace RichED { // singe op for ruby struct RED_RICHED_ALIGNED ObjectSingeOp { // point DocPoint begin; // ruby text length uint32_t ruby_length; // type of this CellType cell_type; // length of extra data uint16_t extra_length; // next op auto Next() noexcept { const size_t exlen = extra_length; const size_t alignc = alignof(ObjectSingeOp); const size_t mask = ~(alignc - 1); const size_t aligned_exlen = (exlen + (alignc - 1)) & mask; const auto ptr = reinterpret_cast<char*>(this + 1) + aligned_exlen; return reinterpret_cast<ObjectSingeOp*>(ptr); } }; // Rollback objs void RemoveObjs(CEDTextDocument& doc, TrivialUndoRedo& op) noexcept { auto obj = reinterpret_cast<ObjectSingeOp*>(&op + 1); const auto end_ptr = reinterpret_cast<char*>(&op.bytes_from_here) + op.bytes_from_here; const auto end_itr = reinterpret_cast<ObjectSingeOp*>(end_ptr); while (obj < end_itr) { assert(obj->Next() <= end_itr); auto end_dp = obj->begin; end_dp.pos++; doc.RemoveText(obj->begin, end_dp); obj = obj->Next(); } } // execute objs void ExecuteObjs(CEDTextDocument& doc, TrivialUndoRedo& op) noexcept { auto obj = reinterpret_cast<ObjectSingeOp*>(&op + 1); const auto end_ptr = reinterpret_cast<char*>(&op.bytes_from_here) + op.bytes_from_here; const auto end_itr = reinterpret_cast<ObjectSingeOp*>(end_ptr); while (obj < end_itr) { assert(obj->Next() <= end_itr); assert(!!obj->ruby_length != !!obj->extra_length || (!obj->ruby_length && !obj->extra_length)); // 注音符号: 将范围字符转换为被注音, 然后后面指定长度为注音 if (obj->ruby_length) { // 升阶魔法! RUM! doc.RankUpMagic(obj->begin, obj->ruby_length); } // 其他内联对象: 利用EXTRA-INFO创建内联对象 else if (obj->extra_length) { // 升阶魔法! RUM! const auto info = reinterpret_cast<InlineInfo*>(obj + 1); doc.RankUpMagic(obj->begin, *info, obj->extra_length, obj->cell_type); } obj = obj->Next(); } } /// <summary> /// 插入 /// </summary> /// <param name="doc">The document.</param> /// <param name="op">The op.</param> /// <returns></returns> void InsertObjs(CEDTextDocument& doc, TrivialUndoRedo& op) noexcept { // 只有一个 auto obj = reinterpret_cast<ObjectSingeOp*>(&op + 1); const auto end_ptr = reinterpret_cast<char*>(&op.bytes_from_here) + op.bytes_from_here; const auto end_itr = reinterpret_cast<ObjectSingeOp*>(end_ptr); assert(obj->Next() == end_itr); const auto info = reinterpret_cast<InlineInfo*>(obj + 1); doc.InsertInline(obj->begin, *info, obj->extra_length, obj->cell_type); } } // ---------------------------------------------------------------------------- // RichED Ruby // ---------------------------------------------------------------------------- namespace RichED { // singe op for rich struct RubySingeOp { // under riched RichData riched; // begin point DocPoint begin; // ruby length uint32_t ruby_length; // under length uint32_t under_length; // char char32_t ch; // ruby char16_t ruby[2]; }; // Rollback ruby void RemoveRuby(CEDTextDocument& doc, TrivialUndoRedo& op) noexcept { const auto obj = reinterpret_cast<RubySingeOp*>(&op + 1); DocPoint end_dp = obj->begin; end_dp.pos += obj->ruby_length + obj->under_length; doc.RemoveText(obj->begin, end_dp); } // exec ruby void ExecuteRuby(CEDTextDocument& doc, TrivialUndoRedo& op) noexcept { const auto obj = reinterpret_cast<RubySingeOp*>(&op + 1); U16View ruby; ruby.first = obj->ruby; ruby.second = ruby.first + obj->ruby_length; assert(ruby.second > ruby.first); doc.InsertRuby(obj->begin, obj->ch, ruby, &obj->riched); } } // ---------------------------------------------------------------------------- // RichED Rich // ---------------------------------------------------------------------------- namespace RichED { // group op for rich struct RichGroupOp { // op for rollback RichSingeOp back; // back offset uint16_t back_offset; // back length uint16_t back_length; // relayout bool relayout; // unused bool unused[3]; // ops for execute RichSingeOp exec[1]; }; // Rollback rich void RollbackRich(CEDTextDocument& doc, TrivialUndoRedo& op) noexcept { const auto data = reinterpret_cast<RichGroupOp*>(&op + 1); const auto ptr = reinterpret_cast<char*>(&data->back.riched) + data->back_offset; if (data->back_length) { CEDTextDocument::UndoPri::SetRichED( doc, data->back.begin, data->back.end, data->back_offset, data->back_length, ptr, data->relayout ); } // 长度为0则是设置FLAG else { const uint16_t flags = static_cast<uint16_t>(data->back.riched.fflags); CEDTextDocument::UndoPri::SetFlagS( doc, data->back.begin, data->back.end, flags, data->back_offset ); } } // execute rich void ExecuteRich(CEDTextDocument& doc, TrivialUndoRedo& op) noexcept { const auto data = reinterpret_cast<RichGroupOp*>(&op + 1); const auto end_ptr = reinterpret_cast<char*>(&op.bytes_from_here) + op.bytes_from_here; const auto end_itr = reinterpret_cast<RichSingeOp*>(end_ptr); const auto relayout = data->relayout; std::for_each(data->exec, end_itr, [&doc, relayout](const RichSingeOp& op)noexcept { CEDTextDocument::UndoPri::SetRichED( doc, op.begin, op.end, 0, sizeof(op.riched), &op.riched, relayout ); }); } } // ---------------------------------------------------------------------------- // RichED Text // ---------------------------------------------------------------------------- namespace RichED { // group op for text struct TextGroupOp { // begin point DocPoint begin; // end point DocPoint end; // text length uint32_t length; // text data char16_t text[2]; }; // Rollback text void RollbackText(CEDTextDocument& doc, TrivialUndoRedo& op) noexcept { const auto data = reinterpret_cast<TextGroupOp*>(&op + 1); doc.RemoveText(data->begin, data->end); } // execute text void ExecuteText(CEDTextDocument& doc, TrivialUndoRedo& op) noexcept { const auto data = reinterpret_cast<TextGroupOp*>(&op + 1); doc.InsertText(data->begin, { data->text, data->text + data->length }, true); } } // ---------------------------------------------------------------------------- // RichED Overview // ---------------------------------------------------------------------------- namespace RichED { // undo op enum UndoRedoOp : uint16_t { // remove: text Op_RemoveText = 0, // remove: rich Op_RemoveRich, // remove: objs Op_RemoveObjs, // insert: text Op_InsertText, // insert: objs Op_InsertObjs, // insert: ruby Op_InsertRuby, // setas: rich Op_SetAsRich, }; namespace impl { /// <summary> /// Riches the length of the undoredo. /// </summary> /// <param name="count">The count.</param> /// <returns></returns> auto rich_undoredo_len(uint32_t count) noexcept ->size_t { assert(count); const size_t len = sizeof(TrivialUndoRedo) + (sizeof(RichGroupOp) - sizeof(RichSingeOp)) + sizeof(RichSingeOp) * count ; return len; } /// <summary> /// Riches the undoredo mk. /// </summary> /// <param name="ptr">The PTR.</param> /// <param name="len">The length.</param> /// <returns></returns> void rich_undoredo_mk(void* ptr, uint32_t count) noexcept { assert(ptr); const auto len = impl::rich_undoredo_len(count); const auto op = reinterpret_cast<TrivialUndoRedo*>(ptr); const size_t offset = offsetof(TrivialUndoRedo, bytes_from_here); op->bytes_from_here = static_cast<uint32_t>(len - offset); } /// <summary> /// Riches as remove. /// </summary> /// <param name="ptr">The PTR.</param> /// <param name="id">The identifier.</param> /// <returns></returns> void rich_as_remove(void* ptr, uint16_t id) noexcept { assert(ptr && id); const auto op = reinterpret_cast<TrivialUndoRedo*>(ptr); const auto ops = reinterpret_cast<RichGroupOp*>(op + 1); op->type = Op_RemoveRich; op->decorator = id - 1; ops->relayout = true; } /// <summary> /// Riches the initialize. /// </summary> /// <param name="ptr">The PTR.</param> /// <param name="relayout">if set to <c>true</c> [relayout].</param> /// <returns></returns> void rich_init(void* ptr, bool relayout, uint16_t o, uint16_t l, const RichSingeOp& a) noexcept { assert(ptr); const auto op = reinterpret_cast<TrivialUndoRedo*>(ptr); op->type = Op_SetAsRich; const auto ops = reinterpret_cast<RichGroupOp*>(op + 1); ops->relayout = relayout; ops->back = a; ops->back_offset = o; ops->back_length = l; } /// <summary> /// Riches the set. /// </summary> /// <param name="ptr">The PTR.</param> /// <param name="index">The index.</param> /// <param name="data">The data.</param> /// <returns></returns> void rich_set(void* ptr, uint32_t index, const RichData & data, DocPoint a, DocPoint b) noexcept { assert(ptr); assert(a.line != b.line || a.pos != b.pos); const auto op = reinterpret_cast<TrivialUndoRedo*>(ptr); const auto ops = reinterpret_cast<RichGroupOp*>(op + 1); ops->exec[index].riched = data; ops->exec[index].begin = a; ops->exec[index].end = b; } } namespace impl { /// <summary> /// Riches the undoredo. /// </summary> /// <param name="count">The count.</param> /// <returns></returns> auto text_undoredo_len(uint32_t count) noexcept -> size_t { assert(count); const size_t len = sizeof(TrivialUndoRedo) + sizeof(TextGroupOp) + sizeof(char16_t) * count ; return len; } /// <summary> /// Texts the undoredo mk. /// </summary> /// <param name="ptr">The PTR.</param> /// <param name="len">The length.</param> /// <returns></returns> void text_undoredo_mk(void* ptr, uint32_t count) noexcept { assert(ptr); const auto len = impl::text_undoredo_len(count); const auto op = reinterpret_cast<TrivialUndoRedo*>(ptr); const size_t offset = offsetof(TrivialUndoRedo, bytes_from_here); op->bytes_from_here = static_cast<uint32_t>(len - offset); const auto ops = reinterpret_cast<TextGroupOp*>(op + 1); ops->length = count; } /// <summary> /// Texts as remove. /// </summary> /// <param name="ptr">The PTR.</param> /// <param name="id">The identifier.</param> /// <param name="a">a.</param> /// <param name="b">The b.</param> /// <returns></returns> void text_as_remove(void* ptr, uint16_t id, DocPoint a, DocPoint b) noexcept { assert(ptr && id); const auto op = reinterpret_cast<TrivialUndoRedo*>(ptr); op->type = Op_RemoveText; op->decorator = id - 1; const auto ops = reinterpret_cast<TextGroupOp*>(op + 1); ops->begin = a; ops->end = b; } /// <summary> /// Texts as insert. /// </summary> /// <param name="ptr">The PTR.</param> /// <param name="id">The identifier.</param> /// <param name="a">a.</param> /// <param name="b">The b.</param> /// <returns></returns> void text_as_insert(void* ptr, uint16_t id, DocPoint a, DocPoint b) noexcept { assert(ptr && id); const auto op = reinterpret_cast<TrivialUndoRedo*>(ptr); op->type = Op_InsertText; op->decorator = id - 1; const auto ops = reinterpret_cast<TextGroupOp*>(op + 1); ops->begin = a; ops->end = b; } /// <summary> /// Texts the append. /// </summary> /// <param name="ptr">The PTR.</param> /// <param name="i">The i.</param> /// <param name="view">The view.</param> /// <returns></returns> void text_append(void* ptr, uint32_t i, U16View view) noexcept { assert(ptr); const auto op = reinterpret_cast<TrivialUndoRedo*>(ptr); const auto ops = reinterpret_cast<TextGroupOp*>(op + 1); const auto len = view.second - view.first; std::memcpy(ops->text + i, view.first, len * sizeof(char16_t)); #ifndef NDEBUG // 调试时添加NUL字符方便调试 ops->text[i + len] = 0; #endif } /// <summary> /// Texts the append. /// </summary> /// <param name="ptr">The PTR.</param> /// <param name="i">The i.</param> /// <param name="ch">The ch.</param> /// <returns></returns> void text_append(void* ptr, uint32_t i, char16_t ch) noexcept { assert(ptr); const auto op = reinterpret_cast<TrivialUndoRedo*>(ptr); const auto ops = reinterpret_cast<TextGroupOp*>(op + 1); ops->text[i] = ch; #ifndef NDEBUG // 调试时添加NUL字符方便调试 ops->text[i + 1] = 0; #endif } } // impl namespace impl { /// <summary> /// Rubies the length of the undoredo. /// </summary> /// <param name="length">The length.</param> /// <returns></returns> auto ruby_undoredo_len(uint32_t length) noexcept -> size_t { assert(length); const size_t len = sizeof(TrivialUndoRedo) + sizeof(RubySingeOp) + sizeof(char16_t) * length ; return len; } /// <summary> /// Rubies the undoredo mk. /// </summary> /// <param name="ptr">The PTR.</param> /// <param name="length">The length.</param> /// <returns></returns> void ruby_undoredo_mk(void* ptr, uint32_t length) noexcept { assert(ptr); const auto len = impl::ruby_undoredo_len(length); const auto op = reinterpret_cast<TrivialUndoRedo*>(ptr); const size_t offset = offsetof(TrivialUndoRedo, bytes_from_here); op->bytes_from_here = static_cast<uint32_t>(len - offset); } /// <summary> /// Rubies as insert. /// </summary> /// <param name="ptr">The PTR.</param> /// <param name="id">The identifier.</param> /// <returns></returns> void ruby_as_insert(void* ptr, uint16_t id) noexcept { assert(ptr && id); const auto op = reinterpret_cast<TrivialUndoRedo*>(ptr); op->type = Op_InsertRuby; op->decorator = id - 1; } /// <summary> /// Rubies the set data. /// </summary> /// <param name="ptr">The PTR.</param> /// <param name="dp">The dp.</param> /// <param name="ch">The ch.</param> /// <param name="view">The view.</param> /// <param name="data">The data.</param> /// <returns></returns> void ruby_set_data(void* ptr, DocPoint dp, char32_t ch, U16View view, const RichData& data) noexcept { const auto op = reinterpret_cast<TrivialUndoRedo*>(ptr); const auto obj = reinterpret_cast<RubySingeOp*>(op + 1); obj->riched = data; obj->begin = dp; obj->ruby_length = static_cast<uint32_t>(view.second - view.first); obj->under_length = ch > 0xffff ? 2 : 1; obj->ch = ch; const size_t bl = sizeof(view.first[0]) * (view.second - view.first); std::memcpy(obj->ruby, view.first, bl); #ifndef NDEBUG // 调试时添加NUL字符方便调试 obj->ruby[obj->ruby_length] = 0; #endif } } namespace impl { /// <summary> /// Objses the undoredo. /// </summary> /// <param name="count">The count.</param> /// <param name="length">The length.</param> /// <returns></returns> auto objs_undoredo_len(uint32_t count, uint32_t length) noexcept ->size_t { assert(count); assert((length & (alignof(TrivialUndoRedo) - 1)) == 0); const size_t len = sizeof(TrivialUndoRedo) + sizeof(ObjectSingeOp) * count + length ; return len; } /// <summary> /// Objses the undoredo. /// </summary> /// <param name="count">The count.</param> /// <param name="length">The length.</param> /// <returns></returns> void objs_undoredo_mk(void* ptr, uint32_t count, uint32_t length) noexcept { const auto len = impl::objs_undoredo_len(count, length); const auto op = reinterpret_cast<TrivialUndoRedo*>(ptr); const size_t offset = offsetof(TrivialUndoRedo, bytes_from_here); op->bytes_from_here = static_cast<uint32_t>(len - offset); } /// <summary> /// Objses as remove. /// </summary> /// <param name="ptr">The PTR.</param> /// <param name="id">The identifier.</param> /// <returns></returns> void*objs_as_remove(void* ptr, uint16_t id) noexcept { assert(ptr && id); const auto op = reinterpret_cast<TrivialUndoRedo*>(ptr); op->type = Op_RemoveObjs; op->decorator = id - 1; return op + 1; } /// <summary> /// Objses as remove. /// </summary> /// <param name="ptr">The PTR.</param> /// <param name="id">The identifier.</param> /// <returns></returns> void*objs_as_insert(void* ptr, uint16_t id) noexcept { assert(ptr && id); const auto op = reinterpret_cast<TrivialUndoRedo*>(ptr); op->type = Op_InsertObjs; op->decorator = id - 1; return op + 1; } /// <summary> /// Objses as remove. /// </summary> /// <param name="ptr">The PTR.</param> /// <param name="id">The identifier.</param> /// <returns></returns> void*objs_as_goon(void* ptr, DocPoint dp, uint32_t ruby, CellType type, uint16_t exlen, void* data) noexcept { assert(ptr); const auto op = reinterpret_cast<ObjectSingeOp*>(ptr); op->begin = dp; op->ruby_length = ruby; op->extra_length = exlen; op->cell_type = type; std::memcpy(op + 1, data, exlen); return op->Next(); } } /// <summary> /// Initializes the callback. /// </summary> /// <param name="op">The op.</param> /// <returns></returns> void InitCallback(TrivialUndoRedo& op) noexcept { switch (op.type) { default: assert(!"UNKNOWN!"); op.undo = RichED::UndoRedoIdle; op.redo = RichED::UndoRedoIdle; break; case Op_RemoveText: // 移除文本 // - 撤销: 文本添加 // - 重做: 文本移除 op.undo = RichED::ExecuteText; op.redo = RichED::RollbackText; break; case Op_RemoveRich: // 移除富属性 // - 撤销: 富属性的修改 // - 重做: 富属性的无视 op.undo = RichED::ExecuteRich; op.redo = RichED::UndoRedoIdle; break; case Op_RemoveObjs: // 移除内联对象 // - 撤销: 内联对象的再生 // - 重做: 内联对象的无视 op.undo = RichED::ExecuteObjs; op.redo = RichED::UndoRedoIdle; break; case Op_InsertText: // 插入文本 // - 撤销: 文本移除 // - 重做: 文本添加 op.undo = RichED::RollbackText; op.redo = RichED::ExecuteText; break; case Op_InsertObjs: // 插入对象 // - 撤销: 删除 // - 重做: 插入 op.undo = RichED::RemoveObjs; op.redo = RichED::InsertObjs; break; case Op_InsertRuby: // 插入注音 // - 撤销: 删除注音 // - 重做: 插入注音 op.undo = RichED::RemoveRuby; op.redo = RichED::ExecuteRuby; break; case Op_SetAsRich: // 修改富属性 // - 撤销: 执行富属性 // - 重做: 修改富属性 op.undo = RichED::ExecuteRich; op.redo = RichED::RollbackRich; break; } } } // ---------------------------------------------------------------------------- // RichED Save/Load // ---------------------------------------------------------------------------- /// <summary> /// Saves the bin file. /// </summary> /// <param name="ctx">The CTX.</param> /// <returns></returns> bool RichED::CEDTextDocument::SaveBinFile(CtxPtr ctx) noexcept { uint32_t magic_codes[4]; magic_codes[0] = red_magic_code(); magic_codes[1] = RED_ENDIAN_CODE; magic_codes[2] = RED_REV1_CODE; magic_codes[3] = RED_REV2_CODE; auto& plat = this->platform; const auto write_file = [&plat, ctx](const void* ptr, uint32_t len) noexcept { return plat.WriteToFile(ctx, static_cast<const uint8_t*>(ptr), len); }; // 先驱码 if (write_file(magic_codes, sizeof(magic_codes))) { } return false; } /// <summary> /// Loads the bin file. /// </summary> /// <param name="ctx">The CTX.</param> /// <returns></returns> bool RichED::CEDTextDocument::LoadBinFile(CtxPtr ctx) noexcept { uint32_t magic_codes[4]; auto& plat = this->platform; const auto read_file = [&plat, ctx](void* ptr, uint32_t len) noexcept { return plat.ReadFromFile(ctx, static_cast<uint8_t*>(ptr), len); }; if (!read_file(magic_codes, sizeof(magic_codes))) return false; if (magic_codes[0] != red_magic_code()) return false; assert(magic_codes[1] == RED_ENDIAN_CODE && "NOT IMPL"); return false; }
35.014303
118
0.529666
53d7652f3fda6892f8d6400df3d6bf4da800fc4c
2,505
java
Java
org/apache/poi/ss/formula/eval/IntersectionEval.java
AlhonGelios/AO
3e78fefe875ab102016e1259874886970e3c5c2a
[ "Apache-2.0" ]
null
null
null
org/apache/poi/ss/formula/eval/IntersectionEval.java
AlhonGelios/AO
3e78fefe875ab102016e1259874886970e3c5c2a
[ "Apache-2.0" ]
null
null
null
org/apache/poi/ss/formula/eval/IntersectionEval.java
AlhonGelios/AO
3e78fefe875ab102016e1259874886970e3c5c2a
[ "Apache-2.0" ]
null
null
null
package org.apache.poi.ss.formula.eval; import org.apache.poi.ss.formula.eval.AreaEval; import org.apache.poi.ss.formula.eval.ErrorEval; import org.apache.poi.ss.formula.eval.EvaluationException; import org.apache.poi.ss.formula.eval.RefEval; import org.apache.poi.ss.formula.eval.ValueEval; import org.apache.poi.ss.formula.functions.Fixed2ArgFunction; import org.apache.poi.ss.formula.functions.Function; public final class IntersectionEval extends Fixed2ArgFunction { public static final Function instance = new IntersectionEval(); public ValueEval evaluate(int srcRowIndex, int srcColumnIndex, ValueEval arg0, ValueEval arg1) { try { AreaEval e = evaluateRef(arg0); AreaEval reB = evaluateRef(arg1); AreaEval result = resolveRange(e, reB); return (ValueEval)(result == null?ErrorEval.NULL_INTERSECTION:result); } catch (EvaluationException var8) { return var8.getErrorEval(); } } private static AreaEval resolveRange(AreaEval aeA, AreaEval aeB) { int aeAfr = aeA.getFirstRow(); int aeAfc = aeA.getFirstColumn(); int aeBlc = aeB.getLastColumn(); if(aeAfc > aeBlc) { return null; } else { int aeBfc = aeB.getFirstColumn(); if(aeBfc > aeA.getLastColumn()) { return null; } else { int aeBlr = aeB.getLastRow(); if(aeAfr > aeBlr) { return null; } else { int aeBfr = aeB.getFirstRow(); int aeAlr = aeA.getLastRow(); if(aeBfr > aeAlr) { return null; } else { int top = Math.max(aeAfr, aeBfr); int bottom = Math.min(aeAlr, aeBlr); int left = Math.max(aeAfc, aeBfc); int right = Math.min(aeA.getLastColumn(), aeBlc); return aeA.offset(top - aeAfr, bottom - aeAfr, left - aeAfc, right - aeAfc); } } } } } private static AreaEval evaluateRef(ValueEval arg) throws EvaluationException { if(arg instanceof AreaEval) { return (AreaEval)arg; } else if(arg instanceof RefEval) { return ((RefEval)arg).offset(0, 0, 0, 0); } else if(arg instanceof ErrorEval) { throw new EvaluationException((ErrorEval)arg); } else { throw new IllegalArgumentException("Unexpected ref arg class (" + arg.getClass().getName() + ")"); } } }
35.28169
107
0.602395
5b04d039ff4f346818697dae804aa060ea87bf9f
28,888
c
C
os/sa1100/ether589.c
kryptine/inferno-3
a0249d7e6e3176eff94b4fab5a68bbab3aa479de
[ "MIT" ]
4
2021-03-24T20:50:09.000Z
2021-03-26T20:24:57.000Z
os/sa1100/ether589.c
kryptine/inferno-3
a0249d7e6e3176eff94b4fab5a68bbab3aa479de
[ "MIT" ]
null
null
null
os/sa1100/ether589.c
kryptine/inferno-3
a0249d7e6e3176eff94b4fab5a68bbab3aa479de
[ "MIT" ]
1
2021-08-08T07:20:04.000Z
2021-08-08T07:20:04.000Z
#include "u.h" #include "../port/lib.h" #include "mem.h" #include "dat.h" #include "fns.h" #include "io.h" #include "../port/error.h" #include "../port/netif.h" #include "etherif.h" #define DPRINT if(0) print #define XCVRDEBUG if(0) print #define IRQDEBUG if(0) print //#define DEBUG 1 enum { /* all windows */ CommandR = 0x000E, IntStatusR = 0x000E, }; enum { /* Commands */ GlobalReset = 0x0000, SelectRegisterWindow = 0x0001, EnableDcConverter = 0x0002, RxDisable = 0x0003, RxEnable = 0x0004, RxReset = 0x0005, Stall = 0x0006, /* 3C90x */ TxDone = 0x0007, RxDiscard = 0x0008, TxEnable = 0x0009, TxDisable = 0x000A, TxReset = 0x000B, RequestInterrupt = 0x000C, AcknowledgeInterrupt = 0x000D, SetInterruptEnable = 0x000E, SetIndicationEnable = 0x000F, /* SetReadZeroMask */ SetRxFilter = 0x0010, SetRxEarlyThresh = 0x0011, SetTxAvailableThresh = 0x0012, SetTxStartThresh = 0x0013, StatisticsEnable = 0x0015, StatisticsDisable = 0x0016, DisableDcConverter = 0x0017, SetTxReclaimThresh = 0x0018, /* PIO-only adapters */ PowerUp = 0x001B, /* not all adapters */ PowerDownFull = 0x001C, /* not all adapters */ PowerAuto = 0x001D, /* not all adapters */ }; enum { /* (Global|Rx|Tx)Reset command bits */ tpAuiReset = 0x0001, /* 10BaseT and AUI transceivers */ endecReset = 0x0002, /* internal Ethernet encoder/decoder */ networkReset = 0x0004, /* network interface logic */ fifoReset = 0x0008, /* FIFO control logic */ aismReset = 0x0010, /* autoinitialise state-machine logic */ hostReset = 0x0020, /* bus interface logic */ dmaReset = 0x0040, /* bus master logic */ vcoReset = 0x0080, /* on-board 10Mbps VCO */ updnReset = 0x0100, /* upload/download (Rx/TX) logic */ resetMask = 0x01FF, }; enum { /* SetRxFilter command bits */ receiveIndividual = 0x0001, /* match station address */ receiveMulticast = 0x0002, receiveBroadcast = 0x0004, receiveAllFrames = 0x0008, /* promiscuous */ }; enum { /* IntStatus bits */ interruptLatch = 0x0001, hostError = 0x0002, /* Adapter Failure */ txComplete = 0x0004, txAvailable = 0x0008, rxComplete = 0x0010, rxEarly = 0x0020, intRequested = 0x0040, updateStats = 0x0080, commandInProgress = 0x1000, interruptMask = 0x00FE, }; #define COMMAND(port, cmd, a) outs((port)+CommandR, ((cmd)<<11)|(a)) #define STATUS(port) ins((port)+IntStatusR) enum { /* Window 0 - setup */ Wsetup = 0x0000, /* registers */ ManufacturerID = 0x0000, /* 3C5[08]*, 3C59[27] */ ProductID = 0x0002, /* 3C5[08]*, 3C59[27] */ ConfigControl = 0x0004, /* 3C5[08]*, 3C59[27] */ AddressConfig = 0x0006, /* 3C5[08]*, 3C59[27] */ ResourceConfig = 0x0008, /* 3C5[08]*, 3C59[27] */ EepromCommand = 0x000A, EepromData = 0x000C, /* AddressConfig Bits */ autoSelect9 = 0x0080, xcvrMask9 = 0xC000, /* ConfigControl bits */ Ena = 0x0001, base10TAvailable9 = 0x0200, coaxAvailable9 = 0x1000, auiAvailable9 = 0x2000, /* EepromCommand bits */ EepromReadRegister = 0x0080, EepromBusy = 0x8000, }; #define EEPROMCMD(port, cmd, a) outs((port)+EepromCommand, (cmd)|(a)) #define EEPROMBUSY(port) (ins((port)+EepromCommand) & EepromBusy) #define EEPROMDATA(port) ins((port)+EepromData) enum { /* Window 1 - operating set */ Wop = 0x0001, /* registers */ Fifo = 0x0000, RxError = 0x0004, /* 3C59[0257] only */ RxStatus = 0x0008, Timer = 0x000A, TxStatus = 0x000B, TxFree = 0x000C, /* RxError bits */ rxOverrun = 0x0001, runtFrame = 0x0002, alignmentError = 0x0004, /* Framing */ crcError = 0x0008, oversizedFrame = 0x0010, dribbleBits = 0x0080, /* RxStatus bits */ rxBytes = 0x1FFF, /* 3C59[0257] mask */ rxBytes9 = 0x07FF, /* 3C5[078]9 mask */ rxError9 = 0x3800, /* 3C5[078]9 error mask */ rxOverrun9 = 0x0000, oversizedFrame9 = 0x0800, dribbleBits9 = 0x1000, runtFrame9 = 0x1800, alignmentError9 = 0x2000, /* Framing */ crcError9 = 0x2800, rxError = 0x4000, rxIncomplete = 0x8000, /* TxStatus Bits */ txStatusOverflow = 0x0004, maxCollisions = 0x0008, txUnderrun = 0x0010, txJabber = 0x0020, interruptRequested = 0x0040, txStatusComplete = 0x0080, }; enum { /* Window 2 - station address */ Wstation = 0x0002, }; enum { /* Window 3 - FIFO management */ Wfifo = 0x0003, /* registers */ InternalConfig = 0x0000, /* 3C509B, 3C589, 3C59[0257] */ OtherInt = 0x0004, /* 3C59[0257] */ RomControl = 0x0006, /* 3C509B, 3C59[27] */ MacControl = 0x0006, /* 3C59[0257] */ ResetOptions = 0x0008, /* 3C59[0257] */ RxFree = 0x000A, /* InternalConfig bits */ disableBadSsdDetect = 0x00000100, ramLocation = 0x00000200, /* 0 external, 1 internal */ ramPartition5to3 = 0x00000000, ramPartition3to1 = 0x00010000, ramPartition1to1 = 0x00020000, ramPartition3to5 = 0x00030000, ramPartitionMask = 0x00030000, xcvr10BaseT = 0x00000000, xcvrAui = 0x00100000, /* 10BASE5 */ xcvr10Base2 = 0x00300000, xcvr100BaseTX = 0x00400000, xcvr100BaseFX = 0x00500000, xcvrMii = 0x00600000, xcvrMask = 0x00700000, autoSelect = 0x01000000, /* MacControl bits */ deferExtendEnable = 0x0001, deferTimerSelect = 0x001E, /* mask */ fullDuplexEnable = 0x0020, allowLargePackets = 0x0040, extendAfterCollision = 0x0080, /* 3C90xB */ flowControlEnable = 0x0100, /* 3C90xB */ vltEnable = 0x0200, /* 3C90xB */ /* ResetOptions bits */ baseT4Available = 0x0001, baseTXAvailable = 0x0002, baseFXAvailable = 0x0004, base10TAvailable = 0x0008, coaxAvailable = 0x0010, auiAvailable = 0x0020, miiConnector = 0x0040, }; enum { /* Window 4 - diagnostic */ Wdiagnostic = 0x0004, /* registers */ VcoDiagnostic = 0x0002, FifoDiagnostic = 0x0004, NetworkDiagnostic = 0x0006, PhysicalMgmt = 0x0008, MediaStatus = 0x000A, BadSSD = 0x000C, UpperBytesOk = 0x000D, /* FifoDiagnostic bits */ txOverrun = 0x0400, rxUnderrun = 0x2000, receiving = 0x8000, /* PhysicalMgmt bits */ mgmtClk = 0x0001, mgmtData = 0x0002, mgmtDir = 0x0004, cat5LinkTestDefeat = 0x8000, /* MediaStatus bits */ dataRate100 = 0x0002, crcStripDisable = 0x0004, enableSqeStats = 0x0008, collisionDetect = 0x0010, carrierSense = 0x0020, jabberGuardEnable = 0x0040, linkBeatEnable = 0x0080, jabberDetect = 0x0200, polarityReversed = 0x0400, linkBeatDetect = 0x0800, txInProg = 0x1000, dcConverterEnabled = 0x4000, auiDisable = 0x8000, /* 10BaseT transceiver selected */ }; enum { /* Window 5 - internal state */ Wstate = 0x0005, /* registers */ TxStartThresh = 0x0000, TxAvailableThresh = 0x0002, RxEarlyThresh = 0x0006, RxFilter = 0x0008, InterruptEnable = 0x000A, IndicationEnable = 0x000C, }; enum { /* Window 6 - statistics */ Wstatistics = 0x0006, /* registers */ CarrierLost = 0x0000, SqeErrors = 0x0001, MultipleColls = 0x0002, SingleCollFrames = 0x0003, LateCollisions = 0x0004, RxOverruns = 0x0005, FramesXmittedOk = 0x0006, FramesRcvdOk = 0x0007, FramesDeferred = 0x0008, UpperFramesOk = 0x0009, BytesRcvdOk = 0x000A, BytesXmittedOk = 0x000C, }; enum { SelectWindow = 0x01, /* SelectWindow command */ EEPROMcmd = 0x0A, EEPROMdata = 0x0C, }; typedef struct { Lock wlock; /* window access */ int attached; Block* rbp; /* receive buffer */ Block* txbp; /* FIFO -based transmission */ int txthreshold; int txbusy; long interrupts; /* statistics */ long timer; long stats[BytesRcvdOk+3]; int xcvr; /* transceiver type */ int rxearly; /* RxEarlyThreshold */ int ts; /* threshold shift */ } Ctlr; static Block* rbpalloc(Block* (*f)(int)) { Block *bp; ulong addr; /* allocate on 32-byte boundary */ if(bp = f(ROUNDUP(sizeof(Etherpkt), 4) + 31)){ addr = (ulong)bp->base; addr = ROUNDUP(addr, 32); bp->rp = (uchar*)addr; } return bp; } static void promiscuous(void* arg, int on) { int filter, port; Ether *ether; ether = (Ether*)arg; port = ether->port; filter = receiveBroadcast|receiveIndividual; if(ether->nmaddr) filter |= receiveMulticast; if(on) filter |= receiveAllFrames; COMMAND(port, SetRxFilter, filter); } static void multicast(void* arg, uchar *addr, int on) { int filter, port; Ether *ether; USED(addr, on); ether = (Ether*)arg; port = ether->port; filter = receiveBroadcast|receiveIndividual; if(ether->nmaddr) filter |= receiveMulticast; if(ether->prom) filter |= receiveAllFrames; COMMAND(port, SetRxFilter, filter); } static void attach(Ether* ether) { int port, mask; Ctlr *ctlr; GpioReg *g; g = GPIOREG; ctlr = ether->ctlr; ilock(&ctlr->wlock); if(ctlr->attached){ iunlock(&ctlr->wlock); return; } /* * Set the receiver packet filter for this and broadcast addresses, * set the interrupt masks for all interrupts, enable the receiver * and transmitter. */ promiscuous(ether, ether->prom); port = ether->port; COMMAND(port, RxEnable, 0); COMMAND(port, TxEnable, 0); COMMAND(port, SetIndicationEnable, interruptMask); COMMAND(port, SetInterruptEnable, interruptMask); COMMAND(port, AcknowledgeInterrupt, 0xff); COMMAND(port, AcknowledgeInterrupt, 0xff); /* configure PCMCIA interrupt pin */ mask = (1<<ether->irq); g->gfer |= mask; /* falling edge */ g->grer &= ~mask; /* not rising edge */ g->gpdr &= ~mask; /* input */ ctlr->attached = 1; iunlock(&ctlr->wlock); } static void statistics(Ether* ether) { int port, i, u, w; Ctlr *ctlr; port = ether->port; ctlr = ether->ctlr; /* * 3C59[27] require a read between a PIO write and * reading a statistics register. */ w = (STATUS(port)>>13) & 0x07; COMMAND(port, SelectRegisterWindow, Wstatistics); STATUS(port); for(i = 0; i < UpperFramesOk; i++) ctlr->stats[i] += inb(port+i) & 0xFF; u = inb(port+UpperFramesOk) & 0xFF; ctlr->stats[FramesXmittedOk] += (u & 0x30)<<4; ctlr->stats[FramesRcvdOk] += (u & 0x03)<<8; ctlr->stats[BytesRcvdOk] += ins(port+BytesRcvdOk) & 0xFFFF; ctlr->stats[BytesRcvdOk+1] += ins(port+BytesXmittedOk) & 0xFFFF; switch(ctlr->xcvr){ case xcvrMii: case xcvr100BaseTX: case xcvr100BaseFX: COMMAND(port, SelectRegisterWindow, Wdiagnostic); STATUS(port); ctlr->stats[BytesRcvdOk+2] += inb(port+BadSSD); break; } COMMAND(port, SelectRegisterWindow, w); } static void txstart(Ether* ether) { int port, len, fifo; Ctlr *ctlr; Block *bp; port = ether->port; fifo = port+Fifo; ctlr = ether->ctlr; /* * Attempt to top-up the transmit FIFO. If there's room simply * stuff in the packet length (unpadded to a dword boundary), the * packet data (padded) and remove the packet from the queue. * If there's no room post an interrupt for when there is. * This routine is called both from the top level and from interrupt * level and expects to be called with ctlr->wlock already locked * and the correct register window (Wop) in place. */ for(;;) { if (ctlr->txbp){ bp = ctlr->txbp; ctlr->txbp = 0; } else { bp = qget(ether->oq); if(bp == nil) break; } len = ROUNDUP(BLEN(bp), 4); if(len+4 <= ins(port+TxFree)){ /* 32 bit header */ outs(fifo, BLEN(bp)); outs(fifo, 0x0000); /* data rounded to 32 bits */ { uchar *p = (uchar *)bp->rp; uchar *e = p + len; while (p < e) { outs(fifo, p[1] << 8 | p[0]); outs(fifo, p[3] << 8 | p[2]); p += 4; } } freeb(bp); ether->outpackets++; } else { ctlr->txbp = bp; if(ctlr->txbusy == 0){ ctlr->txbusy = 1; COMMAND(port, SetTxAvailableThresh, len>>ctlr->ts); } break; } } } static void transmit(Ether* ether) { Ctlr *ctlr; int port, w; port = ether->port; ctlr = ether->ctlr; ilock(&ctlr->wlock); w = (STATUS(port)>>13) & 0x07; COMMAND(port, SelectRegisterWindow, Wop); txstart(ether); COMMAND(port, SelectRegisterWindow, w); iunlock(&ctlr->wlock); } static void receive(Ether* ether) { int len, port, rxstatus; Ctlr *ctlr; Block *bp, *rbp; port = ether->port; ctlr = ether->ctlr; while(((rxstatus = ins(port+RxStatus)) & rxIncomplete) == 0){ /* If there was an error, log it and continue. */ if (rxstatus & rxError) { switch (rxstatus & rxError9) { case rxOverrun9: ether->overflows++; break; case oversizedFrame9: case runtFrame9: ether->buffs++; break; case alignmentError9: ether->frames++; break; case crcError9: ether->crcs++; break; } goto next; } /* * If there was an error or a new receive buffer can't be * allocated, discard the packet and go on to the next. */ bp = rbpalloc(iallocb); if (!bp) goto next; rbp = ctlr->rbp; ctlr->rbp = bp; /* * A valid receive packet awaits: * if using PIO, read it into the buffer; * discard the packet from the FIFO; * pass the packet on to whoever wants it. */ len = (rxstatus & rxBytes9); rbp->wp = rbp->rp + len; { int i, count = HOWMANY(len, 4); ulong *p = (ulong *)rbp->rp; ulong ioaddr = port+Fifo; for (i = 0; i < count; i++) { *p = (ins(ioaddr) << 16 | ins(ioaddr)); p++; } } etheriq(ether, rbp, 1); next: COMMAND(port, RxDiscard, 0); while(STATUS(port) & commandInProgress) ; } } static void interrupt(Ureg*, void* arg) { Ether *ether; int port, status, s, w, x; Ctlr *ctlr; ether = arg; port = ether->port; ctlr = ether->ctlr; /* ack interrupt (clear edge detect) */ GPIOREG->gedr = (1 << ether->irq); ilock(&ctlr->wlock); w = (STATUS(port)>>13) & 0x07; COMMAND(port, SelectRegisterWindow, Wop); IRQDEBUG("IRQ"); ctlr->interrupts++; ctlr->timer += inb(port+Timer) & 0xFF; while((status = STATUS(port)) & (interruptMask|interruptLatch)){ IRQDEBUG(" "); if(status & hostError){ IRQDEBUG("hostError"); /* * Adapter failure, try to find out why, reset if * necessary. What happens if Tx is active and a reset * occurs, need to retransmit? This probably isn't right. */ COMMAND(port, SelectRegisterWindow, Wdiagnostic); x = ins(port+FifoDiagnostic); COMMAND(port, SelectRegisterWindow, Wop); print("#l%d: status 0x%uX, diag 0x%uX\n", ether->ctlrno, status, x); if(x & txOverrun){ COMMAND(port, TxReset, 0); COMMAND(port, TxEnable, 0); } if(x & rxUnderrun){ /* * This shouldn't happen... * Reset the receiver and restore the filter and RxEarly * threshold before re-enabling. */ COMMAND(port, SelectRegisterWindow, Wstate); s = (port+RxFilter) & 0x000F; COMMAND(port, SelectRegisterWindow, Wop); COMMAND(port, RxReset, 0); while(STATUS(port) & commandInProgress) ; COMMAND(port, SetRxFilter, s); COMMAND(port, SetRxEarlyThresh, ctlr->rxearly>>ctlr->ts); COMMAND(port, RxEnable, 0); } status &= ~hostError; } if(status & (rxComplete)){ IRQDEBUG("rxComplete"); receive(ether); status &= ~(rxComplete); } if(status & txComplete){ IRQDEBUG("txComplete"); /* * Pop the TxStatus stack, accumulating errors. * Adjust the TX start threshold if there was an underrun. * If there was a Jabber or Underrun error, reset * the transmitter. * For all conditions enable the transmitter. */ s = 0; do { if(x = inb(port+TxStatus)) outb(port+TxStatus, 0); s |= x; } while(STATUS(port) & txComplete); if(s & txUnderrun){ COMMAND(port, SelectRegisterWindow, Wdiagnostic); while(ins(port+MediaStatus) & txInProg) ; COMMAND(port, SelectRegisterWindow, Wop); if(ctlr->txthreshold < ETHERMAXTU) ctlr->txthreshold += ETHERMINTU; } /* * According to the manual, maxCollisions does not require * a TxReset, merely a TxEnable. However, evidence points to * it being necessary on the 3C905. The jury is still out. */ if (s & (txJabber|txUnderrun|maxCollisions)){ COMMAND(port, TxReset, 0); while(STATUS(port) & commandInProgress) ; COMMAND(port, SetTxStartThresh, ctlr->txthreshold>>ctlr->ts); } print("#l%d: txstatus 0x%uX, threshold %d\n", ether->ctlrno, s, ctlr->txthreshold); COMMAND(port, TxEnable, 0); ether->oerrs++; status &= ~txComplete; status |= txAvailable; } if(status & txAvailable){ IRQDEBUG("txAvailable"); COMMAND(port, AcknowledgeInterrupt, txAvailable); ctlr->txbusy = 0; txstart(ether); status &= ~txAvailable; } if(status & updateStats){ IRQDEBUG("updateStats"); statistics(ether); status &= ~updateStats; } /* Currently, this shouldn't happen. */ if(status & rxEarly){ IRQDEBUG("rxEarly"); COMMAND(port, AcknowledgeInterrupt, rxEarly); status &= ~rxEarly; } /* Panic if there are any interrupts not dealt with. */ if(status & interruptMask) panic("#l%d: interrupt mask 0x%uX\n", ether->ctlrno, status); COMMAND(port, AcknowledgeInterrupt, interruptLatch); } COMMAND(port, SelectRegisterWindow, w); iunlock(&ctlr->wlock); } static long ifstat(Ether* ether, void* a, long n, ulong offset) { char *p; int len; Ctlr *ctlr; if(n == 0) return 0; ctlr = ether->ctlr; ilock(&ctlr->wlock); statistics(ether); iunlock(&ctlr->wlock); p = malloc(READSTR); len = snprint(p, READSTR, "interrupts: %lud\n", ctlr->interrupts); len += snprint(p+len, READSTR-len, "timer: %lud\n", ctlr->timer); len += snprint(p+len, READSTR-len, "carrierlost: %lud\n", ctlr->stats[CarrierLost]); len += snprint(p+len, READSTR-len, "sqeerrors: %lud\n", ctlr->stats[SqeErrors]); len += snprint(p+len, READSTR-len, "multiplecolls: %lud\n", ctlr->stats[MultipleColls]); len += snprint(p+len, READSTR-len, "singlecollframes: %lud\n", ctlr->stats[SingleCollFrames]); len += snprint(p+len, READSTR-len, "latecollisions: %lud\n", ctlr->stats[LateCollisions]); len += snprint(p+len, READSTR-len, "rxoverruns: %lud\n", ctlr->stats[RxOverruns]); len += snprint(p+len, READSTR-len, "framesxmittedok: %lud\n", ctlr->stats[FramesXmittedOk]); len += snprint(p+len, READSTR-len, "framesrcvdok: %lud\n", ctlr->stats[FramesRcvdOk]); len += snprint(p+len, READSTR-len, "framesdeferred: %lud\n", ctlr->stats[FramesDeferred]); len += snprint(p+len, READSTR-len, "bytesrcvdok: %lud\n", ctlr->stats[BytesRcvdOk]); len += snprint(p+len, READSTR-len, "bytesxmittedok: %lud\n", ctlr->stats[BytesRcvdOk+1]); snprint(p+len, READSTR-len, "badssd: %lud\n", ctlr->stats[BytesRcvdOk+2]); n = readstr(offset, a, n, p); free(p); return n; } static void setxcvr(int port, int xcvr, int) { int x; COMMAND(port, SelectRegisterWindow, Wsetup); x = ins(port+AddressConfig) & ~xcvrMask9; x |= (xcvr>>20)<<14; outs(port+AddressConfig, x); COMMAND(port, TxReset, 0); while(STATUS(port) & commandInProgress) ; COMMAND(port, RxReset, 0); while(STATUS(port) & commandInProgress) ; } static int autoselect(int port) { int media, x; /* * Pathetic attempt at automatic media selection. * Really just to get the Fast Etherlink 10BASE-T/100BASE-TX * cards operational. * It's a bonus if it works for anything else. */ COMMAND(port, SelectRegisterWindow, Wsetup); x = ins(port+ConfigControl); media = 0; if(x & base10TAvailable9) media |= base10TAvailable; if(x & coaxAvailable9) media |= coaxAvailable; if(x & auiAvailable9) media |= auiAvailable; XCVRDEBUG("autoselect: media %uX\n", media); COMMAND(port, SelectRegisterWindow, Wdiagnostic); XCVRDEBUG("autoselect: media status %luX\n", ins(port+MediaStatus)); if(media & baseTXAvailable){ /* * Must have InternalConfig register. */ setxcvr(port, xcvr100BaseTX, 1); COMMAND(port, SelectRegisterWindow, Wdiagnostic); x = ins(port+MediaStatus) & ~(dcConverterEnabled|jabberGuardEnable); outs(port+MediaStatus, linkBeatEnable|x); delay(10); if(ins(port+MediaStatus) & linkBeatDetect) return xcvr100BaseTX; outs(port+MediaStatus, x); } if(media & base10TAvailable){ setxcvr(port, xcvr10BaseT, 1); COMMAND(port, SelectRegisterWindow, Wdiagnostic); x = ins(port+MediaStatus) & ~dcConverterEnabled; outs(port+MediaStatus, linkBeatEnable|jabberGuardEnable|x); delay(100); XCVRDEBUG("autoselect: 10BaseT media status %luX\n", ins(port+MediaStatus)); if(ins(port+MediaStatus) & linkBeatDetect) return xcvr10BaseT; outs(port+MediaStatus, x); } /* * Botch. */ return autoSelect; } static int eepromdata(int port, int offset) { COMMAND(port, SelectRegisterWindow, Wsetup); while(EEPROMBUSY(port)) ; EEPROMCMD(port, EepromReadRegister, offset); while(EEPROMBUSY(port)) ; return EEPROMDATA(port); } extern int etherelnk3reset(Ether*); static Ether *dbg_ether; static int reset(Ether *ether) { int did, i, slot, port, rxearly, x, xcvr; uchar ea[Eaddrlen]; Ctlr *ctlr; if(ether->port == 0) ether->port = 0x240; /* default position in PCMCIA space */ slot = pcmspecial("3C589", ether); if(slot < 0) slot = pcmspecial("589E", ether); if(slot < 0) return -1; DPRINT("Ethernet found in slot #%d\n",slot); /* save pointer for debugging */ dbg_ether = ether; port = ether->port; ether->pcmslot = slot; /* configure to use PCMCIA interrupt */ ether->irq = ether->sairq; ether->tbdf = BusGPIO; /* set Window 0 configuration registers */ COMMAND(port, SelectWindow, 0); /* ROM size & base - must be set before we can access ROM */ /* transceiver type (for now always 10baseT) */ x = ins(port + AddressConfig); outs(port + AddressConfig, x & 0x20); /* IRQ must be 3 on 3C589 */ x = ins(port + ResourceConfig); outs(port + ResourceConfig, 0x3f00 | (x&0xfff)); /* move product ID to register */ while(ins(port+EEPROMcmd) & 0x8000) ; outs(port+EEPROMcmd, (2<<6)|3); while(ins(port+EEPROMcmd) & 0x8000) ; x = ins(port+EEPROMdata); outs(port + ProductID, x); COMMAND(port, SelectRegisterWindow, Wsetup); x = ins(port+AddressConfig); xcvr = ((x & xcvrMask9)>>14)<<20; if(x & autoSelect9) xcvr |= autoSelect; rxearly = 2044; /* * Check if the adapter's station address is to be overridden. * If not, read it from the EEPROM and set in ether->ea prior to loading the * station address in Wstation. The EEPROM returns 16-bits at a time. */ memset(ea, 0, Eaddrlen); if(memcmp(ea, ether->ea, Eaddrlen) == 0){ for(i = 0; i < Eaddrlen/2; i++){ x = eepromdata(port, i); ether->ea[2*i] = x>>8; ether->ea[2*i+1] = x; } } COMMAND(port, SelectRegisterWindow, Wstation); for(i = 0; i < Eaddrlen; i++) outb(port+i, ether->ea[i]); XCVRDEBUG("reset: xcvr %uX\n", xcvr); if(xcvr & autoSelect) { xcvr = autoselect(port); XCVRDEBUG("autoselect returns: xcvr %uX, did 0x%uX\n", xcvr, did); } switch(xcvr){ case xcvr10BaseT: /* * Enable Link Beat and Jabber to start the * transceiver. */ XCVRDEBUG("Enabling 10Base-T ...\n"); COMMAND(port, SelectRegisterWindow, Wdiagnostic); x = ins(port+MediaStatus) & ~dcConverterEnabled; x |= linkBeatEnable | jabberGuardEnable; outs(port+MediaStatus, x); /* check the line status */ delay(1); x = ins(port+MediaStatus); if (!(x & auiDisable)) print("ERROR: 10Base-T not enabled!\n"); if (!(x & linkBeatDetect)) print("WARNING: No 10Base-T Link Detected\n"); if (x & polarityReversed) print("WARNING: 10Base-T Parity Reversal Detected\n"); break; case xcvr10Base2: XCVRDEBUG("Enabling 10Base-2 ...\n"); COMMAND(port, SelectRegisterWindow, Wdiagnostic); x = ins(port+MediaStatus) & ~(linkBeatEnable|jabberGuardEnable); outs(port+MediaStatus, x); /* * Start the DC-DC converter. * Wait > 800 microseconds. */ COMMAND(port, EnableDcConverter, 0); delay(1); break; } /* * Wop is the normal operating register set. * The 3C59[0257] adapters allow access to more than one register window * at a time, but there are situations where switching still needs to be * done, so just do it. * Clear out any lingering Tx status. */ COMMAND(port, SelectRegisterWindow, Wop); while(inb(port+TxStatus)) outb(port+TxStatus, 0); /* * Allocate a controller structure, clear out the * adapter statistics, clear the statistics logged into ctlr * and enable statistics collection. Xcvr is needed in order * to collect the BadSSD statistics. */ ether->ctlr = malloc(sizeof(Ctlr)); ctlr = ether->ctlr; ilock(&ctlr->wlock); ctlr->xcvr = xcvr; statistics(ether); memset(ctlr->stats, 0, sizeof(ctlr->stats)); ctlr->xcvr = xcvr; ctlr->rxearly = rxearly; if(rxearly >= 2048) ctlr->ts = 2; COMMAND(port, StatisticsEnable, 0); /* * Allocate any receive buffers. */ ctlr->rbp = rbpalloc(allocb); /* * Set a base TxStartThresh which will be incremented * if any txUnderrun errors occur and ensure no RxEarly * interrupts happen. */ ctlr->txthreshold = ETHERMAXTU/2; COMMAND(port, SetTxStartThresh, ctlr->txthreshold>>ctlr->ts); COMMAND(port, SetRxEarlyThresh, rxearly>>ctlr->ts); iunlock(&ctlr->wlock); /* Linkage to the generic ethernet driver. */ ether->port = port; ether->attach = attach; ether->transmit = transmit; ether->interrupt = interrupt; ether->ifstat = ifstat; ether->promiscuous = promiscuous; ether->multicast = multicast; ether->arg = ether; return 0; } #ifdef DEBUG static void dbg_status(Rune) { Ctlr *ctlr; int port, w, i, s; if (!dbg_ether) { print("3c589 Card not found\n"); return; } port = dbg_ether->port; ctlr = dbg_ether->ctlr; print("Interrupt count: %ld\n", ctlr->interrupts); /* dump status registers */ ilock(&ctlr->wlock); s = STATUS(port); w = (s>>13) & 0x07; print("Status Register:\n"); print("\tCurrent Window: 0x%x\n", w); print("\tCommand in Progress: %d\n", (s & 0x1000) ? 1 : 0); print("\tUpdate Statistics: %d\n", (s & 0x0080) ? 1 : 0); print("\tInterrupt Requested: %d\n", (s & 0x0040) ? 1 : 0); print("\tRX Early: %d\n", (s & 0x0020) ? 1 : 0); print("\tRX Complete: %d\n", (s & 0x0010) ? 1 : 0); print("\tTX Available: %d\n", (s & 0x0008) ? 1 : 0); print("\tTX Complete: %d\n", (s & 0x0004) ? 1 : 0); print("\tAdapter Failure: %d\n", (s & 0x0002) ? 1 : 0); print("\tInterrupt Latch: %d\n", (s & 0x0001) ? 1 : 0); COMMAND(port, SelectRegisterWindow, Wstate); STATUS(port); print("Command Results and Internal State:\n"); print("\tTX Start Threshold: 0x%x\n", ins(port+TxStartThresh)); print("\tTX Available Threshold: 0x%x\n", ins(port+TxAvailableThresh)); print("\tRX Early Threshold: 0x%x\n", ins(port+RxEarlyThresh)); print("\tRX Filter: 0x%x\n", ins(port+RxFilter)); print("\tInterrupt Enable: 0x%x\n", ins(port+InterruptEnable)); print("\tIndication Enable: 0x%x\n", ins(port+IndicationEnable)); COMMAND(port, SelectRegisterWindow, Wdiagnostic); STATUS(port); i = ins(port+MediaStatus); print("Media Type and Status Port:\n"); print("\tTP (10Base-T) Enabled: %d\n", (i & 0x8000) ? 1 : 0); print("\tCoax (10Base-2) Enabled: %d\n", (i & 0x4000) ? 1 : 0); print("\tSQE Present: %d\n", (i & 0x1000) ? 1 : 0); print("\tValid Link Beat Detected (TP): %d\n", (i & 0x0800) ? 1 : 0); print("\tPolarity Reversal Delected (TP): %d\n", (i & 0x0400) ? 1 : 0); print("\tJabber Detected (TP): %d\n", (i & 0x0200) ? 1 : 0); print("\tUnsquelch (TP): %d\n", (i & 0x0100) ? 1 : 0); print("\tLink Beat Enabled (TP): %d\n", (i & 0x0080) ? 1 : 0); print("\tJabber Enabled (TP): %d\n", (i & 0x0040) ? 1 : 0); print("\tCarrier sense (CRS): %d\n", (i & 0x0020) ? 1 : 0); print("\tCollision: %d\n", (i & 0x0010) ? 1 : 0); print("\tSQE Statistics Enabled: %d\n", (i & 0x0008) ? 1 : 0); print("\tCRC Strip Disable: %d\n", (i & 0x0004) ? 1 : 0); i = ins(port+NetworkDiagnostic); print("Net Diagnostic Port:\n"); print("\tExternal Loopback: %d\n", (i & 0x8000) ? 1 : 0); print("\tENDAC Loopback: %d\n", (i & 0x4000) ? 1 : 0); print("\tController Loopback: %d\n", (i & 0x2000) ? 1 : 0); print("\tFIFO Loopback: %d\n", (i & 0x1000) ? 1 : 0); print("\tTX Enabled: %d\n", (i & 0x0800) ? 1 : 0); print("\tRX Enabled: %d\n", (i & 0x0400) ? 1 : 0); print("\tTX Transmitting: %d\n", (i & 0x0200) ? 1 : 0); print("\tTX Reset Req.: %d\n", (i & 0x0100) ? 1 : 0); print("\tStatistics Enabled: %d\n", (i & 0x0080) ? 1 : 0); { char rev[16] = {"? BCDEFGHIJKLMNO"}; print("\tASIC Revision: 3C589%c\n", rev[(i >> 1) & 0xf]); } i = ins(port+FifoDiagnostic); print("FIFO Diagnostic Port:\n"); print("\tRX Receiving: %d\n", (i & 0x8000) ? 1 : 0); print("\tRX Underrun: %d\n", (i & 0x2000) ? 1 : 0); print("\tRX Status Underrun: %d\n", (i & 0x1000) ? 1 : 0); print("\tRX Overrun: %d\n", (i & 0x0800) ? 1 : 0); print("\tTX Overrun: %d\n", (i & 0x0400) ? 1 : 0); COMMAND(port, SelectRegisterWindow, w); iunlock(&ctlr->wlock); interrupt(0, dbg_ether); } #endif void ether589link(void) { #ifdef DEBUG debugkey('3', "3c589 Status", dbg_status, 0); #endif addethercard("3C589", reset); }
25.407212
95
0.64937
83db88e707e5bb80eaf793826746a691685d5773
8,606
java
Java
app/src/main/java/harper/com/instagram/adapter/PostsAdapter.java
kushuyanhan/Instagram
65b8fb1bccd4f890e67f2075d5056be17a296c19
[ "Apache-2.0" ]
null
null
null
app/src/main/java/harper/com/instagram/adapter/PostsAdapter.java
kushuyanhan/Instagram
65b8fb1bccd4f890e67f2075d5056be17a296c19
[ "Apache-2.0" ]
1
2019-11-16T11:43:30.000Z
2019-11-23T14:10:37.000Z
app/src/main/java/harper/com/instagram/adapter/PostsAdapter.java
kushuyanhan/Instagram
65b8fb1bccd4f890e67f2075d5056be17a296c19
[ "Apache-2.0" ]
null
null
null
package harper.com.instagram.adapter; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bumptech.glide.Glide; import com.parse.ParseException; import com.parse.ParseFile; import com.parse.SaveCallback; import org.w3c.dom.Comment; import java.text.DateFormat; import java.util.Date; import java.util.List; import harper.com.instagram.R; import harper.com.instagram.activity.CommentActivity; import harper.com.instagram.fragments.PostsFragment; import harper.com.instagram.model.Post; import static harper.com.instagram.R.drawable.ufi_heart_active; /** * Created: xuemaomao * Date: 2019-11-16 * Package: harper.com.instagram * File: PostsAdapter * Description: TODO */ public class PostsAdapter extends RecyclerView.Adapter<PostsAdapter.ViewHolder> { private static final String TAG = "postsadapater"; private Context context; private List<Post> posts; private String description; private List<Comment> comments; private Date createdAt; private ParseFile image; private boolean like; private int likesCount; private String objectId; PostsFragment postsFragment; public PostsAdapter(Context context, List<Post> mPosts, PostsFragment postsFragment) { this.context = context; this.posts = mPosts; this.postsFragment = postsFragment; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(context).inflate(R.layout.item_post, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { Post post = posts.get(position); holder.bind(post); } @Override public int getItemCount() { return posts.size(); } // Clean all elements of the recycler public void clear() { posts.clear(); notifyDataSetChanged(); } // Add a list of items -- change to type used public void addAll(List<Post> list) { posts.addAll(list); notifyDataSetChanged(); } class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private TextView tvHandle; private ImageView ivImage; private TextView tvDescription; private TextView tvCreatedAt; private ImageButton ibtnLike; private ImageButton ibtnComment; private TextView tvLikes; public ViewHolder(@NonNull final View itemView) { super(itemView); tvHandle = itemView.findViewById(R.id.tvHandle); ivImage = itemView.findViewById(R.id.ivImage); tvDescription = itemView.findViewById(R.id.tvDescription); tvCreatedAt = itemView.findViewById(R.id.tvCreatedtime); ibtnLike = itemView.findViewById(R.id.ibtnLike); ibtnComment = itemView.findViewById(R.id.ibtnComment); tvLikes = itemView.findViewById(R.id.tvlikes); } public void bind(final Post post) { //todo: bind the view elements to the posts tvHandle.setText(post.getUser().getUsername()); ParseFile image = post.getImage(); if (image != null) { Glide.with(context).load(image.getUrl()).into(ivImage); } tvDescription.setText(post.getDecription()); createdAt = post.getCreatedAt(); like = post.getLike(); likesCount = post.getLikes(); objectId = post.getObjectId(); if (like) { ibtnLike.setImageResource(R.drawable.ufi_heart_active); } else { ibtnLike.setImageResource(R.drawable.ufi_heart); } tvLikes.setText(likesCount + " likes"); String date = DateFormat.getDateTimeInstance().format(post.getCreatedAt()); tvCreatedAt.setText(date); ibtnLike.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(context, "heart count " + likesCount, Toast.LENGTH_SHORT).show(); like = post.getLike(); likesCount = post.getLikes(); like = !like; if (like) { likesCount++; ibtnLike.setImageResource(ufi_heart_active); Toast.makeText(context, "like " + like + "likes count " + likesCount, Toast.LENGTH_SHORT).show(); } else { likesCount--; ibtnLike.setImageResource(R.drawable.ufi_heart); Toast.makeText(context, "like " + like + "likes count " + likesCount, Toast.LENGTH_SHORT).show(); } tvLikes.setText(likesCount + " likes"); int position = getAdapterPosition(); if (position != RecyclerView.NO_POSITION) { // Check if an item was deleted, but the user clicked it before the UI removed it Post post = posts.get(position); final String objectId = post.getObjectId(); post.setLikes(likesCount); post.setLike(like); post.saveInBackground(new SaveCallback() { @Override public void done(ParseException e) { if (e != null) { Log.d(TAG, "error while saving"); e.printStackTrace(); return; } Log.d(TAG, "Success!" + likesCount); } }); } } }); //go to comment page ibtnComment.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(postsFragment.getActivity(), CommentActivity.class); i.putExtra("objectId", objectId); i.putExtra("likesCount", likesCount); postsFragment.startActivity(i); } }); // ibtnComment.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // int position = getAdapterPosition(); // if (position != RecyclerView.NO_POSITION) { // Check if an item was deleted, but the user clicked it before the UI removed it // Post post = posts.get(position); // final String objectId = post.getObjectId(); // ParseQuery<Post> query = ParseQuery.getQuery(Post.class); // query.getInBackground(objectId, new GetCallback<Post>() { // public void done(Post item, ParseException e) { // if (e == null) { // description = item.getDecription(); // //createdAt = item.getCreatedAt(); // //image = item.getImage(); // // Intent intent = new Intent(context, CommentActivity.class); // intent.putExtra("objectId", objectId); // intent.putExtra("description", description); // //intent.putExtra("comment", (Parcelable) comments); // postsFragment.startActivity(intent); // // } else { // e.printStackTrace(); // return; // } // } // // }); // } // } // }); } @Override public void onClick(View view) { } } }
37.255411
147
0.545201
b3b420e0cb0942acba045b7ddf3b5be5fe90ee05
2,300
dart
Dart
client_flutter/lib/src/widgets/homepage/favorite_floating_action_button.dart
oliwave/Hitchhike
3f14429e9f67779de94441911f26b98b57a9e866
[ "MIT" ]
1
2021-04-24T17:08:10.000Z
2021-04-24T17:08:10.000Z
client_flutter/lib/src/widgets/homepage/favorite_floating_action_button.dart
oliwave/Hitchhike
3f14429e9f67779de94441911f26b98b57a9e866
[ "MIT" ]
null
null
null
client_flutter/lib/src/widgets/homepage/favorite_floating_action_button.dart
oliwave/Hitchhike
3f14429e9f67779de94441911f26b98b57a9e866
[ "MIT" ]
null
null
null
import 'package:client_flutter/src/provider/provider_collection.dart'; import 'package:client_flutter/src/screen/favorite_routes_page.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class FavoriteFloatingActionButton extends StatefulWidget { @override _FavoriteFloatingActionButtonState createState() => _FavoriteFloatingActionButtonState(); } class _FavoriteFloatingActionButtonState extends State<FavoriteFloatingActionButton> with SingleTickerProviderStateMixin { AnimationController _favoriteButtonController; Animation<Alignment> _alignmentAnimation; @override void initState() { _favoriteButtonController = AnimationController( vsync: this, duration: Duration( milliseconds: 300, ), ); _alignmentAnimation = _favoriteButtonController.drive( AlignmentTween( begin: Alignment(0.9, -0.5), end: Alignment(2, -0.5), ), ); final manager = Provider.of<HomepageProvider>( context, listen: false, ).animationManager; manager.favoriteButtonController = _favoriteButtonController; super.initState(); } @override Widget build(BuildContext context) { return AnimatedBuilder( animation: _alignmentAnimation, builder: (BuildContext context, Widget floatingButton) { return Align( alignment: _alignmentAnimation.value, child: floatingButton, ); }, child: Hero( tag: 'bookmark', child: Material( child: Container( decoration: const BoxDecoration( color: Colors.white, borderRadius: BorderRadius.all( Radius.circular(30), ), boxShadow: [ BoxShadow( blurRadius: 2, color: Colors.grey, ), ], ), child: IconButton( icon: Icon( Icons.bookmark, // color: Colors.blue[600], color: Colors.black87, ), onPressed: () { Navigator.pushNamed(context, FavoriteRoutesPage.routeName); }, ), ), ), ), ); } }
26.744186
75
0.596087
c24adab2dcb5d22d08fcd9970f222d8434efd6fc
494
go
Go
cmd/api/app.go
deqode/GoArcc
e5acbb5d11c577ef093b8b4c8c7bcbd14e48b763
[ "MIT" ]
92
2021-07-13T07:57:43.000Z
2022-03-09T22:34:38.000Z
cmd/api/app.go
radeqode/GoArcc
a389a593b8c2672be0be088e9621fcf9aa36f62f
[ "MIT" ]
null
null
null
cmd/api/app.go
radeqode/GoArcc
a389a593b8c2672be0be088e9621fcf9aa36f62f
[ "MIT" ]
7
2021-07-21T07:44:20.000Z
2022-03-22T07:12:32.000Z
package main import "go.uber.org/fx" //GetApp : Get App will return the fx app. // Fx App contains invokers , providers , lifecycles etc. // When we start the application using fx app then used providers will initialises first. // After that invoker will invoked automatically. // Note: Invokers will be executed in the same order. func GetApp() *fx.App { opts := make([]fx.Option, 0) opts = GetProviderOptions() opts = append(opts, GetInvokersOptions()) return fx.New( opts..., ) }
27.444444
91
0.716599
8023d85f47bfd693f9b39709772ae1cd39994dc3
6,473
java
Java
egov-idgen/src/main/java/org/egov/id/service/MdmsService.java
dineshkumardboss/d
78df46dc7b8381835c7197bec7fcc5868f679de8
[ "MIT" ]
null
null
null
egov-idgen/src/main/java/org/egov/id/service/MdmsService.java
dineshkumardboss/d
78df46dc7b8381835c7197bec7fcc5868f679de8
[ "MIT" ]
17
2020-02-06T06:55:14.000Z
2021-12-09T22:49:40.000Z
egov-idgen/src/main/java/org/egov/id/service/MdmsService.java
punitdwievdi45/velocis-projects
01df6e6cd760ee23342a4995af2fffe18ad5a5b7
[ "MIT" ]
1
2020-05-13T21:43:41.000Z
2020-05-13T21:43:41.000Z
package org.egov.id.service; import java.io.IOException; import java.util.*; import org.egov.id.model.IdRequest; import org.egov.id.model.RequestInfo; import org.egov.mdms.model.MasterDetail; import org.egov.mdms.model.MdmsCriteria; import org.egov.mdms.model.MdmsCriteriaReq; import org.egov.mdms.model.MdmsResponse; import org.egov.mdms.model.ModuleDetail; import org.egov.mdms.service.MdmsClientService; import org.egov.tracer.model.CustomException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.jayway.jsonpath.DocumentContext; import com.jayway.jsonpath.JsonPath; import lombok.extern.log4j.Log4j; @Service @Log4j public class MdmsService { @Autowired MdmsClientService mdmsClientService; // 'tenants' & 'citymodule' are the JSON files inside the folder 'tenant'. private static final String tenantMaster = "tenants"; private static final String cityMaster = "citymodule"; private static final String tenantModule = "tenant"; //'IdFormat' is the JSON file in the Folder 'common-masters'. private static final String formatMaster = "IdFormat"; private static final String formatModule = "common-masters"; public MdmsResponse getMasterData(RequestInfo requestInfo, String tenantId, Map<String, List<MasterDetail>> masterDetails) { MdmsResponse mdmsResponse = null; try { mdmsResponse = mdmsClientService.getMaster(RequestInfo.toCommonRequestInfo(requestInfo), tenantId, masterDetails); } catch (IOException e) { // TODO Auto-generated catch block log.error("Error occurred while fetching MDMS data", e); } return mdmsResponse; } /** * Description : This method to get CityCode from Mdms * * @param idRequest * @param requestInfo * @return cityCode * @throws Exception */ public String getCity(RequestInfo requestInfo, IdRequest idRequest) { Map<String, String> getCity = doMdmsServiceCall(requestInfo, idRequest); String cityCode = null; try { if (getCity != null) { cityCode = getCity.get(tenantMaster); } } catch (Exception e) { // TODO Auto-generated catch block log.error("Error occurred while fetching city code", e); throw new CustomException("PARSING ERROR", "Failed to get citycode from MDMS"); } return cityCode; } /** * Description : This method to get IdFormat from Mdms * * @param idRequest * @param requestInfo * @return IdFormat * @throws Exception */ public String getIdFormat(RequestInfo requestInfo, IdRequest idRequest) { Map<String, String> getIdFormat = doMdmsServiceCall(requestInfo, idRequest); String idFormat = null; try { if (getIdFormat != null) { idFormat = getIdFormat.get(formatMaster); } } catch (Exception e) { // TODO Auto-generated catch block log.error("Error while fetching id format", e); throw new CustomException("PARSING ERROR", "Failed to get formatid from MDMS"); } return idFormat; } /** * Prepares and returns Mdms search request * * @param requestInfo * @return MAP */ private Map<String, String> doMdmsServiceCall(RequestInfo requestInfo, IdRequest idRequest) { String idname = idRequest.getIdName(); String tenantId = idRequest.getTenantId(); String idFormatFromMdms = null; String cityCodeFromMdms = null; Map<String, List<MasterDetail>> masterDetails = new HashMap<String, List<MasterDetail>>(); List<MasterDetail> masterDetailListCity = new LinkedList(); List<MasterDetail> masterDetailListFormat = new LinkedList(); MasterDetail masterDetailForCity = MasterDetail.builder().name(tenantMaster) .filter("[?(@.code=='" + tenantId + "')]").build(); masterDetailListCity.add(masterDetailForCity); MasterDetail masterDetailForFormat = MasterDetail.builder().name(formatMaster) .filter("[?(@.idname=='" + idname + "')]").build(); masterDetailListFormat.add(masterDetailForFormat); masterDetails.put(tenantModule, masterDetailListCity); masterDetails.put(formatModule, masterDetailListFormat); MdmsResponse mdmsResponse = null; try { mdmsResponse = getMasterData(requestInfo, tenantId, masterDetails); if (mdmsResponse.getMdmsRes() != null && mdmsResponse.getMdmsRes().containsKey(tenantModule) && mdmsResponse.getMdmsRes().get(tenantModule).containsKey(tenantMaster) && mdmsResponse.getMdmsRes().get(tenantModule).get(tenantMaster).size() > 0 && mdmsResponse.getMdmsRes().get(tenantModule).get(tenantMaster).get(0) != null) { DocumentContext documentContext = JsonPath .parse(mdmsResponse.getMdmsRes().get(tenantModule).get(tenantMaster).get(0)); cityCodeFromMdms = documentContext.read("$.city.code"); log.debug("Found city code as - " + cityCodeFromMdms); } if (mdmsResponse.getMdmsRes() != null && mdmsResponse.getMdmsRes().containsKey(formatModule) && mdmsResponse.getMdmsRes().get(formatModule).containsKey(formatMaster) && mdmsResponse.getMdmsRes().get(formatModule).get(formatMaster).size() > 0 && mdmsResponse.getMdmsRes().get(formatModule).get(formatMaster).get(0) != null) { DocumentContext documentContext = JsonPath .parse(mdmsResponse.getMdmsRes().get(formatModule).get(formatMaster).get(0)); idFormatFromMdms = documentContext.read("$.format"); } } catch (Exception e) { // TODO Auto-generated catch block log.error("MDMS Fetch failed", e); throw new CustomException("PARSING ERROR", "Failed to get citycode/formatid from MDMS"); } Map<String, String> mdmsCallMap = new HashMap(); mdmsCallMap.put(formatMaster, idFormatFromMdms); mdmsCallMap.put(tenantMaster, cityCodeFromMdms); return mdmsCallMap; } }
37.416185
110
0.644678
cb0754334690e8acd8432416d484deb3c804d895
10,387
h
C
admin/pchealth/sysinfo/control/whqlobj.h
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/pchealth/sysinfo/control/whqlobj.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/pchealth/sysinfo/control/whqlobj.h
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// WhqlObj.h : Declaration of the CWhqlObj #ifndef __WHQLOBJ_H_ #define __WHQLOBJ_H_ #include "resource.h" // main symbols #include "WbemProv.h" #include <softpub.h> // Macros and pre-defined values #define cbX(X) sizeof(X) #define cA(a) (cbX(a)/cbX(a[0])) #define MALLOC(x) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (x)) #define FREE(x) if (x) { HeapFree(GetProcessHeap(), 0, (x)); x = NULL; } #define EXIST(x) (GetFileAttributes(x) != 0xFFFFFFFF) #define MAX_INT 0x7FFFFFFF #define HASH_SIZE 100 #define NUM_PAGES 2 typedef struct tagFileNode { LPTSTR lpFileName; LPTSTR lpDirName; LPTSTR lpVersion; LPTSTR lpCatalog; LPTSTR lpSignedBy; LPTSTR lpTypeName; INT iIcon; BOOL bSigned; BOOL bScanned; BOOL bValidateAgainstAnyOs; DWORD LastError; SYSTEMTIME LastModified; struct tagFileNode *next; } FILENODE, *LPFILENODE; ///////////////////////////////////////////////////////////////////////////// // CWhqlObj class ATL_NO_VTABLE CWhqlObj : public CComObjectRootEx<CComMultiThreadModel>, public CComCoClass<CWhqlObj, &CLSID_WhqlObj>, public IDispatchImpl<IWhqlObj, &IID_IWhqlObj, &LIBID_MSINFO32Lib>, public IWbemProviderInit, public IWbemServices { public: CWhqlObj() { } //DECLARE_REGISTRY_RESOURCEID(IDR_WHQLPROV) DECLARE_REGISTRY_RESOURCEID(IDR_WHQLOBJ) DECLARE_PROTECT_FINAL_CONSTRUCT() BEGIN_COM_MAP(CWhqlObj) COM_INTERFACE_ENTRY(IWhqlObj) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(IWbemProviderInit) COM_INTERFACE_ENTRY(IWbemServices) END_COM_MAP() // IWhqlObj public: //IWbemProviderInit STDMETHOD(Initialize)( /* [in] */ LPWSTR pszUser, /* [in] */ LONG lFlags, /* [in] */ LPWSTR pszNamespace, /* [in] */ LPWSTR pszLocale, /* [in] */ IWbemServices *pNamespace, /* [in] */ IWbemContext *pCtx, /* [in] */ IWbemProviderInitSink *pInitSink); STDMETHOD(GetByPath)(BSTR Path, IWbemClassObject FAR* FAR* pObj, IWbemContext *pCtx) {return WBEM_E_NOT_SUPPORTED;}; //IWbemServices HRESULT STDMETHODCALLTYPE OpenNamespace( /* [in] */ const BSTR strNamespace, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [unique][in][out] */ IWbemServices __RPC_FAR *__RPC_FAR *ppWorkingNamespace, /* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppResult){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE CancelAsyncCall( /* [in] */ IWbemObjectSink __RPC_FAR *pSink){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE QueryObjectSink( /* [in] */ long lFlags, /* [out] */ IWbemObjectSink __RPC_FAR *__RPC_FAR *ppResponseHandler){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE GetObject( /* [in] */ const BSTR strObjectPath, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [unique][in][out] */ IWbemClassObject __RPC_FAR *__RPC_FAR *ppObject, /* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppCallResult){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE GetObjectAsync( /* [in] */ const BSTR strObjectPath, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE PutClass( /* [in] */ IWbemClassObject __RPC_FAR *pObject, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppCallResult){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE PutClassAsync( /* [in] */ IWbemClassObject __RPC_FAR *pObject, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE DeleteClass( /* [in] */ const BSTR strClass, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppCallResult){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE DeleteClassAsync( /* [in] */ const BSTR strClass, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE CreateClassEnum( /* [in] */ const BSTR strSuperclass, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [out] */ IEnumWbemClassObject __RPC_FAR *__RPC_FAR *ppEnum){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE CreateClassEnumAsync( /* [in] */ const BSTR strSuperclass, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE PutInstance( /* [in] */ IWbemClassObject __RPC_FAR *pInst, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppCallResult){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE PutInstanceAsync( /* [in] */ IWbemClassObject __RPC_FAR *pInst, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE DeleteInstance( /* [in] */ const BSTR strObjectPath, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppCallResult){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE DeleteInstanceAsync( /* [in] */ const BSTR strObjectPath, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE CreateInstanceEnum( /* [in] */ const BSTR strClass, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [out] */ IEnumWbemClassObject __RPC_FAR *__RPC_FAR *ppEnum){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE CreateInstanceEnumAsync( /* [in] */ const BSTR strClass, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler); HRESULT STDMETHODCALLTYPE ExecQuery( /* [in] */ const BSTR strQueryLanguage, /* [in] */ const BSTR strQuery, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [out] */ IEnumWbemClassObject __RPC_FAR *__RPC_FAR *ppEnum){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE ExecQueryAsync( /* [in] */ const BSTR strQueryLanguage, /* [in] */ const BSTR strQuery, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE ExecNotificationQuery( /* [in] */ const BSTR strQueryLanguage, /* [in] */ const BSTR strQuery, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [out] */ IEnumWbemClassObject __RPC_FAR *__RPC_FAR *ppEnum){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE ExecNotificationQueryAsync( /* [in] */ const BSTR strQueryLanguage, /* [in] */ const BSTR strQuery, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE ExecMethod( /* [in] */ const BSTR strObjectPath, /* [in] */ const BSTR strMethodName, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemClassObject __RPC_FAR *pInParams, /* [unique][in][out] */ IWbemClassObject __RPC_FAR *__RPC_FAR *ppOutParams, /* [unique][in][out] */ IWbemCallResult __RPC_FAR *__RPC_FAR *ppCallResult){return WBEM_E_NOT_SUPPORTED;}; HRESULT STDMETHODCALLTYPE ExecMethodAsync( /* [in] */ const BSTR strObjectPath, /* [in] */ const BSTR strMethodName, /* [in] */ long lFlags, /* [in] */ IWbemContext __RPC_FAR *pCtx, /* [in] */ IWbemClassObject __RPC_FAR *pInParams, /* [in] */ IWbemObjectSink __RPC_FAR *pResponseHandler){return WBEM_E_NOT_SUPPORTED;}; private: IWbemServices* m_pNamespace; //IWbemClassObject* m_pClass; //CString m_csPathStr ; //CPtrArray m_ptrArr; SCODE PutPropertyValue(IWbemClassObject*, LPCTSTR, LPCTSTR); SCODE PutPropertyDTMFValue(IWbemClassObject* pInstance, LPCTSTR szName, LPCTSTR szValue);//v-stlowe int WalkTree(void); int CreateList(CPtrArray&, IWbemClassObject *&, IWbemContext *, Classes_Provided); SCODE GetServerAndNamespace(IWbemContext*, CString&); void BuildPrinterFileList(CPtrArray&, IWbemClassObject *&, IWbemContext *, Classes_Provided); }; #endif //__WHQLOBJ_H_
43.279167
119
0.590546
abfd127b1501ed515d75e896d8ee4db315a3b8b4
2,203
go
Go
2018/day25.go
k8s-arya/lizthegrey-adventofcode
73ad13fcf46911231b70b86c41630797a5bc1edd
[ "Apache-2.0" ]
81
2018-12-01T13:38:35.000Z
2022-01-21T17:14:08.000Z
2018/day25.go
k8s-arya/lizthegrey-adventofcode
73ad13fcf46911231b70b86c41630797a5bc1edd
[ "Apache-2.0" ]
1
2020-12-17T16:03:16.000Z
2020-12-18T15:05:00.000Z
2018/day25.go
k8s-arya/lizthegrey-adventofcode
73ad13fcf46911231b70b86c41630797a5bc1edd
[ "Apache-2.0" ]
14
2019-01-04T12:55:18.000Z
2022-02-12T14:32:01.000Z
package main import ( "bufio" "flag" "fmt" "os" "strconv" "strings" ) var inputFile = flag.String("inputFile", "inputs/day25.input", "Relative file path to use as input.") type Coord4 struct { X, Y, Z, T int } func (c Coord4) Adjacent(t Coord4) bool { deltaX := c.X - t.X deltaY := c.Y - t.Y deltaZ := c.Z - t.Z deltaT := c.T - t.T sum := 0 if deltaX < 0 { sum -= deltaX } else { sum += deltaX } if deltaY < 0 { sum -= deltaY } else { sum += deltaY } if deltaZ < 0 { sum -= deltaZ } else { sum += deltaZ } if deltaT < 0 { sum -= deltaT } else { sum += deltaT } return sum <= 3 } func main() { flag.Parse() f, err := os.Open(*inputFile) if err != nil { return } defer f.Close() coords := make([]Coord4, 0) r := bufio.NewReader(f) for { l, err := r.ReadString('\n') if err != nil || len(l) == 0 { break } l = l[:len(l)-1] nums := strings.Split(l, ",") x, _ := strconv.Atoi(nums[0]) y, _ := strconv.Atoi(nums[1]) z, _ := strconv.Atoi(nums[2]) t, _ := strconv.Atoi(nums[3]) coords = append(coords, Coord4{x, y, z, t}) } // Maps index of coord to clique number. cliquesByCoord := make(map[int]int) coordsByClique := make(map[int][]int) // Seed the first element. highestClique := 1 changed := true for changed { changed = false for c := range coords { cClique := cliquesByCoord[c] if cClique == 0 { cliquesByCoord[c] = highestClique coordsByClique[highestClique] = []int{c} cClique = highestClique highestClique++ changed = true } for t := range coords { tClique := cliquesByCoord[t] if tClique == cClique { continue } if coords[c].Adjacent(coords[t]) { if tClique == 0 { cliquesByCoord[t] = cClique coordsByClique[cClique] = append(coordsByClique[cClique], t) changed = true continue } // Merge the t Clique and the c Clique. changed = true for _, v := range coordsByClique[tClique] { cliquesByCoord[v] = cClique } coordsByClique[cClique] = append(coordsByClique[cClique], coordsByClique[tClique]...) delete(coordsByClique, tClique) } } } } fmt.Println(len(coordsByClique)) }
18.82906
101
0.592828
2b4b7e060b10866a5b5efcdeec01d90d502ccb59
5,342
swift
Swift
Tests/PlotlyTests/Subplots/MixedSubplots.swift
vinbrule/Plotly.swift
6782f71915bfe2cb018f184815308d7217d99f12
[ "MIT" ]
null
null
null
Tests/PlotlyTests/Subplots/MixedSubplots.swift
vinbrule/Plotly.swift
6782f71915bfe2cb018f184815308d7217d99f12
[ "MIT" ]
null
null
null
Tests/PlotlyTests/Subplots/MixedSubplots.swift
vinbrule/Plotly.swift
6782f71915bfe2cb018f184815308d7217d99f12
[ "MIT" ]
null
null
null
import XCTest import Plotly import CSV // https://plot.ly/javascript/mixed-subplots/ final class MixedSubplots: XCTestCase { static var allTests = [ ("testMixedSubplots", testMixedSubplots) ] struct Volcano: Decodable { let number, name, country, region: String let latitude, longitude: Double let elevation: Int? let type, status, lastKnown: String enum CodingKeys: String, CodingKey { case number = "Number", name = "Volcano Name", country = "Country", region = "Region" case latitude = "Latitude", longitude = "Longitude" case elevation = "Elev" case type = "Type", status = "Status", lastKnown = "Last Known" } } class func downloadVolcanos() -> [Volcano] { let url = URL(string: "https://raw.githubusercontent.com/plotly/datasets/master/volcano_db.csv")! let contents = try! String(contentsOf: url, encoding: .ascii) let reader = try! CSVReader(string: contents, hasHeaderRow: true) return reader.map { _ in try! CSVRowDecoder().decode(Volcano.self, from: reader) } } // https://plot.ly/javascript/mixed-subplots/#mixed-subplots func testMixedSubplots() { let volcanos = Self.downloadVolcanos() let trace1 = Scatter3D( showLegend: false, x: volcanos.map { $0.status }, y: volcanos.map { $0.type }, z: volcanos.map { $0.elevation ?? 0 }, text: .variable(volcanos.map { $0.country }), mode: .markers, marker: .init( size: 2, line: .init( coloring: .constant(.transparent) ), coloring: .colorScale(volcanos.map { Double($0.elevation ?? 0) }), colorScale: .reds ), hoverInfo: [.x, .y, .z, .text], scene: .init( uid: 1, domain: .init(x: [0.55, 1], y: [0, 0.6]), xAxis: .init( title: .init(text: "Status"), showTickLabels: false, showGrid: true, gridColor: .white ), yAxis: .init( title: .init(text: "Type"), showTickLabels: false, showGrid: true, gridColor: .white ), zAxis: .init( title: .init(text: "Elevation"), showTickLabels: false, showGrid: true, gridColor: .white ) ) ) let trace2 = Histogram<[Int?], [Int]>( showLegend: false, hoverInfo: [.x, .y], x: volcanos.map { $0.elevation }, marker: Shared.Marker( coloring: .constant(.red) ), xAxis: .init( uid: 2, tickAngle: 45, tickSuffix: "m", domain: [0.6, 1] ), yAxis: .init( uid: 2, showGrid: false, domain: [0.7, 1] ) ) trace2.xAxis.anchor = .yAxis(trace2.yAxis) trace2.yAxis.anchor = .xAxis(trace2.xAxis) let trace3 = ScatterGeo<[Double], [Double]>( showLegend: false, longitude: volcanos.map { $0.longitude }, latitude: volcanos.map { $0.latitude }, locationMode: .countryNames, mode: .markers, text: .variable(volcanos.map { String($0.elevation ?? 0) }), marker: ScatterGeo<[Double], [Double]>.GradientMarker( symbol: .circle, opacity: 0.8, size: 4, line: .init(width: 1), coloring: .colorScale(volcanos.map { Double($0.elevation ?? 0) }), colorScale: .reds ), hoverInfo: .text, geo: Layout.Geo( uid: 3, domain: .init( x: [0, 0.45], y: [0.02, 0.98] ), scope: .world, projection: .init(type: .orthographic), showLand: true, landColor: .RGB(250, 250, 250), showOcean: true, oceanColor: .RGB(6, 66, 115), showLakes: true, lakeColor: .RGB(127, 205, 255), showCountries: true, countryColor: .RGB(217, 217, 217), countryWidth: 0.5, subUnitWidth: 0.5, backgroundColor: .black ) ) let layout = Layout( font: .init(color: .white), title: "Volcano Database: Elevation", height: 600, paperBackgroundColor: .black, plotBackgroundColor: .black, annotations: [ .init( text: "Source: NOAA", showArrow: false, xReference: .paper, x: 0, yReference: .paper, y: 0 ) ] ) let figure = Figure(data: [trace1, trace2, trace3], layout: layout) output(figure) } }
33.810127
105
0.457881
b20014e47b7cf3b84d9a89e239716cb6c800c7ed
19
asm
Assembly
src/main/fragment/csg65ce02-common/vbuaa=vbuaa_plus_vbuzz.asm
jbrandwood/kickc
d4b68806f84f8650d51b0e3ef254e40f38b0ffad
[ "MIT" ]
2
2022-03-01T02:21:14.000Z
2022-03-01T04:33:35.000Z
src/main/fragment/csg65ce02-common/vbuaa=vbuaa_plus_vbuzz.asm
jbrandwood/kickc
d4b68806f84f8650d51b0e3ef254e40f38b0ffad
[ "MIT" ]
null
null
null
src/main/fragment/csg65ce02-common/vbuaa=vbuaa_plus_vbuzz.asm
jbrandwood/kickc
d4b68806f84f8650d51b0e3ef254e40f38b0ffad
[ "MIT" ]
null
null
null
stz $ff clc adc $ff
6.333333
7
0.684211
8a6e0667a3dd4a47ad942604d8f29b4304c368d0
7,028
ps1
PowerShell
.github/workflows/update-project-items.ps1
bobheadlabs/sourcegraph
9699b27c150ea30b64abe06e4dfbf6eddc8b71b0
[ "Apache-2.0" ]
null
null
null
.github/workflows/update-project-items.ps1
bobheadlabs/sourcegraph
9699b27c150ea30b64abe06e4dfbf6eddc8b71b0
[ "Apache-2.0" ]
null
null
null
.github/workflows/update-project-items.ps1
bobheadlabs/sourcegraph
9699b27c150ea30b64abe06e4dfbf6eddc8b71b0
[ "Apache-2.0" ]
null
null
null
# Script to run as a GitHub action on issue and PR updates that will update the associated GitHub Beta project items. [CmdletBinding()] param( # GitHub GraphQL Node ID of the GitHub Beta project [Parameter(Mandatory)] [string] $ProjectNodeId, # The team/* label to filter issues/PRs by. `labeled` events for other labels than this label will be ignored. [Parameter(Mandatory)] [string] $TeamLabel, # A regular expression pattern to match milestone titles by. # All `milestoned` events not matching the pattern will be ignored. [Parameter(Mandatory)] [regex] $TeamIterationMilestonePattern, # Previously set up webhook URI from https://sourcegraph.slack.com/apps/A0F7XDUAZ [Parameter(Mandatory)] [string] $SlackWebhookUri, # Slack channel to post to [Parameter(Mandatory)] [string] $SlackChannel ) switch ($github.event_name) { 'issues' { Write-Information "Issue was $($github.event.action)" if ($github.event.action -eq 'labeled') { # If issue was labeled, make sure to only consider the team label being added. if ($github.event.label.name -ne $TeamLabel) { Write-Information "Labeled with non-team label ($($github.event.label.name)), exiting." return } # Add issue to the team project board. Idempotent. [pscustomobject]$github.event.issue | Add-GitHubBetaProjectItem -ProjectNodeId $ProjectNodeId } elseif ($github.event.action -eq 'milestoned') { # If issue was milestoned, make sure to only consider team iteration milestones if ($github.event.issue.milestone.title -notmatch $TeamIterationMilestonePattern) { Write-Information "Milestoned with non-matching milestone ($($github.event.issue.milestone.title)), exiting. Pattern: $TeamIterationMilestonePattern" return } # Add issue to the team project board. Idempotent, will return the item if already exists in the board. $item = [pscustomobject]$github.event.issue | Add-GitHubBetaProjectItem -ProjectNodeId $ProjectNodeId # Update status and set "Proposed by" to the event actor $proposer = $github.event.sender.login Write-Information "Updating issue as 'Proposed for iteration' by @$proposer" $item | Set-GitHubBetaProjectItemField -Name 'Status' -Value 'Proposed for iteration' | Set-GitHubBetaProjectItemField -Name 'Proposed by' -Value $proposer # Post Slack message $stats = Find-GitHubIssue "org:sourcegraph is:issue milestone:`"$($item.content.milestone.title)`"" | Get-GitHubBetaProjectItem | Where-Object { $_.project.id -eq $ProjectNodeId -and $_.Fields['Status'] -ne 'Done' } | ForEach-Object { $_.Fields['Size 🔵'] ?? 1 } | Measure-Object -AllStats $color = if ($item.content.state -eq 'OPEN') { '#1A7F37' } else { '#8250DF' } $message = "*$proposer* proposed a new issue for iteration <$($item.content.milestone.url)|$($item.content.milestone.title)>.`n" + "There are now $($stats.Sum) points of open issues in the iteration." # Plain text fallback for contexts without formatting capability, e.g. push notifications $fallback = "*$proposer* proposed a new issue for iteration $($item.content.milestone.title): #$($item.content.number) $($item.content.title). There are now $($stats.Sum) points of open issues in the iteration." New-SlackMessageAttachment ` -Pretext $message ` -Color $color ` -AuthorName $item.content.author.login ` -AuthorIcon $item.content.author.avatarUrl ` -Title "#$($item.content.number) $($item.content.title)" ` -TitleLink $item.content.url ` -Text $item.content.bodyText.Substring(0, [System.Math]::Min(1000, $item.content.bodyText.Length)) ` -Fields @( @{ title = 'Size'; value = $item.Fields['Size 🔵']; short = $true }, @{ title = 'Importance'; value = $item.Fields['Importance']; short = $true }, @{ title = 'Labels'; value = $item.content.labels | ForEach-Object name | Join-String -Separator ', '; short = $true }, @{ title = 'Assignee'; value = $item.content.assignees | ForEach-Object login | Join-String -Separator ', '; short = $true } ) ` -Fallback $fallback | New-SlackMessage -Username 'Iteration Bot' -IconEmoji ':robot:' -Channel $SlackChannel | Send-SlackMessage -Uri $SlackWebhookUri } else { # If issue was closed or reopened, update Status column $status = if ($github.event.action -eq 'closed') { 'Done' } else { 'In Progress' } [pscustomobject]$github.event.issue | # Idempotent, will return the item if already exists Add-GitHubBetaProjectItem -ProjectNodeId $ProjectNodeId | Set-GitHubBetaProjectItemField -FieldName 'Status' -Value $status | ForEach-Object { Write-Information "Updated `"Status`" field of project item for $($_.content.url) to `"$status`"" } } } 'pull_request' { $pr = $github.event.pull_request # Ignore merged and closed PRs if ($pr.state -ne 'open') { return } $status = if ($pr.draft) { 'In Progress' } else { 'In Review' } # Regex for extracting the "Closes #1234" pattern in GitHub PR descriptions $fixIssuePattern = "(?:close|fixe?|resolve)(?:[sd])? (?:#|(?<owner>[\w_-]+)/(?<repo>[\w_-]+)#|https://github\.com/(?<owner>[\w_-]+)/(?<repo>[\w_-]+)/issues/)(?<number>\d+)" # Get fixed issues from the PR description [regex]::Matches($pr.body, $fixIssuePattern, [Text.RegularExpressions.RegexOptions]::IgnoreCase) | ForEach-Object { $owner = if ($_.Groups['owner'].Success) { $_.Groups['owner'].Value } else { $github.event.repository.owner.login } $repo = if ($_.Groups['repo'].Success) { $_.Groups['repo'].Value } else { $github.event.repository.name } $number = $_.Groups['number'].Value Write-Information "Found fixed issue $owner/$repo#$number" Get-GitHubIssue -Owner $owner -Repository $repo -Number $number } | Where-Object { $_.labels | Where-Object { $_.name -eq $TeamLabel } } | # Idempotent, will return the item if already exists Add-GitHubBetaProjectItem -ProjectNodeId $ProjectNodeId | Set-GitHubBetaProjectItemField -FieldName 'Status' -Value $status | ForEach-Object { Write-Information "Updated `"Status`" field of project item for $($_.content.url) to `"$status`"" } } }
51.676471
223
0.608139
bebbd6aaa7fb2903a6185410f68db0a8db935185
1,233
sql
SQL
vault-pgsql/sql-scripts/create_vault_table.sql
yura-shutkin/docker-lab
aa58fd82a6cf9c96b1dc24939fe3d885c667fd5d
[ "MIT" ]
4
2020-09-23T10:01:36.000Z
2022-02-21T07:44:08.000Z
vault-pgsql/sql-scripts/create_vault_table.sql
infra-lab-xyz/docker-lab
aa58fd82a6cf9c96b1dc24939fe3d885c667fd5d
[ "MIT" ]
1
2019-05-31T11:40:16.000Z
2019-05-31T11:40:16.000Z
vault-pgsql/sql-scripts/create_vault_table.sql
infra-lab-xyz/docker-lab
aa58fd82a6cf9c96b1dc24939fe3d885c667fd5d
[ "MIT" ]
null
null
null
-- Create user for vault service with only necessary rights -- Prefix r_ means that it is a role CREATE ROLE r_vault WITH NOSUPERUSER NOCREATEROLE NOCREATEDB NOREPLICATION LOGIN CONNECTION LIMIT -1 ENCRYPTED PASSWORD 's3cr3TT'; -- Create database for vault CREATE DATABASE vault_db ENCODING 'utf-8' LC_COLLATE 'en_US.utf8' OWNER r_vault; -- Use vault_db \c vault_db; -- Create schema for vault service CREATE SCHEMA vault AUTHORIZATION r_vault; -- Revoke rights from public schema REVOKE ALL ON SCHEMA public FROM PUBLIC; -- Grant rights on vault schema to r_vault GRANT USAGE ON SCHEMA vault TO r_vault; -- Create tables CREATE TABLE vault.kv_store ( parent_path TEXT COLLATE "C" NOT NULL, path TEXT COLLATE "C", key TEXT COLLATE "C", value BYTEA, CONSTRAINT pkey PRIMARY KEY (path, key) ); ALTER TABLE vault.kv_store OWNER TO r_vault; CREATE INDEX parent_path_idx ON vault.kv_store (parent_path); CREATE TABLE vault.ha_locks ( ha_key TEXT COLLATE "C" NOT NULL, ha_identity TEXT COLLATE "C" NOT NULL, ha_value TEXT COLLATE "C", valid_until TIMESTAMP WITH TIME ZONE NOT NULL, CONSTRAINT ha_key PRIMARY KEY (ha_key) ); ALTER TABLE vault.ha_locks OWNER TO r_vault;
35.228571
130
0.743715
d00b347f7e729684f05a2583a635f309c2430500
3,857
swift
Swift
Sources/App/Parsing/Partials/AnonymousConstraint.swift
blueantcorp/wtfautolayout
b7504625d36d86243cc2f880f4b1aec7c7461c9e
[ "MIT" ]
1,040
2017-08-20T21:33:19.000Z
2022-03-22T19:00:32.000Z
Sources/App/Parsing/Partials/AnonymousConstraint.swift
blueantcorp/wtfautolayout
b7504625d36d86243cc2f880f4b1aec7c7461c9e
[ "MIT" ]
23
2017-08-28T07:48:23.000Z
2021-05-08T21:40:15.000Z
Sources/App/Parsing/Partials/AnonymousConstraint.swift
blueantcorp/wtfautolayout
b7504625d36d86243cc2f880f4b1aec7c7461c9e
[ "MIT" ]
25
2017-08-25T23:37:17.000Z
2021-12-21T21:58:53.000Z
import Foundation struct AnonymousConstraint { let first: LayoutItemAttribute let second: LayoutItemAttribute? let relation: Constraint.Relation let constant: Constant let multiplier: Multiplier } extension AnonymousConstraint { init(first: (partialInstance: PartialInstance, attribute: Attribute), relation: Constraint.Relation, multiplier: Multiplier, second: (partialInstance: PartialInstance, attribute: Attribute)?, constant: Constant, names: [String:Instance]) throws { let instance1 = try first.partialInstance.getInstance(names: names) self.init( first: LayoutItemAttribute(layoutItem: instance1, attribute: first.attribute), second: try second.map { LayoutItemAttribute(layoutItem: try $0.partialInstance.getInstance(names: names), attribute: $0.attribute) }, relation: relation, constant: constant, multiplier: multiplier ) } init(axis: Attribute.Axis, partialInstance2: PartialInstance, comparison: (relation: Constraint.Relation, amount: Double), partialInstance1: PartialInstance, names: [String:Instance]) throws { let instance1 = try partialInstance1.getInstance(names: names) let instance2 = try partialInstance2.getInstance(names: names) let pinpoints: (Attribute.PinPoint, Attribute.PinPoint) = { switch (partialInstance1, partialInstance2) { case (.superview, _): return (.end, .end) case (_, .superview): return (.start, .start) default: return (.start, .end) } }() let attribute1 = try Attribute(axis: axis, pinPoint: pinpoints.0) let attribute2 = try Attribute(axis: axis, pinPoint: pinpoints.1) self.init(first: LayoutItemAttribute(layoutItem: instance1, attribute: attribute1), second: LayoutItemAttribute(layoutItem: instance2, attribute: attribute2), relation: comparison.relation, constant: Constant(comparison.amount), multiplier: Multiplier()) } init(axis: Attribute.Axis, partialInstance: PartialInstance, comparison: (relation: Constraint.Relation, amount: Double), names: [String:Instance]) throws { let instance = try partialInstance.getInstance(names: names) let attribute = try Attribute(axis: axis, pinPoint: .extent) let first = LayoutItemAttribute(layoutItem: instance, attribute: attribute) self.init( first: first, second: nil, relation: comparison.relation, constant: Constant(comparison.amount), multiplier: Multiplier() ) } } extension AnonymousConstraint { func deanonymized(instance: Instance, isFromAutoresizingMask: Bool) -> Constraint { let origin: Constraint.Origin if isFromAutoresizingMask { origin = .autoresizingMask } else if let identifier = instance.identifier, identifier.hasPrefix("UIView-Encapsulated-Layout") { origin = .encapsulatedLayout } else if let identifier = instance.identifier, identifier.hasPrefix("UISV") { origin = .stackView } else { origin = .user } return Constraint( identity: instance, first: first, second: second, relation: relation, constant: constant, multiplier: multiplier, origin: origin ) } }
38.57
250
0.591392
f841b94a1f667630097fe667b7ecd4adae7b38c6
6,299
swift
Swift
TooDoo/View Controllers/Settings/Look & Feel/App Icon/AppIconSettingsTableViewController.swift
jriosdev/TooDoo
087afa4c43afa895c9a3da4423be61d0190f9f00
[ "Apache-2.0" ]
1
2018-04-25T04:29:40.000Z
2018-04-25T04:29:40.000Z
TooDoo/View Controllers/Settings/Look & Feel/App Icon/AppIconSettingsTableViewController.swift
jriosdev/TooDoo
087afa4c43afa895c9a3da4423be61d0190f9f00
[ "Apache-2.0" ]
null
null
null
TooDoo/View Controllers/Settings/Look & Feel/App Icon/AppIconSettingsTableViewController.swift
jriosdev/TooDoo
087afa4c43afa895c9a3da4423be61d0190f9f00
[ "Apache-2.0" ]
1
2019-04-08T03:57:12.000Z
2019-04-08T03:57:12.000Z
// // AppIconSettingsTableViewController.swift // TooDoo // // Created by Cali Castle on 12/6/17. // Copyright © 2017 Cali Castle . All rights reserved. // import UIKit import ViewAnimator import DeckTransition final class AppIconSettingsTableViewController: SettingTableViewController, CALayerDelegate { // MARK: - Interface Builder Outlets. @IBOutlet var iconChangeWithThemeSwitch: UISwitch! @IBOutlet var cellLabels: [UILabel]! @IBOutlet var appIconsCollectionView: UICollectionView! @IBOutlet var collectionViewModel: AppIconsCollectionViewModel! // MARK: - Properties /// Gradient mask for color collection view. private lazy var gradientMaskForIcons: CAGradientLayer = { let gradientMask = CAGradientLayer() gradientMask.colors = [UIColor.black.cgColor, UIColor.clear.cgColor] gradientMask.locations = [0.78, 1] gradientMask.startPoint = CGPoint(x: 0, y: 0.5) gradientMask.endPoint = CGPoint(x: 1, y: 0.5) gradientMask.delegate = self return gradientMask }() /// Helper for app icon changer private var canChangeAppIcon: Bool = true { didSet { if canChangeAppIcon != oldValue, !canChangeAppIcon { DispatchQueue.main.async { if #available(iOS 11.0, *) { self.tableView.performBatchUpdates({ self.tableView.deleteSections(IndexSet(integer: 0), with: .none) }, completion: nil) } else { // Fallback on earlier versions self.tableView.deleteSections(IndexSet(integer: 0), with: .none) } } } } } /// Helper for change with theme option. private var changedWithTheme: Bool = false { didSet { if changedWithTheme != oldValue, changedWithTheme { appIconsCollectionView.isUserInteractionEnabled = false appIconsCollectionView.alpha = 0.35 } else { appIconsCollectionView.isUserInteractionEnabled = true appIconsCollectionView.alpha = 1 } } } /// Localize interface. override func localizeInterface() { super.localizeInterface() } // MARK: - View Life Cycle override func viewDidLoad() { super.viewDidLoad() configureSwitches() if #available(iOS 10.3, *) { configureAppIconsCollectionView() } } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() checkAlternateIconSupport() updateGradientFrame() } /// Remove action from gradient layer. func action(for layer: CALayer, forKey event: String) -> CAAction? { return NSNull() } /// Configure switches. fileprivate func configureSwitches() { changedWithTheme = UserDefaultManager.bool(forKey: .AppIconChangedWithTheme) iconChangeWithThemeSwitch.setOn(changedWithTheme, animated: false) } /// Check for alternate icons support. fileprivate func checkAlternateIconSupport() { // Check for alternate icons if #available(iOS 10.3, *) { // Supports alternate icons canChangeAppIcon = UIApplication.shared.supportsAlternateIcons } else { canChangeAppIcon = false } } /// Configure app icons collection view. @available(iOS 10.3, *) fileprivate func configureAppIconsCollectionView() { collectionViewModel.delegate = self appIconsCollectionView.delegate = collectionViewModel appIconsCollectionView.dataSource = collectionViewModel appIconsCollectionView.isScrollEnabled = true appIconsCollectionView.bounces = true appIconsCollectionView.layer.mask = gradientMaskForIcons appIconsCollectionView.contentOffset = CGPoint(x: -10, y: 0) // Add bouncy layout let layout = BouncyLayoutCollectionViewLayout(style: .prominent) layout.scrollDirection = .horizontal appIconsCollectionView.collectionViewLayout = layout appIconsCollectionView.contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 70) // Set selected if let index = collectionViewModel.currentIconIndex() { appIconsCollectionView.selectItem(at: IndexPath(item: index, section: 0), animated: false, scrollPosition: .centeredHorizontally) appIconsCollectionView.scrollToItem(at: IndexPath(item: index, section: 0), at: .centeredHorizontally, animated: false) } } /// Update gradient frame when scrolling. private func updateGradientFrame() { gradientMaskForIcons.frame = CGRect(x: appIconsCollectionView.contentOffset.x, y: 0, width: appIconsCollectionView.bounds.width, height: appIconsCollectionView.bounds.height) } /// Get cell labels. override func getCellLabels() -> [UILabel]? { return cellLabels } /// Change with theme option changed. @IBAction func changeWithThemeChanged(_ sender: UISwitch) { changedWithTheme = sender.isOn // Save setting UserDefaultManager.set(value: sender.isOn, forKey: .AppIconChangedWithTheme) if #available(iOS 10.3, *), sender.isOn { ApplicationManager.changeAppIcon(to: currentThemeIsDark() ? .Primary : .Navy) } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { return canChangeAppIcon ? 2 : 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: return canChangeAppIcon ? 2 : 1 default: return 1 } } } extension AppIconSettingsTableViewController: AppIconsCollectionViewModelDelegate { func appIconsCollectionViewDidScroll(_ scrollView: UIScrollView) { updateGradientFrame() } }
31.813131
182
0.624226
cfac71966a2bae20f4900c8ff4a2f9ca6d3a8ff4
45
sql
SQL
spec/support/database_integration/drop_gpdb.sql
bornio/chorus
dddee70821d9f37bf8fca919ddc41f7204c689dd
[ "Apache-2.0" ]
null
null
null
spec/support/database_integration/drop_gpdb.sql
bornio/chorus
dddee70821d9f37bf8fca919ddc41f7204c689dd
[ "Apache-2.0" ]
null
null
null
spec/support/database_integration/drop_gpdb.sql
bornio/chorus
dddee70821d9f37bf8fca919ddc41f7204c689dd
[ "Apache-2.0" ]
1
2020-11-11T08:20:09.000Z
2020-11-11T08:20:09.000Z
DROP DATABASE IF EXISTS "gpdb_test_database";
45
45
0.844444
4a0ea3cb8727a96ee21e54d35c0f346360726264
892
cpp
C++
framework_c++/jugimap/jmFont.cpp
Jugilus/jugimapAPI
93fba7827b16169f858f7bd88c87236c5cf27183
[ "MIT" ]
8
2020-11-23T23:34:39.000Z
2022-02-23T12:14:02.000Z
framework_c++/jugimap/jmFont.cpp
Jugilus/jugimapAPI
93fba7827b16169f858f7bd88c87236c5cf27183
[ "MIT" ]
null
null
null
framework_c++/jugimap/jmFont.cpp
Jugilus/jugimapAPI
93fba7827b16169f858f7bd88c87236c5cf27183
[ "MIT" ]
3
2019-12-19T13:44:43.000Z
2020-05-15T01:02:10.000Z
#include "../utf8cpp/utf8.h" #include "jmSprites.h" #include "jmFont.h" namespace jugimap { std::string Font::pathPrefix; std::string Font::textForHeight = "ABCXYZgqj"; FontsLibrary::~FontsLibrary() { DeleteData(); } void FontsLibrary::DeleteData() { for(auto f : fonts){ delete f.second; } fonts.clear(); } Font* FontsLibrary::Find(const std::string &_name) { for(auto f : fonts){ if(f.first == _name){ return f.second; } } if(fonts.empty()==false){ return fonts.front().second; } return nullptr;; } Font* FontsLibrary::At(int _index) { if(_index>=0 && _index<fonts.size()){ return fonts[_index].second; } if(fonts.empty()==false){ return fonts.front().second; } return nullptr; } //std::vector<Font*>fontLibrary; FontsLibrary fontLibrary; }
11.736842
50
0.586323
05e3c4ef4a70578a808fb0433cf0d38a2a393389
51,505
html
HTML
pages/m-1.html
yosevukilonzo/etymonline
f4c57566c581599642cfbf96853211e513fc615b
[ "MIT" ]
2
2018-11-05T05:29:53.000Z
2019-03-13T01:47:49.000Z
pages/m-1.html
yosevukilonzo/etymonline
f4c57566c581599642cfbf96853211e513fc615b
[ "MIT" ]
null
null
null
pages/m-1.html
yosevukilonzo/etymonline
f4c57566c581599642cfbf96853211e513fc615b
[ "MIT" ]
null
null
null
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>Online Etymology Dictionary</title> <meta name="msApplication-ID" content="LongHairSoftwareLLC.EtymOnline" /> <meta name="msApplication-PackageFamilyName" content="LongHairSoftwareLLC.EtymOnline_p4n214xp2cs4e" /> <link rel="stylesheet" type="text/css" media="all" href="http://www.etymonline.com/style.css" /> <script type="text/javascript" src="http://www.etymonline.com/resources/js/functions.js"></script> <meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1" /> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-26425972-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </head> <body onload="focus_on_initial_element_if_any(0);"> <div id="container"> <div id="navigation"> <div id="logo"> <a href="http://www.etymonline.com/index.php" title="The Online Etymology Dictionary"> <img src="http://www.etymonline.com/graphics/header.jpg" width="450" height="160" alt="The Online Etymology Dictionary" title="The Online Etymology Dictionary" /> </a> </div> <!-- LOGO --> <form action="http://www.etymonline.com/index.php" method="get"> <input type="hidden" name="allowed_in_frame" value="0"> <div id="search"> Search: <input type="text" name="search" value="" size="40" maxlength="255" class="initial_focus"/> <!-- <select name="searchmode" size="1"> <option value="none" selected="selected">Search Mode</option> <option value="nl">Natural Language</option> <option value="term">Find single term</option> <option value="or">Find any term</option> <option value="phrase">Find exact phrase</option> </select> --> <input type="submit" value="OK" /> </div> <!-- SEARCH --> </form> <div id="browse"> <ul> <li><a href="http://www.etymonline.com/index.php?l=a&allowed_in_frame=0">A</a></li> <li><a href="http://www.etymonline.com/index.php?l=b&allowed_in_frame=0">B</a></li> <li><a href="http://www.etymonline.com/index.php?l=c&allowed_in_frame=0">C</a></li> <li><a href="http://www.etymonline.com/index.php?l=d&allowed_in_frame=0">D</a></li> <li><a href="http://www.etymonline.com/index.php?l=e&allowed_in_frame=0">E</a></li> <li><a href="http://www.etymonline.com/index.php?l=f&allowed_in_frame=0">F</a></li> <li><a href="http://www.etymonline.com/index.php?l=g&allowed_in_frame=0">G</a></li> <li><a href="http://www.etymonline.com/index.php?l=h&allowed_in_frame=0">H</a></li> <li><a href="http://www.etymonline.com/index.php?l=i&allowed_in_frame=0">I</a></li> <li><a href="http://www.etymonline.com/index.php?l=j&allowed_in_frame=0">J</a></li> <li><a href="http://www.etymonline.com/index.php?l=k&allowed_in_frame=0">K</a></li> <li><a href="http://www.etymonline.com/index.php?l=l&allowed_in_frame=0">L</a></li> <li><a href="http://www.etymonline.com/index.php?l=m&allowed_in_frame=0">M</a></li> <li><a href="http://www.etymonline.com/index.php?l=n&allowed_in_frame=0">N</a></li> <li><a href="http://www.etymonline.com/index.php?l=o&allowed_in_frame=0">O</a></li> <li><a href="http://www.etymonline.com/index.php?l=p&allowed_in_frame=0">P</a></li> <li><a href="http://www.etymonline.com/index.php?l=q&allowed_in_frame=0">Q</a></li> <li><a href="http://www.etymonline.com/index.php?l=r&allowed_in_frame=0">R</a></li> <li><a href="http://www.etymonline.com/index.php?l=s&allowed_in_frame=0">S</a></li> <li><a href="http://www.etymonline.com/index.php?l=t&allowed_in_frame=0">T</a></li> <li><a href="http://www.etymonline.com/index.php?l=u&allowed_in_frame=0">U</a></li> <li><a href="http://www.etymonline.com/index.php?l=v&allowed_in_frame=0">V</a></li> <li><a href="http://www.etymonline.com/index.php?l=w&allowed_in_frame=0">W</a></li> <li><a href="http://www.etymonline.com/index.php?l=x&allowed_in_frame=0">X</a></li> <li><a href="http://www.etymonline.com/index.php?l=y&allowed_in_frame=0">Y</a></li> <li><a href="http://www.etymonline.com/index.php?l=z&allowed_in_frame=0">Z</a></li> </ul> </div> <!-- BROWSE --> </div> <!-- NAVIGATION --> <div id="dictionary"> <div class="paging"> <ul> <li><a href="/index.php?l=m&amp;p=0&allowed_in_frame=0">1</a></li> <li><a class="current" href="/index.php?l=m&amp;p=1&allowed_in_frame=0">2</a></li> <li><a href="/index.php?l=m&amp;p=2&allowed_in_frame=0">3</a></li> <li><a href="/index.php?l=m&amp;p=3&allowed_in_frame=0">4</a></li> <li><a href="/index.php?l=m&amp;p=4&allowed_in_frame=0">5</a></li> <li><a href="/index.php?l=m&amp;p=5&allowed_in_frame=0">6</a></li> <li><a href="/index.php?l=m&amp;p=6&allowed_in_frame=0">7</a></li> <li><a href="/index.php?l=m&amp;p=7&allowed_in_frame=0">8</a></li> <li><a href="/index.php?l=m&amp;p=8&allowed_in_frame=0">9</a></li> <li><a href="/index.php?l=m&amp;p=9&allowed_in_frame=0">10</a></li> <li><a href="/index.php?l=m&amp;p=10&allowed_in_frame=0">11</a></li> <li><a href="/index.php?l=m&amp;p=11&allowed_in_frame=0">12</a></li> <li><a href="/index.php?l=m&amp;p=12&allowed_in_frame=0">13</a></li> <li><a href="/index.php?l=m&amp;p=13&allowed_in_frame=0">14</a></li> <li><a href="/index.php?l=m&amp;p=14&allowed_in_frame=0">15</a></li> <li><a href="/index.php?l=m&amp;p=15&allowed_in_frame=0">16</a></li> <li><a href="/index.php?l=m&amp;p=16&allowed_in_frame=0">17</a></li> <li><a href="/index.php?l=m&amp;p=17&allowed_in_frame=0">18</a></li> <li><a href="/index.php?l=m&amp;p=18&allowed_in_frame=0">19</a></li> <li><a href="/index.php?l=m&amp;p=19&allowed_in_frame=0">20</a></li> <li><a href="/index.php?l=m&amp;p=20&allowed_in_frame=0">21</a></li> <li><a href="/index.php?l=m&amp;p=21&allowed_in_frame=0">22</a></li> <li><a href="/index.php?l=m&amp;p=22&allowed_in_frame=0">23</a></li> <li><a href="/index.php?l=m&amp;p=23&allowed_in_frame=0">24</a></li> <li><a href="/index.php?l=m&amp;p=24&allowed_in_frame=0">25</a></li> <li><a href="/index.php?l=m&amp;p=25&allowed_in_frame=0">26</a></li> <li><a href="/index.php?l=m&amp;p=26&allowed_in_frame=0">27</a></li> <li><a href="/index.php?l=m&amp;p=27&allowed_in_frame=0">28</a></li> <li><a href="/index.php?l=m&amp;p=28&allowed_in_frame=0">29</a></li> <li><a href="/index.php?l=m&amp;p=29&allowed_in_frame=0">30</a></li> <li><a href="/index.php?l=m&amp;p=30&allowed_in_frame=0">31</a></li> <li><a href="/index.php?l=m&amp;p=31&allowed_in_frame=0">32</a></li> <li><a href="/index.php?l=m&amp;p=32&allowed_in_frame=0">33</a></li> <li><a href="/index.php?l=m&amp;p=33&allowed_in_frame=0">34</a></li> <li><a href="/index.php?l=m&amp;p=34&allowed_in_frame=0">35</a></li> <li><a href="/index.php?l=m&amp;p=35&allowed_in_frame=0">36</a></li> <li><a href="/index.php?l=m&amp;p=36&allowed_in_frame=0">37</a></li> <li><a href="/index.php?l=m&amp;p=37&allowed_in_frame=0">38</a></li> <li><a href="/index.php?l=m&amp;p=38&allowed_in_frame=0">39</a></li> <li><a href="/index.php?l=m&amp;p=39&allowed_in_frame=0">40</a></li> <li><a href="/index.php?l=m&amp;p=40&allowed_in_frame=0">41</a></li> <li><a href="/index.php?l=m&amp;p=41&allowed_in_frame=0">42</a></li> <li><a href="/index.php?l=m&amp;p=42&allowed_in_frame=0">43</a></li> <li><a href="/index.php?l=m&amp;p=43&allowed_in_frame=0">44</a></li> <li><a href="/index.php?l=m&amp;p=44&allowed_in_frame=0">45</a></li> <li><a href="/index.php?l=m&amp;p=45&allowed_in_frame=0">46</a></li> <li><a href="/index.php?l=m&amp;p=46&allowed_in_frame=0">47</a></li> <li><a href="/index.php?l=m&amp;p=47&allowed_in_frame=0">48</a></li> <li><a href="/index.php?l=m&amp;p=48&allowed_in_frame=0">49</a></li> <li><a href="/index.php?l=m&amp;p=49&allowed_in_frame=0">50</a></li> <li><a href="/index.php?l=m&amp;p=50&allowed_in_frame=0">51</a></li> <li><a href="/index.php?l=m&amp;p=51&allowed_in_frame=0">52</a></li> <li><a href="/index.php?l=m&amp;p=52&allowed_in_frame=0">53</a></li> <li><a href="/index.php?l=m&amp;p=53&allowed_in_frame=0">54</a></li> <li><a href="/index.php?l=m&amp;p=54&allowed_in_frame=0">55</a></li> <li><a href="/index.php?l=m&amp;p=55&allowed_in_frame=0">56</a></li> </ul> </div> <!-- PAGING --> <dl> <dt class="highlight"><a href="/index.php?term=machree&allowed_in_frame=0">machree</a> <a href="http://dictionary.reference.com/search?q=machree" class="dictionary" title="Look up machree at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up machree at Dictionary.com" title="Look up machree at Dictionary.com" /></a></dt> <dd class="highlight">Irish expression, 1829, from Irish-Gaelic <span class="foreign">mo chroidhe</span> "(of) my heart," hence "my dear!"</dd> <dt><a href="/index.php?term=Machu+Picchu&allowed_in_frame=0">Machu Picchu</a> <a href="http://dictionary.reference.com/search?q=Machu Picchu" class="dictionary" title="Look up Machu Picchu at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up Machu Picchu at Dictionary.com" title="Look up Machu Picchu at Dictionary.com" /></a></dt> <dd>from Quechua (Inca) <span class="foreign">machu</span> "old man" + <span class="foreign">pikchu</span> "peak."</dd> <dt class="highlight"><a href="/index.php?term=Mack&allowed_in_frame=0">Mack</a> <a href="http://dictionary.reference.com/search?q=Mack" class="dictionary" title="Look up Mack at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up Mack at Dictionary.com" title="Look up Mack at Dictionary.com" /></a></dt> <dd class="highlight">proprietary name for a brand of heavy automobile trucks, named for brothers John M., Augustus F., and William C. <span class="foreign">Mack</span>, who established Mack Brothers Company, N.Y., N.Y., in 1902. Their trucks formally known as "Mack Trucks" from 1910.</dd> <dt><a href="/index.php?term=Mackenzie&allowed_in_frame=0">Mackenzie</a> <a href="http://dictionary.reference.com/search?q=Mackenzie" class="dictionary" title="Look up Mackenzie at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up Mackenzie at Dictionary.com" title="Look up Mackenzie at Dictionary.com" /></a></dt> <dd>river in Canada, named for Scottish fur trader and explorer Sir Alexander <span class="foreign">Mackenzie</span> (1764-1820) who discovered and explored it 1789.</dd> <dt class="highlight"><a href="/index.php?term=mackerel&allowed_in_frame=0">mackerel (n.)</a> <a href="http://dictionary.reference.com/search?q=mackerel" class="dictionary" title="Look up mackerel at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up mackerel at Dictionary.com" title="Look up mackerel at Dictionary.com" /></a></dt> <dd class="highlight">edible fish, c. 1300, from Old French <span class="foreign">maquerel</span> "mackerel" (Modern French <span class="foreign">maquereau</span>), of unknown origin but apparently identical with Old French <span class="foreign">maquerel</span> "pimp, procurer, broker, agent, intermediary," a word from a Germanic source (compare Middle Dutch <span class="foreign">makelaer</span> "broker," from Old Frisian <span class="foreign">mek</span> "marriage," from <span class="foreign">maken</span> "to make"). The connection is obscure, but medieval people had imaginative notions about the erotic habits of beasts. The fish approach the shore in shoals in summertime to spawn. Exclamation <span class="foreign">holy mackerel</span> is attested from 1876.</dd> <dt><a href="/index.php?term=Mackinaw&allowed_in_frame=0">Mackinaw</a> <a href="http://dictionary.reference.com/search?q=Mackinaw" class="dictionary" title="Look up Mackinaw at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up Mackinaw at Dictionary.com" title="Look up Mackinaw at Dictionary.com" /></a></dt> <dd>type of boat used on the Great Lakes, 1812, from <span class="foreign">Mackinac</span>, name of a port and island in Michigan, from Ojibway (Algonquian) <span class="foreign">mitchimakinak</span> "many turtles," from <span class="foreign">mishiin-</span> "be many" + <span class="foreign">mikinaak</span> "snapping turtle." As a type of heavy blanket given to the Indians by the U.S. government, it is attested from 1822.</dd> <dt class="highlight"><a href="/index.php?term=mackintosh&allowed_in_frame=0">mackintosh (n.)</a> <a href="http://dictionary.reference.com/search?q=mackintosh" class="dictionary" title="Look up mackintosh at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up mackintosh at Dictionary.com" title="Look up mackintosh at Dictionary.com" /></a></dt> <dd class="highlight">waterproof outer coat, 1836, named for Charles <span class="foreign">Macintosh</span> (1766-1843), inventor of a waterproofing process (patent #4804, June 17, 1823). The surname is from Gaelic <span class="foreign">Mac an toisich</span> "Son of the chieftain."</dd> <dt><a href="/index.php?term=macrame&allowed_in_frame=0">macrame (n.)</a> <a href="http://dictionary.reference.com/search?q=macrame" class="dictionary" title="Look up macrame at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up macrame at Dictionary.com" title="Look up macrame at Dictionary.com" /></a></dt> <dd>1869, from French <span class="foreign">macram&eacute;</span>, from Turkish <span class="foreign">maqrama</span> "towel, napkin," from Arabic <span class="foreign">miqramah</span> "embroidered veil."</dd> <dt class="highlight"><a href="/index.php?term=macro&allowed_in_frame=0">macro (n.)</a> <a href="http://dictionary.reference.com/search?q=macro" class="dictionary" title="Look up macro at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up macro at Dictionary.com" title="Look up macro at Dictionary.com" /></a></dt> <dd class="highlight">1959 in computing sense, shortened from <a href="/index.php?term=macro-instruction&allowed_in_frame=0" class="crossreference">macro-instruction</a>.</dd> <dt><a href="/index.php?term=macro-&allowed_in_frame=0">macro-</a> <a href="http://dictionary.reference.com/search?q=macro-" class="dictionary" title="Look up macro- at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up macro- at Dictionary.com" title="Look up macro- at Dictionary.com" /></a></dt> <dd>word-forming element meaning "long, abnormally large, on a large scale," taken into English via Middle French and Medieval Latin from Greek <span class="foreign">makros</span> "long, large," from PIE root <span class="foreign">*mak-</span> "long, thin" (source also of Latin <span class="foreign">macer</span> "lean, thin;" Old Norse <span class="foreign">magr</span>, Old English <span class="foreign">m&aelig;ger</span> "lean, thin;" Greek <span class="foreign">mekos</span> "length").</dd> <dt class="highlight"><a href="/index.php?term=macrobiotic&allowed_in_frame=0">macrobiotic (adj.)</a> <a href="http://dictionary.reference.com/search?q=macrobiotic" class="dictionary" title="Look up macrobiotic at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up macrobiotic at Dictionary.com" title="Look up macrobiotic at Dictionary.com" /></a></dt> <dd class="highlight">also <span class="foreign">macro-biotic</span>, "inclined to prolong life," 1797, from Greek <span class="foreign">makrobiotikos</span> "long-lived," from <span class="foreign">makros</span> "long" (see <a href="/index.php?term=macro&allowed_in_frame=0" class="crossreference">macro</a>-) + <span class="foreign">bios</span> "life" (see <a href="/index.php?term=bio-&allowed_in_frame=0" class="crossreference">bio-</a>). The specific reference to a Zen Buddhist dietary system dates from 1936.</dd> <dt><a href="/index.php?term=macrocephalic&allowed_in_frame=0">macrocephalic (adj.)</a> <a href="http://dictionary.reference.com/search?q=macrocephalic" class="dictionary" title="Look up macrocephalic at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up macrocephalic at Dictionary.com" title="Look up macrocephalic at Dictionary.com" /></a></dt> <dd>1851, from Greek <span class="foreign">makrokephalos</span>; see <a href="/index.php?term=macro-&allowed_in_frame=0" class="crossreference">macro-</a>. Second element is from Greek <span class="foreign">kephale</span> "head" (see <a href="/index.php?term=cephalo-&allowed_in_frame=0" class="crossreference">cephalo-</a>). Related: <span class="foreign">Macrocephalous</span>; <span class="foreign">macrocephaly</span>.</dd> <dt class="highlight"><a href="/index.php?term=macrocosm&allowed_in_frame=0">macrocosm (n.)</a> <a href="http://dictionary.reference.com/search?q=macrocosm" class="dictionary" title="Look up macrocosm at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up macrocosm at Dictionary.com" title="Look up macrocosm at Dictionary.com" /></a></dt> <dd class="highlight">c. 1600, "the great world" (the universe, as distinct from the "little world" of man), from Old French <span class="foreign">macrocosme</span> (c. 1300) and directly from Medieval Latin <span class="foreign">macrocosmus</span>, from Greek <span class="foreign">makros</span> "large, long" (see <a href="/index.php?term=macro-&allowed_in_frame=0" class="crossreference">macro-</a>) + <span class="foreign">kosmos</span> (see <a href="/index.php?term=cosmos&allowed_in_frame=0" class="crossreference">cosmos</a>).</dd> <dt><a href="/index.php?term=macroeconomic&allowed_in_frame=0">macroeconomic (adj.)</a> <a href="http://dictionary.reference.com/search?q=macroeconomic" class="dictionary" title="Look up macroeconomic at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up macroeconomic at Dictionary.com" title="Look up macroeconomic at Dictionary.com" /></a></dt> <dd>also <span class="foreign">macro-economic</span>, 1938, from <a href="/index.php?term=macro-&allowed_in_frame=0" class="crossreference">macro-</a> + <a href="/index.php?term=economic&allowed_in_frame=0" class="crossreference">economic</a>.</dd> <dt class="highlight"><a href="/index.php?term=macroeconomics&allowed_in_frame=0">macroeconomics (n.)</a> <a href="http://dictionary.reference.com/search?q=macroeconomics" class="dictionary" title="Look up macroeconomics at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up macroeconomics at Dictionary.com" title="Look up macroeconomics at Dictionary.com" /></a></dt> <dd class="highlight">also <span class="foreign">macro-economics</span>, 1948, from <a href="/index.php?term=macroeconomic&allowed_in_frame=0" class="crossreference">macroeconomic</a>; also see <a href="/index.php?term=-ics&allowed_in_frame=0" class="crossreference">-ics</a>.</dd> <dt><a href="/index.php?term=macroinstruction&allowed_in_frame=0">macroinstruction (n.)</a> <a href="http://dictionary.reference.com/search?q=macroinstruction" class="dictionary" title="Look up macroinstruction at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up macroinstruction at Dictionary.com" title="Look up macroinstruction at Dictionary.com" /></a></dt> <dd>also <span class="foreign">macro-instruction</span>, 1959, from <a href="/index.php?term=macro-&allowed_in_frame=0" class="crossreference">macro-</a> + <a href="/index.php?term=instruction&allowed_in_frame=0" class="crossreference">instruction</a>.</dd> <dt class="highlight"><a href="/index.php?term=macromolecule&allowed_in_frame=0">macromolecule</a> <a href="http://dictionary.reference.com/search?q=macromolecule" class="dictionary" title="Look up macromolecule at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up macromolecule at Dictionary.com" title="Look up macromolecule at Dictionary.com" /></a></dt> <dd class="highlight">1886, from <a href="/index.php?term=macro-&allowed_in_frame=0" class="crossreference">macro-</a> + <a href="/index.php?term=molecule&allowed_in_frame=0" class="crossreference">molecule</a>. Apparently coined in "On Macro-molecules, with the Determinations of the Form of Some of Them," by Anglo-Irish physicist G. Johnstone Stoney (1826&ndash;1911). Originally of crystals. Meaning "molecule composed of many atoms" is from 1935, from German <span class="foreign">makromolekul</span> (1922). Related: <span class="foreign">Macromolecular</span>.</dd> <dt><a href="/index.php?term=macron&allowed_in_frame=0">macron (n.)</a> <a href="http://dictionary.reference.com/search?q=macron" class="dictionary" title="Look up macron at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up macron at Dictionary.com" title="Look up macron at Dictionary.com" /></a></dt> <dd>"short horizontal line placed over a vowel to indicate length," 1827, from Greek <span class="foreign">makron</span>, neuter of <span class="foreign">makros</span> "long" (see <a href="/index.php?term=macro&allowed_in_frame=0" class="crossreference">macro</a>-).</dd> <dt class="highlight"><a href="/index.php?term=macropaedia&allowed_in_frame=0">macropaedia (n.)</a> <a href="http://dictionary.reference.com/search?q=macropaedia" class="dictionary" title="Look up macropaedia at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up macropaedia at Dictionary.com" title="Look up macropaedia at Dictionary.com" /></a></dt> <dd class="highlight">1974, introduced with the 15th edition of the "<span class="foreign">Encyclopaedia Britannica</span>," from <a href="/index.php?term=macro-&allowed_in_frame=0" class="crossreference">macro-</a> + ending from <a href="/index.php?term=encyclopaedia&allowed_in_frame=0" class="crossreference">encyclopaedia</a>.</dd> <dt><a href="/index.php?term=macrophage&allowed_in_frame=0">macrophage (n.)</a> <a href="http://dictionary.reference.com/search?q=macrophage" class="dictionary" title="Look up macrophage at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up macrophage at Dictionary.com" title="Look up macrophage at Dictionary.com" /></a></dt> <dd>1890, from <a href="/index.php?term=macro-&allowed_in_frame=0" class="crossreference">macro-</a> + <a href="/index.php?term=-phage&allowed_in_frame=0" class="crossreference">-phage</a>.</dd> <dt class="highlight"><a href="/index.php?term=macrophotography&allowed_in_frame=0">macrophotography (n.)</a> <a href="http://dictionary.reference.com/search?q=macrophotography" class="dictionary" title="Look up macrophotography at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up macrophotography at Dictionary.com" title="Look up macrophotography at Dictionary.com" /></a></dt> <dd class="highlight">1863, from <a href="/index.php?term=macro-&allowed_in_frame=0" class="crossreference">macro-</a> + <a href="/index.php?term=photography&allowed_in_frame=0" class="crossreference">photography</a>.</dd> <dt><a href="/index.php?term=macroscopic&allowed_in_frame=0">macroscopic (adj.)</a> <a href="http://dictionary.reference.com/search?q=macroscopic" class="dictionary" title="Look up macroscopic at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up macroscopic at Dictionary.com" title="Look up macroscopic at Dictionary.com" /></a></dt> <dd>1872, from <a href="/index.php?term=macro-&allowed_in_frame=0" class="crossreference">macro-</a> + ending from <a href="/index.php?term=microscopic&allowed_in_frame=0" class="crossreference">microscopic</a>. Related: <span class="foreign">Macroscopical</span>; <span class="foreign">macroscopically</span>.</dd> <dt class="highlight"><a href="/index.php?term=macrospore&allowed_in_frame=0">macrospore (n.)</a> <a href="http://dictionary.reference.com/search?q=macrospore" class="dictionary" title="Look up macrospore at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up macrospore at Dictionary.com" title="Look up macrospore at Dictionary.com" /></a></dt> <dd class="highlight">1859, from <a href="/index.php?term=macro-&allowed_in_frame=0" class="crossreference">macro-</a> + <a href="/index.php?term=spore&allowed_in_frame=0" class="crossreference">spore</a> (n.).</dd> <dt><a href="/index.php?term=macula&allowed_in_frame=0">macula (n.)</a> <a href="http://dictionary.reference.com/search?q=macula" class="dictionary" title="Look up macula at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up macula at Dictionary.com" title="Look up macula at Dictionary.com" /></a></dt> <dd>plural <span class="foreign">maculae</span>, from Latin <span class="foreign">macula</span> "spot, stain," used of various spots (sunspots, markings on minerals, etc.), from Proto-Italic <span class="foreign">*smalto-</span>, of uncertain origin. Especially the <span class="foreign">macula lutea</span> in the eye.</dd> <dt class="highlight"><a href="/index.php?term=macular&allowed_in_frame=0">macular (adj.)</a> <a href="http://dictionary.reference.com/search?q=macular" class="dictionary" title="Look up macular at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up macular at Dictionary.com" title="Look up macular at Dictionary.com" /></a></dt> <dd class="highlight">1822, from <a href="/index.php?term=macula&allowed_in_frame=0" class="crossreference">macula</a> + <a href="/index.php?term=-ar&allowed_in_frame=0" class="crossreference">-ar</a>.</dd> <dt><a href="/index.php?term=maculate&allowed_in_frame=0">maculate (adj.)</a> <a href="http://dictionary.reference.com/search?q=maculate" class="dictionary" title="Look up maculate at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up maculate at Dictionary.com" title="Look up maculate at Dictionary.com" /></a></dt> <dd>"spotted," late 15c., from Latin <span class="foreign">maculatus</span>, past participle of <span class="foreign">maculare</span> "to make spotted, to speckle," from <span class="foreign">macula</span> "spot, stain" (see <a href="/index.php?term=macula&allowed_in_frame=0" class="crossreference">macula</a>). Middle English also had <span class="foreign">maculation</span> "sexual defilement, sinning" (late 15c.).</dd> <dt class="highlight"><a href="/index.php?term=maculate&allowed_in_frame=0">maculate (v.)</a> <a href="http://dictionary.reference.com/search?q=maculate" class="dictionary" title="Look up maculate at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up maculate at Dictionary.com" title="Look up maculate at Dictionary.com" /></a></dt> <dd class="highlight">early 15c., from Latin <span class="foreign">maculatus</span>, past participle of <span class="foreign">maculare</span> "to make spotted, to speckle," from <span class="foreign">macula</span> "spot, stain" (see <a href="/index.php?term=macula&allowed_in_frame=0" class="crossreference">macula</a>). Related: <span class="foreign">Maculated</span>; <span class="foreign">maculating</span>.</dd> <dt><a href="/index.php?term=maculation&allowed_in_frame=0">maculation (n.)</a> <a href="http://dictionary.reference.com/search?q=maculation" class="dictionary" title="Look up maculation at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up maculation at Dictionary.com" title="Look up maculation at Dictionary.com" /></a></dt> <dd>mid-15c., from Latin <span class="foreign">maculationem</span> (nominative <span class="foreign">maculatio</span>), noun of action from past participle stem of <span class="foreign">maculare</span> (see <a href="/index.php?term=maculate&allowed_in_frame=0" class="crossreference">maculate</a>).</dd> <dt class="highlight"><a href="/index.php?term=macule&allowed_in_frame=0">macule (n.)</a> <a href="http://dictionary.reference.com/search?q=macule" class="dictionary" title="Look up macule at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up macule at Dictionary.com" title="Look up macule at Dictionary.com" /></a></dt> <dd class="highlight">"blemish, spot," late 15c., from Latin <span class="foreign">macula</span> (see <a href="/index.php?term=macula&allowed_in_frame=0" class="crossreference">macula</a>), perhaps via French <span class="foreign">macule</span>.</dd> <dt><a href="/index.php?term=mad&allowed_in_frame=0">mad (adj.)</a> <a href="http://dictionary.reference.com/search?q=mad" class="dictionary" title="Look up mad at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up mad at Dictionary.com" title="Look up mad at Dictionary.com" /></a></dt> <dd>late 13c., from Old English <span class="foreign">gem&aelig;dde</span> (plural) "out of one's mind" (usually implying also violent excitement), also "foolish, extremely stupid," earlier <span class="foreign">gem&aelig;ded</span> "rendered insane," past participle of a lost verb <span class="foreign">*gem&aelig;dan</span> "to make insane or foolish," from Proto-Germanic <span class="foreign">*ga-maid-jan</span>, demonstrative form of <span class="foreign">*ga-maid-az</span> "changed (for the worse), abnormal" (source also of Old Saxon <span class="foreign">gimed</span> "foolish," Old High German <span class="foreign">gimeit</span> "foolish, vain, boastful," Gothic <span class="foreign">gamai&thorn;s</span> "crippled, wounded," Old Norse <span class="foreign">mei&eth;a</span> "to hurt, maim"), from intensive prefix <span class="foreign">*ga-</span> + PIE <span class="foreign">*moito-</span>, past participle of root <span class="foreign">*mei-</span> (1) "to change" (source also of Latin <span class="foreign">mutare</span> "to change," <span class="foreign">mutuus</span> "done in exchange," <span class="foreign">migrare</span> "to change one's place of residence;" see <a href="/index.php?term=mutable&allowed_in_frame=0" class="crossreference">mutable</a>). <BR><BR> Emerged in Middle English to replace the more usual Old English word, <span class="foreign">wod</span> (see <a href="/index.php?term=wood&allowed_in_frame=0" class="crossreference">wood</a> (adj.)). Sense of "beside oneself with excitement or enthusiasm" is from early 14c. Meaning "beside oneself with anger" is attested from early 14c., but deplored by Rev. John Witherspoon (1781) as an Americanism. It now competes in American English with <a href="/index.php?term=angry&allowed_in_frame=0" class="crossreference">angry</a> for this sense. Of animals, "affected with rabies," from late 13c. Phrase <span class="foreign">mad as a March hare</span> is attested from 1520s, via notion of breeding season; <span class="foreign">mad as a hatter</span> is from 1829 as "demented," 1837 as "enraged," according to a modern theory supposedly from erratic behavior caused by prolonged exposure to poison mercuric nitrate, used in making felt hats. For <span class="foreign">mad as a wet hen</span> see <a href="/index.php?term=hen&allowed_in_frame=0" class="crossreference">hen</a>. <span class="foreign">Mad money</span> is attested from 1922; <span class="foreign">mad scientist</span> is from 1891.</dd> <dt class="highlight"><a href="/index.php?term=mad&allowed_in_frame=0">mad (adv.)</a> <a href="http://dictionary.reference.com/search?q=mad" class="dictionary" title="Look up mad at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up mad at Dictionary.com" title="Look up mad at Dictionary.com" /></a></dt> <dd class="highlight">late 14c., from <a href="/index.php?term=mad&allowed_in_frame=0" class="crossreference">mad</a> (adj.).</dd> <dt><a href="/index.php?term=Madagascar&allowed_in_frame=0">Madagascar</a> <a href="http://dictionary.reference.com/search?q=Madagascar" class="dictionary" title="Look up Madagascar at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up Madagascar at Dictionary.com" title="Look up Madagascar at Dictionary.com" /></a></dt> <dd>large island off the east coast of Africa, from <a href="/index.php?term=Mogadishu&allowed_in_frame=0" class="crossreference">Mogadishu</a>, the name of the city in Somalia, due to an error by Marco Polo in reading Arabic, whereby he thought the name was that of the island. There is no indigenous name for the whole island. Related: <span class="foreign">Madagascan</span>.</dd> <dt class="highlight"><a href="/index.php?term=madam&allowed_in_frame=0">madam</a> <a href="http://dictionary.reference.com/search?q=madam" class="dictionary" title="Look up madam at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up madam at Dictionary.com" title="Look up madam at Dictionary.com" /></a></dt> <dd class="highlight">c. 1300, from Old French <span class="foreign">ma dame,</span> literally "my lady," from Latin <span class="foreign">mea domina</span> (compare <a href="/index.php?term=madonna&allowed_in_frame=0" class="crossreference">madonna</a>). Meaning "female owner or manager of a brothel" is first attested 1871.</dd> <dt><a href="/index.php?term=madame&allowed_in_frame=0">madame</a> <a href="http://dictionary.reference.com/search?q=madame" class="dictionary" title="Look up madame at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up madame at Dictionary.com" title="Look up madame at Dictionary.com" /></a></dt> <dd>1590s, see <a href="/index.php?term=madam&allowed_in_frame=0" class="crossreference">madam</a>, which is an earlier borrowing of the same French phrase. Originally a title of respect for a woman of rank, now given to any married woman. OED recommends <span class="foreign">madam</span> as an English title, <span class="foreign">madame</span> in reference to foreign women.</dd> <dt class="highlight"><a href="/index.php?term=madarosis&allowed_in_frame=0">madarosis (n.)</a> <a href="http://dictionary.reference.com/search?q=madarosis" class="dictionary" title="Look up madarosis at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up madarosis at Dictionary.com" title="Look up madarosis at Dictionary.com" /></a></dt> <dd class="highlight">"loss of the eyelashes," 1690s, medical Latin, from Greek <span class="foreign">madarosis</span> "baldness." Related: <span class="foreign">Madarotic</span>.</dd> <dt><a href="/index.php?term=madcap&allowed_in_frame=0">madcap</a> <a href="http://dictionary.reference.com/search?q=madcap" class="dictionary" title="Look up madcap at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up madcap at Dictionary.com" title="Look up madcap at Dictionary.com" /></a></dt> <dd>1580s, noun and adjective, from <a href="/index.php?term=mad&allowed_in_frame=0" class="crossreference">mad</a> (adj.) + <a href="/index.php?term=cap&allowed_in_frame=0" class="crossreference">cap</a>, used here figuratively for "head." Related: <span class="foreign">Madcappery</span>.</dd> <dt class="highlight"><a href="/index.php?term=madden&allowed_in_frame=0">madden (v.)</a> <a href="http://dictionary.reference.com/search?q=madden" class="dictionary" title="Look up madden at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up madden at Dictionary.com" title="Look up madden at Dictionary.com" /></a></dt> <dd class="highlight">"to drive to distraction," 1822; earlier "to be mad" (1735), from <a href="/index.php?term=mad&allowed_in_frame=0" class="crossreference">mad</a> (adj.) + <a href="/index.php?term=-en&allowed_in_frame=0" class="crossreference">-en</a> (1). Related: <span class="foreign">Maddened</span>; <span class="foreign">maddening</span>. The earlier verb was simply <span class="foreign">mad</span> (early 14c., intransitive; late 14c., transitive), from the adjective.</dd> <dt><a href="/index.php?term=maddening&allowed_in_frame=0">maddening (adj.)</a> <a href="http://dictionary.reference.com/search?q=maddening" class="dictionary" title="Look up maddening at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up maddening at Dictionary.com" title="Look up maddening at Dictionary.com" /></a></dt> <dd>1743, from present participle of <a href="/index.php?term=madden&allowed_in_frame=0" class="crossreference">madden</a>. Related: <span class="foreign">Maddeningly</span>. </dd> <dt class="highlight"><a href="/index.php?term=madder&allowed_in_frame=0">madder (n.)</a> <a href="http://dictionary.reference.com/search?q=madder" class="dictionary" title="Look up madder at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up madder at Dictionary.com" title="Look up madder at Dictionary.com" /></a></dt> <dd class="highlight">type of plant (in modern use <span class="foreign">Rubia tinctorum</span>) used for making dyes, Old English <span class="foreign">m&aelig;dere</span>, from PIE <span class="foreign">*modhro-</span> "dye plant" (source also of Old Norse <span class="foreign">ma&eth;ra</span>, Old High German <span class="foreign">matara</span> "madder," Polish <span class="foreign">modry</span>, Czech <span class="foreign">modry</span> "blue").</dd> <dt><a href="/index.php?term=madding&allowed_in_frame=0">madding (adj.)</a> <a href="http://dictionary.reference.com/search?q=madding" class="dictionary" title="Look up madding at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up madding at Dictionary.com" title="Look up madding at Dictionary.com" /></a></dt> <dd>present participle adjective from obsolete verb <span class="foreign">mad</span> "to make insane; to become insane" (see <a href="/index.php?term=madden&allowed_in_frame=0" class="crossreference">madden</a>); now principally in the phrase <span class="foreign">far from the madding crowd</span>, title of a novel by Hardy (1874), who lifted it from a line of Gray's "Elegy" (1749), which seems to echo a line from Drummond of Hawthornden from 1614 ("Farre from the madding Worldling's hoarse discords").</dd> <dt class="highlight"><a href="/index.php?term=maddish&allowed_in_frame=0">maddish (adj.)</a> <a href="http://dictionary.reference.com/search?q=maddish" class="dictionary" title="Look up maddish at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up maddish at Dictionary.com" title="Look up maddish at Dictionary.com" /></a></dt> <dd class="highlight">1570s, from <a href="/index.php?term=mad&allowed_in_frame=0" class="crossreference">mad</a> (adj.) + <a href="/index.php?term=-ish&allowed_in_frame=0" class="crossreference">-ish</a>.</dd> <dt><a href="/index.php?term=made&allowed_in_frame=0">made (adj.)</a> <a href="http://dictionary.reference.com/search?q=made" class="dictionary" title="Look up made at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up made at Dictionary.com" title="Look up made at Dictionary.com" /></a></dt> <dd>late 14c., from Middle English <span class="foreign">maked</span>, from Old English <span class="foreign">macod</span> "made," past participle of <span class="foreign">macian</span> "to make" (see <a href="/index.php?term=make&allowed_in_frame=0" class="crossreference">make</a>). <span class="foreign">Made up</span> "invented" is from 1789; of minds, "settled, decided," from 1873. To be a <span class="foreign">made man</span> is in Marlowe's "Faust" (1590). To <span class="foreign">have it made</span> (1955) is American English colloquial. Grose's dictionary of slang and cant (1785) has for this word what might be the shortest and most cynical definition ever penned: "MADE. Stolen. <span class="foreign">Cant.</span>"</dd> <dt class="highlight"><a href="/index.php?term=Madeira&allowed_in_frame=0">Madeira (n.)</a> <a href="http://dictionary.reference.com/search?q=Madeira" class="dictionary" title="Look up Madeira at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up Madeira at Dictionary.com" title="Look up Madeira at Dictionary.com" /></a></dt> <dd class="highlight">white wine, 1540s, from island of <span class="foreign">Madeira</span> in the Atlantic, from Portuguese <span class="foreign">madeira</span> "wood," because the island formerly was thickly wooded, from Latin <span class="foreign">materia</span> "wood, matter" (see <a href="/index.php?term=matter&allowed_in_frame=0" class="crossreference">matter</a> (n.)).</dd> <dt><a href="/index.php?term=Madeleine&allowed_in_frame=0">Madeleine</a> <a href="http://dictionary.reference.com/search?q=Madeleine" class="dictionary" title="Look up Madeleine at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up Madeleine at Dictionary.com" title="Look up Madeleine at Dictionary.com" /></a></dt> <dd>fem. proper name, variation of <a href="/index.php?term=Madeline&allowed_in_frame=0" class="crossreference">Madeline</a>. The kind of small, rich confection is attested from 1845, said in OED to be named for <span class="foreign">Madeleine</span> Paulmier, 19c. French pastry cook; any use with a sense of "small thing that evokes powerful nostalgia" is due to Proust (1922).</dd> <dt class="highlight"><a href="/index.php?term=Madeline&allowed_in_frame=0">Madeline</a> <a href="http://dictionary.reference.com/search?q=Madeline" class="dictionary" title="Look up Madeline at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up Madeline at Dictionary.com" title="Look up Madeline at Dictionary.com" /></a></dt> <dd class="highlight">fem. proper name, from French <a href="/index.php?term=Magdalene&allowed_in_frame=0" class="crossreference">Magdalene</a> (q.v.). Compare also <a href="/index.php?term=Madeleine&allowed_in_frame=0" class="crossreference">Madeleine</a>.</dd> <dt><a href="/index.php?term=mademoiselle&allowed_in_frame=0">mademoiselle</a> <a href="http://dictionary.reference.com/search?q=mademoiselle" class="dictionary" title="Look up mademoiselle at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up mademoiselle at Dictionary.com" title="Look up mademoiselle at Dictionary.com" /></a></dt> <dd>mid-15c., "unmarried Frenchwoman," from French <span class="foreign">mademoiselle</span> (12c.), from a compound of <span class="foreign">ma dameisele</span> (see <a href="/index.php?term=damsel&allowed_in_frame=0" class="crossreference">damsel</a>), literally "young mistress."</dd> <dt class="highlight"><a href="/index.php?term=Madge&allowed_in_frame=0">Madge</a> <a href="http://dictionary.reference.com/search?q=Madge" class="dictionary" title="Look up Madge at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up Madge at Dictionary.com" title="Look up Madge at Dictionary.com" /></a></dt> <dd class="highlight">pet form of fem. proper name <a href="/index.php?term=Margaret&allowed_in_frame=0" class="crossreference">Margaret</a>. <blockquote> MADGE. The private parts of a woman. [Grose, "Dictionary of the Vulgar Tongue," London, 1785] </blockquote></dd> <dt><a href="/index.php?term=madhouse&allowed_in_frame=0">madhouse (n.)</a> <a href="http://dictionary.reference.com/search?q=madhouse" class="dictionary" title="Look up madhouse at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up madhouse at Dictionary.com" title="Look up madhouse at Dictionary.com" /></a></dt> <dd>1680s, from <a href="/index.php?term=mad&allowed_in_frame=0" class="crossreference">mad</a> + <a href="/index.php?term=house&allowed_in_frame=0" class="crossreference">house</a> (n.). Figurative use by 1919.</dd> <dt class="highlight"><a href="/index.php?term=Madison&allowed_in_frame=0">Madison</a> <a href="http://dictionary.reference.com/search?q=Madison" class="dictionary" title="Look up Madison at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up Madison at Dictionary.com" title="Look up Madison at Dictionary.com" /></a></dt> <dd class="highlight">surname attested from early 15c., probably in many cases a variant of <span class="foreign">Mathieson</span> "son of Matthew," but in some cases perhaps "son of <span class="foreign">Maddy</span>," from the pet form of the fem. proper name <a href="/index.php?term=Maud&allowed_in_frame=0" class="crossreference">Maud</a>. The city in Wisconsin, U.S., was named 1836 for U.S. President James <span class="foreign">Madison</span>, who had died that year. As the name of a popular dance of 1960, its signification is unknown; supposedly it originated in Baltimore.</dd> <dt><a href="/index.php?term=Madison+Avenue&allowed_in_frame=0">Madison Avenue</a> <a href="http://dictionary.reference.com/search?q=Madison Avenue" class="dictionary" title="Look up Madison Avenue at Dictionary.com"><img src="graphics/dictionary.gif" width="16" height="16" alt="Look up Madison Avenue at Dictionary.com" title="Look up Madison Avenue at Dictionary.com" /></a></dt> <dd>"values and business of advertising and public relations," 1954, from the street in Manhattan, laid out c. 1836 and named for U.S. President James <a href="/index.php?term=Madison&allowed_in_frame=0" class="crossreference">Madison</a>. The concentration of advertising agencies there seems to date from the 1940s.</dd> </dl> <div class="paging"> <ul> <li><a href="/index.php?l=m&amp;p=0&allowed_in_frame=0">1</a></li> <li><a class="current" href="/index.php?l=m&amp;p=1&allowed_in_frame=0">2</a></li> <li><a href="/index.php?l=m&amp;p=2&allowed_in_frame=0">3</a></li> <li><a href="/index.php?l=m&amp;p=3&allowed_in_frame=0">4</a></li> <li><a href="/index.php?l=m&amp;p=4&allowed_in_frame=0">5</a></li> <li><a href="/index.php?l=m&amp;p=5&allowed_in_frame=0">6</a></li> <li><a href="/index.php?l=m&amp;p=6&allowed_in_frame=0">7</a></li> <li><a href="/index.php?l=m&amp;p=7&allowed_in_frame=0">8</a></li> <li><a href="/index.php?l=m&amp;p=8&allowed_in_frame=0">9</a></li> <li><a href="/index.php?l=m&amp;p=9&allowed_in_frame=0">10</a></li> <li><a href="/index.php?l=m&amp;p=10&allowed_in_frame=0">11</a></li> <li><a href="/index.php?l=m&amp;p=11&allowed_in_frame=0">12</a></li> <li><a href="/index.php?l=m&amp;p=12&allowed_in_frame=0">13</a></li> <li><a href="/index.php?l=m&amp;p=13&allowed_in_frame=0">14</a></li> <li><a href="/index.php?l=m&amp;p=14&allowed_in_frame=0">15</a></li> <li><a href="/index.php?l=m&amp;p=15&allowed_in_frame=0">16</a></li> <li><a href="/index.php?l=m&amp;p=16&allowed_in_frame=0">17</a></li> <li><a href="/index.php?l=m&amp;p=17&allowed_in_frame=0">18</a></li> <li><a href="/index.php?l=m&amp;p=18&allowed_in_frame=0">19</a></li> <li><a href="/index.php?l=m&amp;p=19&allowed_in_frame=0">20</a></li> <li><a href="/index.php?l=m&amp;p=20&allowed_in_frame=0">21</a></li> <li><a href="/index.php?l=m&amp;p=21&allowed_in_frame=0">22</a></li> <li><a href="/index.php?l=m&amp;p=22&allowed_in_frame=0">23</a></li> <li><a href="/index.php?l=m&amp;p=23&allowed_in_frame=0">24</a></li> <li><a href="/index.php?l=m&amp;p=24&allowed_in_frame=0">25</a></li> <li><a href="/index.php?l=m&amp;p=25&allowed_in_frame=0">26</a></li> <li><a href="/index.php?l=m&amp;p=26&allowed_in_frame=0">27</a></li> <li><a href="/index.php?l=m&amp;p=27&allowed_in_frame=0">28</a></li> <li><a href="/index.php?l=m&amp;p=28&allowed_in_frame=0">29</a></li> <li><a href="/index.php?l=m&amp;p=29&allowed_in_frame=0">30</a></li> <li><a href="/index.php?l=m&amp;p=30&allowed_in_frame=0">31</a></li> <li><a href="/index.php?l=m&amp;p=31&allowed_in_frame=0">32</a></li> <li><a href="/index.php?l=m&amp;p=32&allowed_in_frame=0">33</a></li> <li><a href="/index.php?l=m&amp;p=33&allowed_in_frame=0">34</a></li> <li><a href="/index.php?l=m&amp;p=34&allowed_in_frame=0">35</a></li> <li><a href="/index.php?l=m&amp;p=35&allowed_in_frame=0">36</a></li> <li><a href="/index.php?l=m&amp;p=36&allowed_in_frame=0">37</a></li> <li><a href="/index.php?l=m&amp;p=37&allowed_in_frame=0">38</a></li> <li><a href="/index.php?l=m&amp;p=38&allowed_in_frame=0">39</a></li> <li><a href="/index.php?l=m&amp;p=39&allowed_in_frame=0">40</a></li> <li><a href="/index.php?l=m&amp;p=40&allowed_in_frame=0">41</a></li> <li><a href="/index.php?l=m&amp;p=41&allowed_in_frame=0">42</a></li> <li><a href="/index.php?l=m&amp;p=42&allowed_in_frame=0">43</a></li> <li><a href="/index.php?l=m&amp;p=43&allowed_in_frame=0">44</a></li> <li><a href="/index.php?l=m&amp;p=44&allowed_in_frame=0">45</a></li> <li><a href="/index.php?l=m&amp;p=45&allowed_in_frame=0">46</a></li> <li><a href="/index.php?l=m&amp;p=46&allowed_in_frame=0">47</a></li> <li><a href="/index.php?l=m&amp;p=47&allowed_in_frame=0">48</a></li> <li><a href="/index.php?l=m&amp;p=48&allowed_in_frame=0">49</a></li> <li><a href="/index.php?l=m&amp;p=49&allowed_in_frame=0">50</a></li> <li><a href="/index.php?l=m&amp;p=50&allowed_in_frame=0">51</a></li> <li><a href="/index.php?l=m&amp;p=51&allowed_in_frame=0">52</a></li> <li><a href="/index.php?l=m&amp;p=52&allowed_in_frame=0">53</a></li> <li><a href="/index.php?l=m&amp;p=53&allowed_in_frame=0">54</a></li> <li><a href="/index.php?l=m&amp;p=54&allowed_in_frame=0">55</a></li> <li><a href="/index.php?l=m&amp;p=55&allowed_in_frame=0">56</a></li> </ul> </div> <!-- PAGING --> </div> <!-- DICTIONARY --> <div id="google-adsense"> <div id="ad-icon"><img src="advertising.png"></img></div> <script type="text/javascript"><!-- google_ad_client = "pub-7093273770345366"; google_ad_width = 468; google_ad_height = 60; google_ad_format = "468x60_as"; google_ad_type = "text"; google_ad_channel =""; google_color_border = "000000"; google_color_bg = "FFFBEC"; google_color_link = "300020"; google_color_url = "800020"; google_color_text = "000000"; //--></script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> </div> <!-- GOOGLE-ADSENSE --> <div class="blank">&nbsp;</div> <div id="footer"> <ul id="links"> <li><a href="/abbr.php?allowed_in_frame=0" title="Introduction and abbreviations">Introduction and abbreviations</a></li> <li><a href="/bio.php" title="Who did this?">Who did this?</a></li> <li><a href="/sources.php?allowed_in_frame=0" title="Sources">Sources</a></li> <li><a href="/columns/links.htm" title="Links">Links</a></li> </ul> <ul id="credits"> <li>&copy; 2001-2016 <a href="mailto:byronic106@yahoo.com" title="E-mail Douglas Harper">Douglas Harper</a></li> <li><a href="http://www.logobee.com" title="Logo design by LogoBee.com">Custom logo design</a> by LogoBee.com</li> <li>Web page design by <a href="http://binrock.net/" title="Binary Rock">Dan McCormack</a></li> <li><a href="sponsors.php" title="sponsored words">Sponsored Words</a></li> </ul> <div class="blank">&nbsp;</div> </div> <!-- FOOTER --> </div> <!-- CONTAINER --> <!-- New site launched 20040911.1230 --> <!-- Counter: 863631412 --> <!-- Page was generated in 0.327470 seconds. --> </body> </html> <!-- got/6.3.0 (https://github.com/sindresorhus/got)-->
124.408213
1,278
0.715484
8758ff6ece9d1e5d053bdf12b28dd382e00f6ff5
972
htm
HTML
_data/Vol04_Ch0201-0257/HRS0245/HRS_0245-0021.htm
bronsonavila/hrsscraper
ecbb1048ab284af361fae78adb481eff554b067a
[ "MIT" ]
1
2019-02-22T10:35:29.000Z
2019-02-22T10:35:29.000Z
_data/Vol04_Ch0201-0257/HRS0245/HRS_0245-0021.htm
bronsonavila/hrsscraper
ecbb1048ab284af361fae78adb481eff554b067a
[ "MIT" ]
null
null
null
_data/Vol04_Ch0201-0257/HRS0245/HRS_0245-0021.htm
bronsonavila/hrsscraper
ecbb1048ab284af361fae78adb481eff554b067a
[ "MIT" ]
null
null
null
<div class="WordSection1"> <p align="center" class="RegularParagraphs" style="text-align:center"><b>PART II. STAMPING OF CIGARETTES</b></p> <p class="RegularParagraphs"></p> <p class="XNotesHeading">Note</p> <p class="XNotes"></p> <p class="XNotes"> Repeal of this part on June 30, 2006, by L 2000, c 249, §20(2) was deleted by L 2002, c 94, §3.</p> <p class="XNotes"></p> <p class="RegularParagraphs"> <b>[§245-21] Payment of tax through use of stamps; exemptions.</b> (a) The tax imposed under section 245-3 upon the sale or use of cigarettes shall be paid by licensees through the use of stamps.</p> <p class="RegularParagraphs"> (b) The department may provide by rule that the tax imposed under section 245-3 upon the sale or use of cigarettes may be paid without the use of stamps in connection with a particular type of transaction. [L 2000, c 249, pt of §1, §20(2); am L 2002, c 94, §3]</p> <p class="RegularParagraphs"></p> <p class="RegularParagraphs"></p> </div>
81
294
0.712963
079bdc420876f1c79530589bcb8c86cdfceec240
95
dart
Dart
test/android_tv_channels_test.dart
vanlooverenkoen/flutter_android_tv_channels
305b0d71f39c551cdadfcb3c1353b2475a2b66ca
[ "MIT" ]
null
null
null
test/android_tv_channels_test.dart
vanlooverenkoen/flutter_android_tv_channels
305b0d71f39c551cdadfcb3c1353b2475a2b66ca
[ "MIT" ]
2
2021-05-15T18:15:12.000Z
2021-05-22T18:37:24.000Z
test/android_tv_channels_test.dart
vanlooverenkoen/flutter_android_tv_channels
305b0d71f39c551cdadfcb3c1353b2475a2b66ca
[ "MIT" ]
null
null
null
import 'package:flutter_test/flutter_test.dart'; void main() { test('Noop', () async {}); }
15.833333
48
0.652632
dc0c598da479f6ecfeeefbe45fa23d49ff2a3cec
3,429
py
Python
kitsune/questions/tests/test_feeds.py
jgmize/kitsune
8f23727a9c7fcdd05afc86886f0134fb08d9a2f0
[ "BSD-3-Clause" ]
null
null
null
kitsune/questions/tests/test_feeds.py
jgmize/kitsune
8f23727a9c7fcdd05afc86886f0134fb08d9a2f0
[ "BSD-3-Clause" ]
null
null
null
kitsune/questions/tests/test_feeds.py
jgmize/kitsune
8f23727a9c7fcdd05afc86886f0134fb08d9a2f0
[ "BSD-3-Clause" ]
null
null
null
from datetime import datetime, timedelta from django.core.cache import cache from nose.tools import eq_ from pyquery import PyQuery as pq from kitsune.sumo.urlresolvers import reverse from kitsune.sumo.helpers import urlparams from kitsune.products.tests import product, topic from kitsune.questions.feeds import QuestionsFeed, TaggedQuestionsFeed from kitsune.questions.models import Question from kitsune.questions.tests import TestCaseBase, question from kitsune.tags.tests import tag from kitsune.users.tests import user class ForumTestFeeds(TestCaseBase): def test_tagged_feed(self): """Test the tagged feed.""" t = tag(name='green', slug='green', save=True) q = question(save=True) q.tags.add('green') items = TaggedQuestionsFeed().items(t) eq_(1, len(items)) eq_(q.id, items[0].id) cache.clear() q = question(save=True) q.tags.add('green') q.updated = datetime.now() + timedelta(days=1) q.save() items = TaggedQuestionsFeed().items(t) eq_(2, len(items)) eq_(q.id, items[0].id) def test_tagged_feed_link(self): """Make sure the tagged feed is discoverable on the questions page.""" tag(name='green', slug='green', save=True) url = urlparams(reverse('questions.questions'), tagged='green') response = self.client.get(url) doc = pq(response.content) feed_links = doc('link[type="application/atom+xml"]') eq_(2, len(feed_links)) eq_('Recently updated questions', feed_links[0].attrib['title']) eq_('/en-US/questions/feed', feed_links[0].attrib['href']) eq_('Recently updated questions tagged green', feed_links[1].attrib['title']) eq_('/en-US/questions/tagged/green/feed', feed_links[1].attrib['href']) def test_no_inactive_users(self): """Ensure that inactive users' questions don't appear in the feed.""" u = user(is_active=False, save=True) q = Question(title='Test Question', content='Lorem Ipsum Dolor', creator_id=u.id) q.save() assert q.id not in [x.id for x in QuestionsFeed().items({})] def test_question_feed_with_product(self): """Test that questions feeds with products work.""" p = product(save=True) url = urlparams(reverse('questions.questions'), product=p.slug) res = self.client.get(url) doc = pq(res.content) feed_links = doc('link[type="application/atom+xml"]') feed = feed_links[0] eq_(1, len(feed_links)) eq_('Recently updated questions', feed.attrib['title']) eq_('/en-US/questions/feed?product=' + p.slug, feed.attrib['href']) def test_question_feed_with_product_and_topic(self): """Test that questions feeds with products and topics work.""" p = product(save=True) t = topic(product=p, save=True) url = urlparams(reverse('questions.questions'), product=p.slug, topic=t.slug) res = self.client.get(url) doc = pq(res.content) feed_links = doc('link[type="application/atom+xml"]') feed = feed_links[0] eq_(1, len(feed_links)) eq_('Recently updated questions', feed.attrib['title']) eq_(urlparams('/en-US/questions/feed', product=p.slug, topic=t.slug), feed.attrib['href'])
37.681319
78
0.636045
284e5ef0df401ab2e4fde19277c6eca3c9d1d558
301
go
Go
models/productsearchkeyword.go
RoughIndustries/go_shopware
a1395c3bc007ae1b76cdf1e2babdd3e8292ea24e
[ "MIT" ]
null
null
null
models/productsearchkeyword.go
RoughIndustries/go_shopware
a1395c3bc007ae1b76cdf1e2babdd3e8292ea24e
[ "MIT" ]
null
null
null
models/productsearchkeyword.go
RoughIndustries/go_shopware
a1395c3bc007ae1b76cdf1e2babdd3e8292ea24e
[ "MIT" ]
null
null
null
package models type ProductSearchKeyword struct { Entity LanguageID string `json:"languageId"` ProductID string `json:"productId"` Keyword string `json:"keyword"` Ranking float64 `json:"ranking"` Product *Product `json:"product"` Language *Language `json:"language"` }
25.083333
41
0.694352
265f450da64b70fcb4abbd0a1777bd9af2836d69
4,464
java
Java
org.coreasm.engine/src/org/coreasm/engine/scheduler/ConcurrentProgramEvaluator.java
Locke/coreasm.core
9f6ab791cbe76501754869e031bff63f761f659e
[ "AFL-3.0" ]
1
2020-02-04T20:31:01.000Z
2020-02-04T20:31:01.000Z
org.coreasm.engine/src/org/coreasm/engine/scheduler/ConcurrentProgramEvaluator.java
Locke/coreasm.core
9f6ab791cbe76501754869e031bff63f761f659e
[ "AFL-3.0" ]
null
null
null
org.coreasm.engine/src/org/coreasm/engine/scheduler/ConcurrentProgramEvaluator.java
Locke/coreasm.core
9f6ab791cbe76501754869e031bff63f761f659e
[ "AFL-3.0" ]
null
null
null
/* * ConcurrentProgramEvaluator.java $Revision: 80 $ * * Copyright (c) 2008 Roozbeh Farahbod * * Last modified on $Date: 2009-07-24 16:25:41 +0200 (Fr, 24 Jul 2009) $ by $Author: rfarahbod $ * * Licensed under the Academic Free License version 3.0 * http://www.opensource.org/licenses/afl-3.0.php * http://www.coreasm.org/afl-3.0.php * */ package org.coreasm.engine.scheduler; import java.util.Arrays; import java.util.List; import java.util.concurrent.RecursiveTask; import org.coreasm.engine.ControlAPI; import org.coreasm.engine.EngineException; import org.coreasm.engine.absstorage.AbstractStorage; import org.coreasm.engine.absstorage.Element; import org.coreasm.engine.absstorage.RuleElement; import org.coreasm.engine.absstorage.UpdateMultiset; import org.coreasm.engine.interpreter.ASTNode; import org.coreasm.engine.interpreter.Interpreter; import org.coreasm.engine.interpreter.InterpreterImp; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Evaluates programs of a set of agents in parallel using * Java concurrency methods. * * @author Roozbeh Farahbod * */ public class ConcurrentProgramEvaluator extends RecursiveTask<UpdateMultiset> { protected static final Logger logger = LoggerFactory.getLogger(ConcurrentProgramEvaluator.class); private final AgentContextMap agentContextMap; private final ControlAPI capi; private final AbstractStorage storage; private final Element agent; private final boolean shouldPrintExecutionStats; private String executionStats; /** * Creates a new program evaluator. * * @param capi * @param agentContextMap * @param agent */ public ConcurrentProgramEvaluator(ControlAPI capi, AgentContextMap agentContextMap, Element agent, boolean shouldPrintExecutionStats) { this.agent = agent; this.capi = capi; this.storage = capi.getStorage(); this.agentContextMap = agentContextMap; this.shouldPrintExecutionStats = shouldPrintExecutionStats; } @Override public UpdateMultiset compute() { long startTime = System.nanoTime(); UpdateMultiset result; try { result = evaluate(agent); } catch(EngineException e) { throw new RuntimeException("could not evaluate agent", e); } if (shouldPrintExecutionStats) { executionStats = Thread.currentThread().toString() + " took " + (System.nanoTime() - startTime) / 1e6 + "ms to evaluate agent " + agent; } return result; } /* * Evaluates the program of the given agent. */ private UpdateMultiset evaluate(Element agent) throws EngineException { AgentContext context = agentContextMap.get(agent); Interpreter inter; if (context == null) { context = new AgentContext(agent); agentContextMap.put(agent, context); context.interpreter = new InterpreterImp(capi); inter = context.interpreter; } else { inter = context.interpreter; inter.cleanUp(); } inter.cleanUp(); Element program = storage.getChosenProgram(agent); if (program.equals(Element.UNDEF)) throw new EngineException("Program of agent " + agent.denotation() + " is undefined."); if (!(program instanceof RuleElement)) throw new EngineException("Program of agent " + agent.denotation() + " is not a rule element: " + program); inter.setSelf(agent); ASTNode ruleNode = ((RuleElement)program).getBody(); ASTNode rootNode = context.nodeCopyCache.get(ruleNode); if (rootNode == null) { rootNode = (ASTNode)inter.copyTree(ruleNode); context.nodeCopyCache.put(ruleNode, rootNode); } else { inter.clearTree(rootNode); } inter.setPosition(rootNode); // allow the interpreter to perform internal initialization // prior to program execution inter.initProgramExecution(); do inter.executeTree(); while (!(inter.isExecutionComplete() || capi.hasErrorOccurred())); // if rootNode hasn't been evaluated after inter.isExecutionComplete() returned true, the AST has been corrupted if (!rootNode.isEvaluated() && !capi.hasErrorOccurred()) throw new EngineException("AST of " + agent.denotation() + program.denotation() + " has been corrupted."); // if an error occurred in the engine, just return an empty multiset UpdateMultiset result; if (capi.hasErrorOccurred()) result = new UpdateMultiset(); else result = rootNode.getUpdates(); if (logger.isDebugEnabled()) logger.debug("Updates are: " + result.toString()); return result; } public String getExecutionStats() { return executionStats; } }
28.987013
136
0.737231
965cc0375945814c4a02d69a681f102dd1715359
4,837
lua
Lua
home-manager/configs/neovim/lua/config/telescope.lua
corymhall/nixfiles
3c8e6893fdbfe7f9db46d4a32fcec5207d250338
[ "CC0-1.0" ]
null
null
null
home-manager/configs/neovim/lua/config/telescope.lua
corymhall/nixfiles
3c8e6893fdbfe7f9db46d4a32fcec5207d250338
[ "CC0-1.0" ]
null
null
null
home-manager/configs/neovim/lua/config/telescope.lua
corymhall/nixfiles
3c8e6893fdbfe7f9db46d4a32fcec5207d250338
[ "CC0-1.0" ]
null
null
null
-- Telescope local actions = require('telescope.actions') local sorters = require('telescope.sorters') local previewers = require('telescope.previewers') local trouble = require('trouble.providers.telescope') local themes = require "telescope.themes" require('telescope').setup { defaults = { prompt_prefix = "❯ ", selection_caret = "❯ ", winblend = 0, layout_strategy = "horizontal", layout_config = { width = 0.95, height = 0.85, prompt_position = "top", horizontal = { preview_width = function(_, cols, _) if cols > 200 then return math.floor(cols * 0.4) else return math.floor(cols * 0.6) end end, }, vertical = { width = 0.9, height = 0.95, preview_height = 0.5, }, flex = { horizontal = { preview_width = 0.9, }, }, }, selection_strategy = "reset", color_devicons = true, sorting_strategy = "descending", -- file_sorter = sorters.get_fzy_sorter, file_previewer = previewers.vim_buffer_cat.new, qflist_previewer = previewers.vim_buffer_qflist.new, file_ignore_patterns = { "node_modules", "vendor", "dist", ".git", }, mappings = { i = { ["<C-n>"] = actions.move_selection_next, ["<C-p"] = actions.move_selection_previous, ["<C-j>"] = actions.move_selection_next, ["<C-k"] = actions.move_selection_previous, ["<C-sq"] = actions.send_selected_to_qflist + actions.open_qflist, ["<C-t>"] = trouble.open_with_trouble, }, n = { ["<C-n>"] = actions.move_selection_next, ["<C-p"] = actions.move_selection_previous, ["<C-j>"] = actions.move_selection_next, ["<C-k"] = actions.move_selection_previous, ["<C-sq"] = actions.send_selected_to_qflist + actions.open_qflist, ["<C-t>"] = trouble.open_with_trouble, } }, extensions = { fzf = { override_file_sorter = true, override_generic_sorter = true, } }, } } require('telescope').load_extension 'fzf' require('telescope').load_extension('git_worktree') require('telescope').load_extension("gh") local M = {} function M.fd() local opts = themes.get_ivy { hidden = true } require("telescope.builtin").fd(opts) end function M.git_files() require("telescope.builtin").git_files(themes.get_ivy { hidden = true, cwd = vim.fn.expand "%:p:h", winblend = 10, border = true, shorten_path = false, }) end --telescope mappings --vim.api.nvim_set_keymap('n', '<leader>tt', [[<cmd>lua require("telescope.builtin").find_files()<cr>]], { noremap = true, silent = true }) -- vim.api.nvim_set_keymap('n', '<leader>tt', [[<cmd>lua require("config.telescope").find_files()<cr>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>fd', [[<cmd>lua require("config.telescope").fd()<cr>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>fb', [[<cmd>lua require("telescope.builtin").file_browser()<cr>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>tgf', [[<cmd>lua require("config.telescope").git_files()<cr>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>ta', [[<cmd>lua require("telescope.builtin").live_grep()<cr>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>tgr', [[<cmd>lua require("telescope.builtin").grep_string({ search = vim.fn.expand("<cword>") })<cr>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>tgs', [[<cmd>lua require("telescope.builtin").git_status()<cr>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>tgb', [[<cmd>lua require("telescope.builtin").git_branches()<cr>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>tgbc', [[<cmd>lua require("telescope.builtin").git_bcommits()<cr>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>tgc', [[<cmd>lua require("telescope.builtin").git_commits()<cr>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', ';', [[<cmd>lua require("telescope.builtin").buffers({ ignore_current_buffer = true, sort_mru = true })<cr>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>wo', [[<cmd>lua require("telescope.builtin").lsp_document_symbols()<cr>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>tgw', [[<cmd>lua require("telescope").extensions.git_worktree.git_worktrees()<cr>]], { noremap = true, silent = true }) vim.api.nvim_set_keymap('n', '<leader>tgm', [[<cmd>lua require("telescope").extensions.git_worktree.create_git_worktree()<cr>]], { noremap = true, silent = true }) return M
39.325203
176
0.626628
43274356fecbc7fcd8fce473edf890029785d5f5
909
sql
SQL
zs_m_5_scripts/M5_L13_INSERT_CORNER_CASES.sql
morb1d/zrozumsql
cde4597a8e5c466551f45740039f9ed7038f314f
[ "MIT" ]
1
2020-09-23T18:07:05.000Z
2020-09-23T18:07:05.000Z
zs_m_5_scripts/M5_L13_INSERT_CORNER_CASES.sql
morb1d/zrozumsql
cde4597a8e5c466551f45740039f9ed7038f314f
[ "MIT" ]
null
null
null
zs_m_5_scripts/M5_L13_INSERT_CORNER_CASES.sql
morb1d/zrozumsql
cde4597a8e5c466551f45740039f9ed7038f314f
[ "MIT" ]
5
2020-11-05T11:57:37.000Z
2021-09-22T08:09:54.000Z
-- M5L13 - INSERT CORNER CASES DROP TABLE IF EXISTS sales; CREATE TABLE sales ( id SERIAL, sal_description TEXT, sal_date DATE, sal_value NUMERIC(10,2), added_by TEXT DEFAULT 'admin', created_date TIMESTAMP DEFAULT now() ); EXPLAIN ANALYZE INSERT INTO sales (sal_description, sal_date, sal_value) SELECT left(md5(i::text), 10), NOW() + (random() * (interval '90 days')) + '30 days', random() * 10 + 1 FROM generate_series(1, 20000) s(i); SELECT COUNT(*) FROM sales; TRUNCATE TABLE sales RESTART IDENTITY; -- Option 1 Execute Script Separate Inserts -- Option 2 Execute Script Combined Inserts -- Option 3 COPY -- COPY public.sales TO 'D:\PostgreSQL_dump\M5_L13_SALES20K_COPY.copy'; -- COPY public.sales FROM 'D:\PostgreSQL_dump\M5_L13_SALES20K_COPY.copy'; -- Wiecej o COPY: https://postgresql.org/docs/12/sql-copy.html
30.3
74
0.676568
70cba331fc845c5218316c34bdba4d3cb0b9db3b
295
cs
C#
Assets/Scripts/Control/Equipment/ServeCounter.cs
theoperatore/midnight-barista
941a42a35d588a233676f68fa2fa2b9a3ecf2980
[ "MIT" ]
null
null
null
Assets/Scripts/Control/Equipment/ServeCounter.cs
theoperatore/midnight-barista
941a42a35d588a233676f68fa2fa2b9a3ecf2980
[ "MIT" ]
null
null
null
Assets/Scripts/Control/Equipment/ServeCounter.cs
theoperatore/midnight-barista
941a42a35d588a233676f68fa2fa2b9a3ecf2980
[ "MIT" ]
null
null
null
using System.Collections; using System.Collections.Generic; using Midnight.Control; using Midnight.Events; using UnityEngine; public class ServeCounter : MonoBehaviour { [SerializeField] GameEvent raisesEvent; public void OnInteraction() { raisesEvent.Raise(); } }
18.4375
42
0.728814
b052ab8c8cb072879c213afc96c9944c9ff131eb
2,872
html
HTML
_posts/2009-10-12-una-historia-de-bugs.html
jfromaniello/joseoncodecom
c35f99fbd8b6c709680f9649b078fb6171074719
[ "MIT" ]
1
2015-11-04T19:35:18.000Z
2015-11-04T19:35:18.000Z
_posts/2009-10-12-una-historia-de-bugs.html
jfromaniello/joseoncodecom
c35f99fbd8b6c709680f9649b078fb6171074719
[ "MIT" ]
null
null
null
_posts/2009-10-12-una-historia-de-bugs.html
jfromaniello/joseoncodecom
c35f99fbd8b6c709680f9649b078fb6171074719
[ "MIT" ]
null
null
null
--- layout: post title: Una historia de bugs tags: [] status: publish type: post published: true meta: blogger_blog: jfromaniello.blogspot.com blogger_author: "Jos\xC3\xA9http://www.blogger.com/profile/00939999997597980426noreply@blogger.com" blogger_permalink: /2009/10/una-historia-de-bugs.html blogger_images: "1" --- <p>Hace unos días encontré un error en Moq, el framework de Mock que estoy usando actualmente. Tuve un presentimiento por el stack trace de la excepción que era un error de DynamicProxy, sabiendo que Moq utiliza DynamicProxy de Castle y conociendo un poco DynamicProxy, decidí investigar Moq por dentro.</p> <p>Lo primero que hice fue escribir un test en Moq que fallará, pero adivine qué?, este es un tipo de error muy raro relacionado al debugger de visual studio, así que si el debugger no esta “enganchado”, el error no aparece. Lo segundo que hice fue aislar el problema a DynamicProxy, y ahí fue cuando realmente me di cuenta que estaba directamente relacionado con DynamicProxy. Acto seguido, intente reproducir el problema en la versión trunk de dynamicproxy, que evidentemente no es la que estaba usando mi versión de Moq. Y también fallaba. Todo lo que he comentado hasta este punto ha sido con alguna ayuda de mi amigo de Polonia, <a href="http://kozmic.pl/">Krzysztof Kozmic</a>. Pero en este punto es donde mi participación en la historia termina. Y se puede leer todo el hilo <a href="http://groups.google.com/group/moqdisc/browse_thread/thread/ed60049d258a080b">acá</a>.</p> <p>A partir de que cargo el caso <a href="http://support.castleproject.org/projects/DYNPROXY/issues/view/DYNPROXY-ISSUE-115">DP-115</a> es donde empieza a actuar directamente <a href="http://kozmic.pl/">Krzysztof</a>. Según nos comenta, por la complejidad del error, en su camino a descubrirlo a encontrado bugs en:</p> <ul> <li>Reflector</li> <li>Resharper</li> <li>Y parece que finalmente es un error en el debugger.</li> </ul> <p>Imaginó que este trabajo es muy duro ya que implica revisar incluso como ciertas cosas son compiladas. Vengo siguiendo muy de cerca los pasos de Krzysztof, simplemente por que me apasiona aprender. He visto cosas tan maravillosas como <a href="http://gist.github.com/205833">esta</a>, es practicamente lo que DynamicProxy hace tras bambalinas… En 35 líneas de código, mi amigo ha creado un tipo, heredando una interfaz, ha definido su métodos genérico con constraints, ha generado un ensamblado dinámicamente, ha guardado el ensamblado. WAW!</p> <p>Desde ya felicitaciones a Krzysztof. Seguramente él no va a entender nada de este post por que esta en español, a menos que use un traductor.</p> <div class="blogger-post-footer">http://feeds.feedburner.com/JoseFRomaniello<img width='1' height='1' src='https://s3.amazonaws.com/joseoncode.com/img/2935908889399243312-2682373200136261826' alt='' /></div>
179.5
2,539
0.775418
dde09f065b963849034cd5c0133bf840ccbcb4ef
1,061
c
C
modules/synApps_5_6/support/devIocStats-3-1-7/devIocStats/os/default/osdClustInfo.c
A2-Collaboration/epics
b764a53bf449d9f6b54a1173c5e75a22cf95098c
[ "OML" ]
null
null
null
modules/synApps_5_6/support/devIocStats-3-1-7/devIocStats/os/default/osdClustInfo.c
A2-Collaboration/epics
b764a53bf449d9f6b54a1173c5e75a22cf95098c
[ "OML" ]
null
null
null
modules/synApps_5_6/support/devIocStats-3-1-7/devIocStats/os/default/osdClustInfo.c
A2-Collaboration/epics
b764a53bf449d9f6b54a1173c5e75a22cf95098c
[ "OML" ]
null
null
null
/*************************************************************************\ * Copyright (c) 2009 Helmholtz-Zentrum Berlin fuer Materialien und Energie. * Copyright (c) 2002 The University of Chicago, as Operator of Argonne * National Laboratory. * Copyright (c) 2002 The Regents of the University of California, as * Operator of Los Alamos National Laboratory. * EPICS BASE Versions 3.13.7 * and higher are distributed subject to a Software License Agreement found * in file LICENSE that is included with this distribution. \*************************************************************************/ /* osdClustInfo.c - Memory buffer cluster usage: default implementation = do nothing */ /* * Author: Ralph Lange (HZB/BESSY) * * Modification History * 2009-05-19 Ralph Lange (HZB/BESSY) * Restructured OSD parts * */ #include <devIocStats.h> int devIocStatsInitClusterInfo (void) { return 0; } int devIocStatsGetClusterInfo (int pool, clustInfo *pval) { return -1; } int devIocStatsGetClusterUsage (int pool, int *pval) { return -1; }
37.892857
87
0.63525
3566d6c50ddda137f8a55dba9b09531dd2d4bc2c
647
dart
Dart
lib/src/reporters/messages/test/test_message.dart
BartVerm779/dart_gherkin
0f964b7101d97924e9fc6a5a33a16e2f24371883
[ "MIT" ]
null
null
null
lib/src/reporters/messages/test/test_message.dart
BartVerm779/dart_gherkin
0f964b7101d97924e9fc6a5a33a16e2f24371883
[ "MIT" ]
null
null
null
lib/src/reporters/messages/test/test_message.dart
BartVerm779/dart_gherkin
0f964b7101d97924e9fc6a5a33a16e2f24371883
[ "MIT" ]
null
null
null
part of '../messages.dart'; class TestMessage extends ActionMessage { final List<Tag> tags; TestMessage({ required Target target, required String name, required RunnableDebugInformation context, this.tags = const [], }) : super( target: target, name: name, context: context, ); TestMessage copyWith({ Target? target, String? name, RunnableDebugInformation? context, List<Tag>? tags, }) { return TestMessage( target: target ?? this.target, name: name ?? this.name, context: context ?? this.context, tags: tags ?? this.tags, ); } }
20.870968
46
0.601236
4a4795783f77ce290d22b19f9922500b4a3b8daa
3,119
cs
C#
src/StringEnumGenerator/Generator/EnumClass/EnumAllMembersGenerator.cs
ShadowDancer/StringEnumGenerator
c9574c6b99cc2069bbec8ba107c23222bedda0b2
[ "MIT" ]
null
null
null
src/StringEnumGenerator/Generator/EnumClass/EnumAllMembersGenerator.cs
ShadowDancer/StringEnumGenerator
c9574c6b99cc2069bbec8ba107c23222bedda0b2
[ "MIT" ]
1
2021-11-10T00:19:09.000Z
2021-11-10T00:19:09.000Z
src/StringEnumGenerator/Generator/EnumClass/EnumAllMembersGenerator.cs
ShadowDancer/StringEnumGenerator
c9574c6b99cc2069bbec8ba107c23222bedda0b2
[ "MIT" ]
1
2021-11-12T11:52:59.000Z
2021-11-12T11:52:59.000Z
using System.CodeDom.Compiler; using System.Collections.Generic; using Microsoft.CodeAnalysis.CSharp; using StringEnumGenerator.Generator.Model; using StringEnumGenerator.Generator.Utils; namespace StringEnumGenerator.Generator.EnumClass { internal class EnumAllMembersGenerator { public EnumAllMembersGenerator(EnumContext enumContext, IndentedTextWriter sourceWriter) { EnumContext enumContext1 = enumContext; _sourceWriter = sourceWriter; _accessibility = SyntaxFacts.GetText(enumContext1.Symbol.DeclaredAccessibility); _docWriter = new DocWriter(_sourceWriter); _enumName = enumContext1.Symbol.Name; } private readonly string _enumName; private readonly string _accessibility; private readonly IndentedTextWriter _sourceWriter; private readonly DocWriter _docWriter; public void GenerateAllMembersFunction(IReadOnlyList<string> enumMembers) { const string allMembersFieldName = "_allMembersCache"; string allMembersFieldDeclaration = $"private static Lazy<ImmutableArray<{_enumName}>>? {allMembersFieldName};"; _sourceWriter.WriteLine(allMembersFieldDeclaration); _sourceWriter.WriteLine(); _docWriter.WriteSummary(DocumentationText.AllMembers.Summary(_enumName)); string allMembersSignature = $"{_accessibility} static ImmutableArray<{_enumName}> AllMembers"; _sourceWriter.WriteLine(allMembersSignature); using (_sourceWriter.Scope()) { _sourceWriter.WriteLine("get"); using (_sourceWriter.Scope()) { _sourceWriter.WriteLine($"if ({allMembersFieldName} == null)"); using (_sourceWriter.Scope()) { _sourceWriter.WriteLine($"var newLazy = new Lazy<ImmutableArray<{_enumName}>>(() =>"); using (_sourceWriter.Scope()) { _sourceWriter.WriteLine($"return ImmutableArray.Create<{_enumName}>("); for(int i = 0; i < enumMembers.Count; i++) { _sourceWriter.Write($"{_enumName}.{enumMembers[i]}"); if(i + 1 < enumMembers.Count) { _sourceWriter.Write(","); } _sourceWriter.WriteLine(); } _sourceWriter.WriteLine(");"); } _sourceWriter.WriteLine(");"); _sourceWriter.WriteLine($"Interlocked.CompareExchange(ref {allMembersFieldName}, newLazy, null);"); } _sourceWriter.WriteLine($"return {allMembersFieldName}.Value;"); } } } } }
38.036585
124
0.547932
2f310bf1bfa79f551491f85490c3f587842ce96c
225
java
Java
jpa/deferred/src/main/java/example/service/Customer1341Service.java
Balkerm/spring-data-examples
092e31e890cc5ad226311be0938eb477068905f3
[ "Apache-2.0" ]
4,772
2015-01-06T12:36:15.000Z
2022-03-30T13:37:02.000Z
jpa/deferred/src/main/java/example/service/Customer1341Service.java
Balkerm/spring-data-examples
092e31e890cc5ad226311be0938eb477068905f3
[ "Apache-2.0" ]
519
2015-01-04T17:10:10.000Z
2022-03-30T06:20:17.000Z
jpa/deferred/src/main/java/example/service/Customer1341Service.java
Balkerm/spring-data-examples
092e31e890cc5ad226311be0938eb477068905f3
[ "Apache-2.0" ]
3,670
2015-01-06T03:47:23.000Z
2022-03-31T12:16:18.000Z
package example.service; import example.repo.Customer1341Repository; import org.springframework.stereotype.Service; @Service public class Customer1341Service { public Customer1341Service(Customer1341Repository repo) {} }
20.454545
59
0.84
0699842f40ebb5a4b45bd7be26fdea04a0da304e
23,990
asm
Assembly
engine/debug/debug_menu.asm
AtmaBuster/pokeplat-gen2
fa83b2e75575949b8f72cb2c48f7a1042e97f70f
[ "blessing" ]
6
2021-06-19T06:41:19.000Z
2022-02-15T17:12:33.000Z
engine/debug/debug_menu.asm
AtmaBuster/pokeplat-gen2
fa83b2e75575949b8f72cb2c48f7a1042e97f70f
[ "blessing" ]
null
null
null
engine/debug/debug_menu.asm
AtmaBuster/pokeplat-gen2
fa83b2e75575949b8f72cb2c48f7a1042e97f70f
[ "blessing" ]
2
2021-08-11T19:47:07.000Z
2022-01-01T07:07:56.000Z
smartcp: MACRO IF \1 == 0 and a ELSE cp \1 ENDC ENDM cphl16: MACRO ; arg1: 16 bit register ; arg2: value to compare to ld a, h smartcp HIGH(\1) jr c, .done\@ jr nz, .done\@ ld a, l smartcp LOW(\1) .done\@ ENDM DebugMenu:: call ClearWindowData ld de, SFX_MENU call PlaySFX farcall ReanchorBGMap_NoOAMUpdate ld a, [wBattleMenuCursorBuffer] ld [wMenuCursorBuffer], a lb bc, SCREEN_HEIGHT - 2, 11 hlcoord 0, 0 call Textbox call SafeUpdateSprites call _OpenAndCloseMenu_HDMATransferTileMapAndAttrMap farcall LoadFonts_NoOAMUpdate call UpdateTimePals call .GetInput jr c, .Exit ld a, [wMenuSelection] ld hl, .Jumptable rst JumpTable .Exit: ldh a, [hOAMUpdate] push af ld a, 1 ldh [hOAMUpdate], a call LoadFontsExtra pop af ldh [hOAMUpdate], a call ExitMenu call CloseText call UpdateTimePals ret .GetInput: xor a ldh [hBGMapMode], a ld hl, .MenuHeader call LoadMenuHeader call ScrollingMenu and B_BUTTON jr nz, .b and a ret .b scf ret .MenuHeader: db MENU_BACKUP_TILES ; flags menu_coords 1, 1, 11, SCREEN_HEIGHT - 2 dw .MenuData db 1 ; default selection .MenuData: db 0, 8, 0 db SCROLLINGMENU_ITEMS_NORMAL dba .MenuItems dba .PlaceMenuStrings dba NULL .PlaceMenuStrings: push de ld a, [wMenuSelection] ld hl, .Strings call GetNthString ld d, h ld e, l pop hl call PlaceString ret .Strings: db "Sound Test@" db "Subgame@" db "Warp@" db "Color@" db "Fill Dex@" db "Teach Move@" db "Give #@" db "Max ¥@" db "Warp Any@" db "PC@" db "Fill Bag@" db "Fill TM/HM@" db "Play Cry@" db "Trainer@" .MenuItems db 14 db 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 db -1 .Jumptable dw Debug_SoundTest dw Debug_SubgameMenu dw Debug_Warp dw Debug_ColorPicker dw Debug_FillDex dw Debug_TeachMove dw Debug_GivePoke dw Debug_MaxMoney dw Debug_WarpAny dw Debug_PC dw Debug_FillBag dw Debug_FillTMHM dw Debug_PlayCry dw Debug_Trainer Debug_SoundTest: ld de, MUSIC_NONE call PlayMusic xor a ldh [hDebugMenuDataBuffer], a ldh [hDebugMenuDataBuffer + 1], a ldh [hDebugMenuDataBuffer + 2], a ldh [hDebugMenuDataBuffer + 3], a hlcoord 0, 0 lb bc, 6, SCREEN_WIDTH - 2 call Textbox call WaitBGMap2 ld a, 1 ldh [hDebugMenuCursorPos], a call .update_display xor a ldh [hDebugMenuCursorPos], a call .update_display .loop call JoyTextDelay ldh a, [hJoyLast] cp B_BUTTON jp z, .end cp D_LEFT jr z, .left cp D_RIGHT jr z, .right cp A_BUTTON jp z, .play and D_UP | D_DOWN jr nz, .change jr .loop .change ldh a, [hDebugMenuCursorPos] inc a and 1 ldh [hDebugMenuCursorPos], a call .update_display jr .loop .left call .get_value .left_loop dec de dec a jr nz, .left_loop call .put_value call .update_display jr .loop .right call .get_value .right_loop inc de dec a jr nz, .right_loop call .put_value call .update_display jr .loop .update_display hlcoord 1, 2 ld a, " " ld [hl], a hlcoord 1, 5 ld a, " " ld [hl], a ldh a, [hDebugMenuCursorPos] and a jr z, .update_music hlcoord 1, 5 ld a, "▶" ldi [hl], a inc hl ld a, " " ldi [hl], a ldi [hl], a ldi [hl], a ldi [hl], a ld [hl], a hlcoord 3, 5 ld de, hDebugMenuDataBuffer + 2 lb bc, PRINTNUM_LEADINGZEROS | 2, 5 call PrintNum ret .update_music hlcoord 1, 2 ld a, "▶" ldi [hl], a inc hl ld a, " " ldi [hl], a ldi [hl], a ldi [hl], a ldi [hl], a ld [hl], a hlcoord 3, 2 ld de, hDebugMenuDataBuffer lb bc, PRINTNUM_LEADINGZEROS | 2, 5 call PrintNum hlcoord 1, 3 ld bc, 18 ld a, " " call ByteFill ld hl, Debug_MusicNames ld bc, 18 ldh a, [hDebugMenuDataBuffer + 1] cp a, 103 jp nc, .loop call AddNTimes ld d, h ld e, l hlcoord 1, 3 call PlaceString ret .play ldh a, [hDebugMenuCursorPos] and a jr z, .play_music call .get_value call PlaySFX ;call WaitSFX jp .loop .play_music ld de, 0 call PlayMusic call DelayFrame call .get_value call PlayMusic jp .loop .end ret .get_value ldh a, [hDebugMenuCursorPos] ld hl, hDebugMenuDataBuffer add a add l ld l, a ldi a, [hl] ld e, [hl] ld d, a ldh a, [hJoyDown] and SELECT ld a, 1 ret z ld a, 10 ret .put_value ldh a, [hDebugMenuCursorPos] ld hl, hDebugMenuDataBuffer add a add l ld l, a ld a, d ldi [hl], a ld [hl], e ret INCLUDE "engine/debug/music_names.asm" Debug_SubgameMenu: ld hl, .MenuHeader call LoadMenuHeader call VerticalMenu ret c ld a, [wMenuCursorY] dec a ld bc, 3 ld hl, .Jumptable call AddNTimes ldi a, [hl] ld b, a ldi a, [hl] ld h, [hl] ld l, a ld a, b rst $08 ret .Jumptable: dba SlotMachine dba CardFlip dba MiningGame dba UnownPuzzle .MenuHeader: db MENU_BACKUP_TILES menu_coords 10, 0, SCREEN_WIDTH - 1, 9 dw .MenuData db 1 ; default .MenuData: db STATICMENU_CURSOR db 4 ; # items db "Slots@" db "Card@" db "Mining@" db "Unown@" Debug_Warp: lb bc, SCREEN_HEIGHT - 2, SCREEN_WIDTH - 2 hlcoord 0, 0 call Textbox ld hl, .MenuHeader call LoadMenuHeader call ScrollingMenu and B_BUTTON ret nz ld a, [wMenuSelection] cp -1 ret z dec a ld c, a ld b, 0 ld hl, .SpawnTable add hl, bc ld a, [hl] ld [wDefaultSpawnpoint], a farcall FlyFunction.DoFly ld a, HMENURETURN_SCRIPT ldh [hMenuReturn], a ret .SpawnTable db SPAWN_HOME db SPAWN_DEBUG db SPAWN_TWINLEAF db SPAWN_SANDGEM db SPAWN_JUBILIFE db SPAWN_OREBURGH db SPAWN_FLOAROMA db SPAWN_ETERNA db SPAWN_HEARTHOME db SPAWN_SOLACEON db SPAWN_VEILSTONE db SPAWN_PASTORIA db SPAWN_CELESTIC db SPAWN_CANALAVE db SPAWN_SNOWPOINT db SPAWN_SUNYSHORE db SPAWN_LEAGUE_S db SPAWN_LEAGUE_N db SPAWN_FIGHT_AREA db SPAWN_SURVIVAL_AREA db SPAWN_RESORT_AREA db SPAWN_PAL_PARK NUM_DEBUG_SPAWNS EQU 22 .MenuHeader: db MENU_BACKUP_TILES menu_coords 1, 1, SCREEN_WIDTH - 2, SCREEN_HEIGHT - 2 dw .MenuData db 1 .MenuData: db 0 db 8, 0 db SCROLLINGMENU_ITEMS_NORMAL dba .Items dba .DrawItem dba NULL .Items: db NUM_DEBUG_SPAWNS x = 1 rept NUM_DEBUG_SPAWNS db x x = x + 1 endr db -1 .DrawItem: push de ld a, [wMenuSelection] dec a ld hl, .LocNames ld bc, 13 call AddNTimes ld d, h ld e, l pop hl call PlaceString ret .LocNames: db "HOME@@@@@@@@@" db "DEBUG@@@@@@@@" db "TWINLEAF@@@@@" db "SANDGEM@@@@@@" db "JUBILIFE@@@@@" db "OREBURGH@@@@@" db "6@@@@@@@@@@@@" db "7@@@@@@@@@@@@" db "8@@@@@@@@@@@@" db "9@@@@@@@@@@@@" db "10@@@@@@@@@@@" db "11@@@@@@@@@@@" db "12@@@@@@@@@@@" db "13@@@@@@@@@@@" db "14@@@@@@@@@@@" db "15@@@@@@@@@@@" db "16@@@@@@@@@@@" db "17@@@@@@@@@@@" db "18@@@@@@@@@@@" db "19@@@@@@@@@@@" db "20@@@@@@@@@@@" db "21@@@@@@@@@@@" Debug_ColorPicker: ldh a, [hMapAnims] push af xor a ldh [hMapAnims], a farcall DebugColorPicker pop af ldh [hMapAnims], a ret INCLUDE "engine/debug/color_picker.asm" Debug_FillDex: ; give pokedex ld de, ENGINE_POKEDEX ld b, SET_FLAG farcall EngineFlagAction ; set flags ld hl, 0 .loop inc hl ld a, h cp HIGH(ALT_FORMS) jr nz, .setflag ld a, l cp LOW(ALT_FORMS) ret z .setflag push hl call GetPokemonIDFromIndex call SetSeenAndCaughtMon pop hl jr .loop Debug_TeachMove: xor a ldh [hDebugMenuDataBuffer], a ldh [hDebugMenuDataBuffer + 1], a hlcoord 0, 0 lb bc, 6, SCREEN_WIDTH - 2 call Textbox call WaitBGMap2 call .update_display .loop call JoyTextDelay ldh a, [hJoyLast] cp B_BUTTON ret z cp A_BUTTON jr z, .teach ld b, a ldh a, [hJoyDown] and $f or b cp D_LEFT jr z, .left1 cp D_RIGHT jr z, .right1 cp D_DOWN jr z, .left10 cp D_UP jr z, .right10 cp D_LEFT | SELECT jr z, .left100 cp D_RIGHT | SELECT jr z, .right100 jr .loop .left1 call .left call .update_display jr .loop .right1 call .right call .update_display jr .loop .left100 ld c, 100 jr .left10loop .right100 ld c, 100 jr .right10loop .left10 ld c, 10 .left10loop call .left dec c jr nz, .left10loop call .update_display jr .loop .right10 ld c, 10 .right10loop call .right dec c jr nz, .right10loop call .update_display jr .loop .teach xor a ld [wCurPartyMon], a ldh a, [hDebugMenuDataBuffer] ld h, a ldh a, [hDebugMenuDataBuffer + 1] ld l, a call GetMoveIDFromIndex ld [wTempTMHM], a ld [wPutativeTMHMMove], a call GetMoveName ld de, wStringBuffer2 ld hl, wStringBuffer1 ld bc, 13 call CopyBytes predef LearnMove ret .left ldh a, [hDebugMenuDataBuffer + 1] and a jr nz, .go_left ldh a, [hDebugMenuDataBuffer] and a jr nz, .go_left2 ld a, HIGH(NUM_ATTACKS) ldh [hDebugMenuDataBuffer], a ld a, LOW(NUM_ATTACKS) ldh [hDebugMenuDataBuffer + 1], a ret .go_left2 dec a ldh [hDebugMenuDataBuffer], a xor a .go_left dec a ldh [hDebugMenuDataBuffer + 1], a ret .right ldh a, [hDebugMenuDataBuffer + 1] cp LOW(NUM_ATTACKS) jr nz, .go_right ldh a, [hDebugMenuDataBuffer] cp HIGH(NUM_ATTACKS) jr nz, .go_right xor a ldh [hDebugMenuDataBuffer], a ldh [hDebugMenuDataBuffer + 1], a ret .go_right ldh a, [hDebugMenuDataBuffer + 1] inc a ldh [hDebugMenuDataBuffer + 1], a ret nz ldh a, [hDebugMenuDataBuffer] inc a ldh [hDebugMenuDataBuffer], a ret .update_display hlcoord 3, 2 ld a, " " ldi [hl], a ldi [hl], a ldi [hl], a ldi [hl], a ld [hl], a hlcoord 3, 2 ld de, hDebugMenuDataBuffer lb bc, PRINTNUM_LEADINGZEROS | 2, 5 call PrintNum hlcoord 1, 3 ld a, " " ld bc, 18 call ByteFill ld hl, hDebugMenuDataBuffer ld a, [hli] ld l, [hl] ld h, a and a jr nz, .doname ld a, l and a ret z .doname call GetMoveIDFromIndex ld [wNamedObjectIndexBuffer], a call GetMoveName hlcoord 1, 3 ld de, wStringBuffer1 call PlaceString ret Debug_GivePoke: xor a ldh [hDebugMenuDataBuffer], a ldh [hDebugMenuDataBuffer + 1], a ldh [hDebugMenuDataBuffer + 2], a ldh [hDebugMenuDataBuffer + 3], a ldh [hDebugMenuDataBuffer + 4], a ldh [hDebugMenuDataBuffer + 5], a hlcoord 0, 0 lb bc, 8, SCREEN_WIDTH - 2 call Textbox call WaitBGMap2 ld a, 2 ldh [hDebugMenuCursorPos], a call .update_display ld a, 1 ldh [hDebugMenuCursorPos], a call .update_display xor a ldh [hDebugMenuCursorPos], a call .update_display .loop call JoyTextDelay ldh a, [hJoyDown] and $e ld b, a ldh a, [hJoyLast] or b bit A_BUTTON_F, a jr nz, .givepoke bit B_BUTTON_F, a ret nz bit D_DOWN_F, a jr nz, .down bit D_UP_F, a jr nz, .up ld b, 1 bit START_F, a jr nz, .start bit SELECT_F, a jr z, .select ld b, 10 jr .select .start ld b, 100 .select bit D_LEFT_F, a jr nz, .left bit D_RIGHT_F, a jr nz, .right jr .loop .up ldh a, [hDebugMenuCursorPos] and a jr nz, .do_up ld a, 3 .do_up dec a jr .curchange .down ldh a, [hDebugMenuCursorPos] cp 2 jr nz, .do_down ld a, -1 .do_down inc a .curchange ldh [hDebugMenuCursorPos], a call .update_display jr .loop .left call .getdat .leftloop dec hl dec b jr nz, .leftloop call .putdat call .update_display jr .loop .right call .getdat .rightloop inc hl dec b jr nz, .rightloop call .putdat call .update_display jr .loop .getdat ldh a, [hDebugMenuCursorPos] add a add LOW(hDebugMenuDataBuffer) ld c, a ldh a, [c] ld h, a inc c ldh a, [c] ld l, a dec c ret .putdat ld a, h ldh [c], a inc c ld a, l ldh [c], a ret .givepoke ldh a, [hDebugMenuDataBuffer] ld h, a ldh a, [hDebugMenuDataBuffer + 1] ld l, a cphl16 0 jp z, .loop cphl16 NUM_POKEMON + 1 jp nc, .loop ldh a, [hDebugMenuDataBuffer + 5] and a jp z, .loop cp 101 jp nc, .loop ld [wCurPartyLevel], a ldh a, [hDebugMenuDataBuffer + 3] ld [wCurItem], a call GetPokemonIDFromIndex ld [wCurPartySpecies], a ld b, 0 farcall GivePoke ret .update_display ld a, " " hlcoord 1, 2 ld [hl], a hlcoord 1, 5 ld [hl], a hlcoord 1, 8 ld [hl], a ldh a, [hDebugMenuCursorPos] and a jr z, .put_mon dec a jr z, .put_item ; fallthrough .put_level hlcoord 1, 8 ld a, "▶" ld [hl], a hlcoord 3, 8 ld a, "L" ld [hli], a ld a, "v" ld [hli], a inc hl ld de, hDebugMenuDataBuffer + 5 lb bc, PRINTNUM_LEADINGZEROS | 1, 3 call PrintNum ret .put_mon hlcoord 1, 2 ld a, "▶" ld [hl], a hlcoord 3, 2 ld de, hDebugMenuDataBuffer lb bc, PRINTNUM_LEADINGZEROS | 2, 5 call PrintNum ldh a, [hDebugMenuDataBuffer] ld h, a ldh a, [hDebugMenuDataBuffer + 1] ld l, a cphl16 0 ret z cphl16 NUM_POKEMON + 1 ret nc push hl hlcoord 1, 3 ld a, " " ld bc, 18 call ByteFill pop hl call GetPokemonIDFromIndex ld [wNamedObjectIndexBuffer], a call GetPokemonName ld de, wStringBuffer1 hlcoord 1, 3 call PlaceString ret .put_item hlcoord 1, 5 ld a, "▶" ld [hl], a hlcoord 3, 5 ld de, hDebugMenuDataBuffer + 3 lb bc, PRINTNUM_LEADINGZEROS | 1, 3 call PrintNum hlcoord 1, 6 ld bc, 18 ld a, " " call ByteFill ldh a, [hDebugMenuDataBuffer + 3] ld [wNamedObjectIndexBuffer], a call GetItemName ld de, wStringBuffer1 hlcoord 1, 6 call PlaceString ret Debug_MaxMoney: ld hl, wMoney ld a, HIGH(MAX_MONEY >> 8) ld [hli], a ld a, LOW(MAX_MONEY >> 8) ld [hli], a ld a, LOW(MAX_MONEY) ld [hl], a ld hl, wCoins ld a, HIGH(MAX_COINS) ld [hli], a ld a, LOW(MAX_COINS) ld [hl], a ret Debug_WarpAny: ld a, 1 ldh [hDebugMenuDataBuffer], a ldh [hDebugMenuDataBuffer + 1], a ldh [hDebugMenuDataBuffer + 2], a hlcoord 0, 0 lb bc, 3, SCREEN_WIDTH - 2 call Textbox call WaitBGMap2 ld a, 2 ldh [hDebugMenuCursorPos], a call .update_display ld a, 1 ldh [hDebugMenuCursorPos], a call .update_display xor a ldh [hDebugMenuCursorPos], a call .update_display .loop call JoyTextDelay ldh a, [hJoyDown] and $e ld b, a ldh a, [hJoyLast] or b bit A_BUTTON_F, a jr nz, .warp bit B_BUTTON_F, a ret nz bit D_DOWN_F, a jr nz, .down bit D_UP_F, a jr nz, .up ld b, 1 bit START_F, a jr nz, .start bit SELECT_F, a jr z, .select ld b, 10 jr .select .start ld b, 100 .select bit D_LEFT_F, a jr nz, .left bit D_RIGHT_F, a jr nz, .right jr .loop .up ldh a, [hDebugMenuCursorPos] and a jr nz, .do_up ld a, 3 .do_up dec a jr .curchange .down ldh a, [hDebugMenuCursorPos] cp 2 jr nz, .do_down ld a, -1 .do_down inc a .curchange ldh [hDebugMenuCursorPos], a call .update_display jr .loop .left call .getdat .leftloop dec a dec b jr nz, .leftloop call .putdat call .update_display jr .loop .right call .getdat .rightloop inc a dec b jr nz, .rightloop call .putdat call .update_display jr .loop .getdat ldh a, [hDebugMenuCursorPos] add LOW(hDebugMenuDataBuffer) ld c, a ldh a, [c] ret .putdat ldh [c], a ret .warp ld hl, hDebugMenuDataBuffer ld de, wNextWarp ld bc, 3 call CopyBytes ld a, BANK(dig_incave.UsedDigOrEscapeRopeScript) ld hl, dig_incave.UsedDigOrEscapeRopeScript + 1 call FarQueueScript ld a, HMENURETURN_SCRIPT ldh [hMenuReturn], a ret .update_display ld a, " " hlcoord 1, 1 ld [hl], a hlcoord 1, 2 ld [hl], a hlcoord 1, 3 ld [hl], a ldh a, [hDebugMenuCursorPos] and a ld c, a ld b, 0 ld hl, hDebugMenuDataBuffer add hl, bc ld d, h ld e, l hlcoord 1, 1 ld bc, SCREEN_WIDTH call AddNTimes ld a, "▶" ld [hli], a inc hl lb bc, PRINTNUM_LEADINGZEROS | 1, 3 call PrintNum ret Debug_PC: farcall PokemonCenterPC ret Debug_FillBag: ld hl, wNumItems ld bc, wMedicineEnd - wNumItems xor a call ByteFill ld a, -1 ld hl, wItems ld [hl], a ld hl, wKeyItems ld [hl], a ld hl, wBalls ld [hl], a ld hl, wBerries ld [hl], a ld hl, wMedicine ld [hl], a ld a, 1 .loop push af ld [wCurItem], a ld [wNamedObjectIndexBuffer], a call GetItemName ld a, [wStringBuffer1] cp "?" jr z, .next farcall CheckItemPocket ld a, [wItemAttributeParamBuffer] cp KEY_ITEM jr z, .give_key_item ld a, 99 ld [wItemQuantityChangeBuffer], a ld hl, wNumItems call ReceiveItem call nc, .full_break jr .next .give_key_item ld a, 1 ld [wItemQuantityChangeBuffer], a ld hl, wNumItems call ReceiveItem call nc, .full_break .next pop af inc a cp -1 jr nz, .loop ret .full_break ; set breakpoint to check if full ret Debug_FillTMHM: ld hl, wTMsHMs ld e, NUM_TMS + NUM_HMS pushwrambank wTMsHMs ld a, 99 .loop ld [hli], a dec e jr nz, .loop popwrambank ret Debug_PlayCry: ld de, MUSIC_NONE call PlayMusic xor a ld hl, hDebugMenuDataBuffer ld [hli], a ld [hli], a ld [hli], a ld [hli], a ld [hli], a ld [hli], a ld [hli], a ld [hli], a ld [hDebugMenuCursorPos], a ld a, LOW(hDebugMenuDataBuffer) ld [hl], a hlcoord 0, 0 lb bc, 7, SCREEN_WIDTH - 2 call Textbox call WaitBGMap2 call .update_numbers .loop call JoyTextDelay ldh a, [hJoyLast] cp B_BUTTON ret z cp D_LEFT jr z, .left cp D_RIGHT jr z, .right cp A_BUTTON jr z, .play cp D_UP jr z, .up cp D_DOWN jr z, .down jr .loop ret .left ldh a, [hDebugMenuDataBuffer + 8] ld c, a ldh a, [c] ld h, a inc c ldh a, [c] ld l, a call .updateleft ld a, l ldh [c], a dec c ld a, h ldh [c], a call .update_numbers jr .loop .right ldh a, [hDebugMenuDataBuffer + 8] ld c, a ldh a, [c] ld h, a inc c ldh a, [c] ld l, a call .updateright ld a, l ldh [c], a dec c ld a, h ldh [c], a call .update_numbers jr .loop .up ldh a, [hDebugMenuDataBuffer + 8] cp LOW(hDebugMenuDataBuffer) jr z, .underflow dec a dec a jr .set_cursor .underflow ld a, LOW(hDebugMenuDataBuffer + 6) jr .set_cursor .down ldh a, [hDebugMenuDataBuffer + 8] cp LOW(hDebugMenuDataBuffer + 6) jr z, .overrflow inc a inc a jr .set_cursor .overrflow ld a, LOW(hDebugMenuDataBuffer) .set_cursor ldh [hDebugMenuDataBuffer + 8], a call .update_numbers jr .loop .play ld a, [hJoyDown] and SELECT jr nz, .copyvanilla ld hl, hDebugMenuDataBuffer + 2 ld d, [hl] inc hl ld e, [hl] inc hl ld a, [hli] ld [wCryPitch + 1], a ld a, [hli] ld [wCryPitch], a ld a, [hli] ld [wCryLength + 1], a ld a, [hl] ld [wCryLength], a farcall _PlayCry jp .loop .copyvanilla ld hl, hDebugMenuDataBuffer ld d, [hl] inc hl ld e, [hl] dec de ld a, d and a ld hl, PokemonCries ld a, BANK(PokemonCries) add hl, de add hl, de add hl, de add hl, de add hl, de add hl, de ld de, hDebugMenuDataBuffer + 2 ld bc, 6 call FarCopyBytes ld c, LOW(hDebugMenuDataBuffer + 2) REPT 3 ldh a, [c] inc c ld d, a ldh a, [c] ld e, a ld a, d ldh [c], a dec c ld a, e ldh [c], a inc c inc c ENDR call .update_numbers jp .loop .update_numbers hlcoord 8, 1 ld bc, 11 ld a, " " call ByteFill hlcoord 1, 1 ld bc, SCREEN_WIDTH * 2 ld [hl], a add hl, bc ld [hl], a add hl, bc ld [hl], a add hl, bc ld [hl], a ldh a, [hDebugMenuDataBuffer + 8] sub LOW(hDebugMenuDataBuffer) hlcoord 1, 1 ld bc, SCREEN_WIDTH call AddNTimes ld a, "▶" ld [hl], a hlcoord 2, 3 ld de, .basecry call PlaceString hlcoord 2, 5 ld de, .pitch call PlaceString hlcoord 2, 7 ld de, .length call PlaceString hlcoord 8, 3 ld de, hDebugMenuDataBuffer + 2 lb bc, PRINTNUM_LEADINGZEROS | 2, 5 call PrintNum hlcoord 8, 5 ld de, hDebugMenuDataBuffer + 4 lb bc, PRINTNUM_LEADINGZEROS | 2, 5 call PrintNum hlcoord 8, 7 ld de, hDebugMenuDataBuffer + 6 lb bc, PRINTNUM_LEADINGZEROS | 2, 5 call PrintNum hlcoord 15, 3 ld de, hDebugMenuDataBuffer + 2 ld b, 2 call PrintHexNum hlcoord 15, 5 ld de, hDebugMenuDataBuffer + 4 ld b, 2 call PrintHexNum hlcoord 15, 7 ld de, hDebugMenuDataBuffer + 6 ld b, 2 call PrintHexNum hlcoord 2, 1 ld de, hDebugMenuDataBuffer lb bc, PRINTNUM_LEADINGZEROS | 2, 5 call PrintNum ldh a, [hDebugMenuDataBuffer] cp HIGH(NUM_POKEMON) jr c, .show_name ldh a, [hDebugMenuDataBuffer + 1] cp LOW(NUM_POKEMON) + 1 ret nc .show_name ldh a, [hDebugMenuDataBuffer] ld h, a ldh a, [hDebugMenuDataBuffer + 1] ld l, a call GetPokemonIDFromIndex ld [wNamedObjectIndexBuffer], a call GetPokemonName ld de, wStringBuffer1 hlcoord 8, 1 call PlaceString ret .basecry db "Base@" .pitch db "Pitch@" .length db "Length@" .updateleft call .getupdateamt .leftloop dec hl dec de ld a, d or e jr nz, .leftloop ret .updateright call .getupdateamt .rightloop inc hl dec de ld a, d or e jr nz, .rightloop ret .getupdateamt ldh a, [hJoyDown] and START | SELECT and a jr z, .neither cp START jr z, .start cp SELECT jr z, .select ; both ld de, 1000 ret .select ld de, 10 ret .start ld de, 100 ret .neither ld de, 1 ret PrintHexNum: ld a, [de] inc de call .print_byte dec b jr nz, PrintHexNum ret .print_byte push af swap a call .print_digit pop af .print_digit and $f cp $a jr c, .ok add "A" .ok add "0" ld [hli], a ret Debug_Trainer: xor a ldh [hDebugMenuDataBuffer], a ldh [hDebugMenuDataBuffer + 1], a ldh [hDebugMenuCursorPos], a hlcoord 0, 0 lb bc, 6, SCREEN_WIDTH - 2 call Textbox call WaitBGMap2 call .update_display .loop call JoyTextDelay ldh a, [hJoyLast] cp B_BUTTON jp z, .end cp D_LEFT jr z, .left cp D_RIGHT jr z, .right cp A_BUTTON jp z, .fight and D_UP | D_DOWN jr nz, .change jr .loop .change ldh a, [hDebugMenuCursorPos] inc a and 1 ldh [hDebugMenuCursorPos], a call .update_display jr .loop .left call .get_value .left_loop dec d dec a jr nz, .left_loop call .put_value ldh a, [hDebugMenuCursorPos] and a call z, .reset_trainer_num call .update_display jr .loop .right call .get_value .right_loop inc d dec a jr nz, .right_loop call .put_value ldh a, [hDebugMenuCursorPos] and a call z, .reset_trainer_num call .update_display jr .loop .reset_trainer_num ld a, 1 ldh [hDebugMenuDataBuffer + 1], a ret .update_display hlcoord 1, 2 ld a, " " ld [hl], a hlcoord 1, 5 ld a, " " ld [hl], a ldh a, [hDebugMenuCursorPos] and a hlcoord 1, 2 jr z, .got_cursor_pos hlcoord 1, 5 .got_cursor_pos ld a, "▶" ld [hl], a call .update_class hlcoord 3, 5 ld a, " " ld bc, 15 call ByteFill call .get_trainer_name jr c, .skip_trainer_name hlcoord 3, 5 ld de, wStringBuffer1 call PlaceString .skip_trainer_name hlcoord 3, 6 ld de, hDebugMenuDataBuffer + 1 lb bc, PRINTNUM_LEADINGZEROS | 1, 3 call PrintNum ret .update_class hlcoord 3, 2 ld a, " " ld bc, 15 call ByteFill ld a, TRAINER_NAME ld [wNamedObjectTypeBuffer], a ldh a, [hDebugMenuDataBuffer] and a jr z, .skip_class_name cp NUM_TRAINER_CLASSES jr nc, .skip_class_name ld [wCurSpecies], a ld [wTrainerClass], a call GetName hlcoord 3, 2 ld de, wStringBuffer1 call PlaceString .skip_class_name hlcoord 3, 3 ld de, hDebugMenuDataBuffer lb bc, PRINTNUM_LEADINGZEROS | 1, 3 call PrintNum ret .fight ldh a, [hDebugMenuDataBuffer] and a jp z, .loop cp NUM_TRAINER_CLASSES jp nc, .loop ld [wOtherTrainerClass], a ldh a, [hDebugMenuDataBuffer + 1] and a jp z, .loop ld [wOtherTrainerID], a ld a, $1 ld [wBattleScriptFlags], a ld hl, wWinTextPointer ld a, LOW(DefaultWinText) ld [hli], a ld a, HIGH(DefaultWinText) ld [hli], a ld a, LOW(DefaultLossText) ld [hli], a ld a, HIGH(DefaultLossText) ld [hl], a call BufferScreen predef StartBattle ld a, MAPSETUP_RELOADMAP ldh [hMapEntryMethod], a ld a, MAPSTATUS_ENTER call LoadMapStatus ld hl, wScriptFlags res SCRIPT_RUNNING, [hl] pop af ret .end ret .get_value ldh a, [hDebugMenuCursorPos] ld hl, hDebugMenuDataBuffer add l ld l, a ld d, [hl] ldh a, [hJoyDown] and SELECT ld a, 1 ret z ld a, 10 ret .put_value ldh a, [hDebugMenuCursorPos] ld hl, hDebugMenuDataBuffer add l ld l, a ld [hl], d ret .cancel_trainer_name scf ret .get_trainer_name ldh a, [hDebugMenuDataBuffer] and a jr z, .cancel_trainer_name cp NUM_TRAINER_CLASSES jr nc, .cancel_trainer_name dec a ld c, a add a add c ld c, a ld b, 0 ld hl, TrainerGroups ld a, BANK(TrainerGroups) add hl, bc call GetFarByte push af ld a, BANK(TrainerGroups) inc hl call GetFarHalfword pop af ld b, a ldh a, [hDebugMenuDataBuffer + 1] and a jr z, .cancel_trainer_name dec a and a jr z, .got_loc ld c, a .trainer_name_loop ld a, b call GetFarByte push bc ld b, 0 ld c, a add hl, bc pop bc dec c jr z, .got_loc jr .trainer_name_loop .got_loc inc hl ld de, wStringBuffer1 ld a, b ld bc, 18 call FarCopyBytes ld a, "@" ld [wStringBuffer2 - 1], a ld hl, wStringBuffer1 ld c, 18 call Debug_SanitizeString and a ret Debug_SanitizeString: .loop ld a, [hli] cp "@" ret z cp $80 jr nc, .loop dec hl ld a, "@" ld [hl], a ret
14.557039
54
0.682534
800ee2a59207f1b1c8f79ec1434c9970d0bc06af
1,024
java
Java
src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/NonStationaryLighter.java
Jerome226/Create
dfe2f41b59d91bd9bbf11fb6bca7b260dc1c47fe
[ "MIT" ]
1,131
2019-11-09T00:41:08.000Z
2022-03-31T17:42:41.000Z
src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/NonStationaryLighter.java
Jerome226/Create
dfe2f41b59d91bd9bbf11fb6bca7b260dc1c47fe
[ "MIT" ]
2,749
2019-11-09T03:37:38.000Z
2022-03-31T18:48:00.000Z
src/main/java/com/simibubi/create/content/contraptions/components/structureMovement/NonStationaryLighter.java
Jerome226/Create
dfe2f41b59d91bd9bbf11fb6bca7b260dc1c47fe
[ "MIT" ]
528
2019-11-17T04:55:06.000Z
2022-03-31T16:11:43.000Z
package com.simibubi.create.content.contraptions.components.structureMovement; import com.jozufozu.flywheel.light.GridAlignedBB; import com.simibubi.create.content.contraptions.components.structureMovement.render.RenderedContraption; public class NonStationaryLighter<C extends Contraption> extends ContraptionLighter<C> { public NonStationaryLighter(C contraption) { super(contraption); } @Override public void tick(RenderedContraption owner) { super.tick(owner); GridAlignedBB contraptionBounds = getContraptionBounds(); if (!contraptionBounds.sameAs(bounds)) { lightVolume.move(contraption.entity.level, contraptionBoundsToVolume(contraptionBounds)); bounds = contraptionBounds; startListening(); } } @Override public GridAlignedBB getContraptionBounds() { GridAlignedBB bb = GridAlignedBB.from(contraption.bounds); bb.translate(contraption.entity.blockPosition()); return bb; } }
31.030303
104
0.72168
cb9dd4ac6699d1c8ed9dfe505d5bcae23b9d7653
753
go
Go
authenticate_test.go
Muthu-Palaniyappan-OL/jwt
b28a60fff1dd2bcd105f8b33584d35f87e1735c1
[ "Apache-2.0" ]
null
null
null
authenticate_test.go
Muthu-Palaniyappan-OL/jwt
b28a60fff1dd2bcd105f8b33584d35f87e1735c1
[ "Apache-2.0" ]
null
null
null
authenticate_test.go
Muthu-Palaniyappan-OL/jwt
b28a60fff1dd2bcd105f8b33584d35f87e1735c1
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 Muthu Palaniyappan OL. All rights reserved. // Use of this source code is governed by a Apache-2.0 // license that can be found in the LICENSE file. package jwt import ( "math/rand" "net/http/httptest" "testing" ) func TestAuthenticate(t *testing.T) { if !IsPrivateKeySet() { SetPrivateKey("testingprivatekey") } rw := httptest.NewRecorder() _, err := Authenticate(rw, encode("testingjsonstring"), rand.Int()) if err != nil { t.Fatalf("error created by Authenticate() function, error:", err) return } cookies := rw.Result().Cookies() jwtExists := false for _, c := range cookies { if c.Name == "jwt" { jwtExists = true } } if jwtExists == true { } else { t.Fatal("jwt Cookies is not set") } }
17.511628
68
0.662683
d279a9b8985e5c1103d254b13828e29db16520a3
6,073
php
PHP
web/php/web.php
ruboweb/TorrentScannerET
be0299df0f32c58b88e94bfc9ce57efecf1500be
[ "Apache-2.0" ]
null
null
null
web/php/web.php
ruboweb/TorrentScannerET
be0299df0f32c58b88e94bfc9ce57efecf1500be
[ "Apache-2.0" ]
null
null
null
web/php/web.php
ruboweb/TorrentScannerET
be0299df0f32c58b88e94bfc9ce57efecf1500be
[ "Apache-2.0" ]
null
null
null
<?php require_once("../../config.php"); if(!isset($_SESSION)) { session_start(); } if(empty($_SESSION["scann_result"])) { $_SESSION["scann_result"] = ""; } /* Parse paramenters ------------------ */ if (isset($_GET["type"]) && $_GET["type"] == "update") { if ($_POST["updateRadio"] == "f"){ update("films"); } if($_POST["updateRadio"] == "s"){ update("series"); } } if (isset($_GET["type"]) && $_GET["type"] == "scanfilm") { $dwn = ""; if (isset($_POST["dwn"])) { $dwn = "-d"; } scann("-f", $_POST["title"], $dwn); } if (isset($_GET["type"]) && $_GET["type"] == "scanserie") { $dwn = ""; if (isset($_POST["dwn"])) { $dwn = "-d"; } scann("-s", $_POST["title"], $dwn); } if (isset($_GET["type"]) && $_GET["type"] == "createserie") { createSerie(); } if (isset($_GET["type"]) && $_GET["type"] == "updateserie") { updateSerie(); } if (isset($_GET["type"]) && $_GET["type"] == "deleteserie") { deleteSerie($_GET["id"]); } if (isset($_GET["type"]) && $_GET["type"] == "createfilm") { createFilm(); } if (isset($_GET["type"]) && $_GET["type"] == "updatefilm") { updateFilm(); } if (isset($_GET["type"]) && $_GET["type"] == "deletefilm") { deleteFilm($_GET["id"]); } // Update db contents function update($type) { shell_exec(getPathScanner() . " -" . $type); $_SESSION["scann_result"] = "Last script runned (" . date("d-m-Y H:i:s", time()) ."): \n\n"; $_SESSION["scann_result"] = $_SESSION["scann_result"] . " > " . $type . " Updated!"; header("Location: ../index.php"); die(); } // Scann content function scann($type, $title, $dwn) { $result = shell_exec(getPathScanner() . " " . $type . " " . $title ." -v" . " " . $dwn); $_SESSION["scann_result"] = "Last script runned (" . date("d-m-Y H:i:s", time()) ."): \n\n"; $_SESSION["scann_result"] = $_SESSION["scann_result"] . $result; header("Location: ../index.php"); die(); } // create serie function createSerie() { $title = "'".$_POST["title"]."'"; $search = "'".$_POST["search"]."'"; $lastEpisode = "'".$_POST["lastepisode"]."'"; $lastView = "'".$_POST["lastview"]."'"; $active = 0; if (isset($_POST["active"])) { $active = 1; } $query = "insert into serie (name, search, lastEpisode, lastView, active) values(".$title.", ".$search.", ".$lastEpisode.", ".$lastView.", ".$active.");"; $db = new SQLite3(getDataBaseLocation()); $db->exec($query); $db->close(); header("Location: ../series.php"); die(); } // update serie function updateSerie() { $id = $_POST["id"]; $title = "'".$_POST["title"]."'"; $search = "'".$_POST["search"]."'"; $lastEpisode = "'".$_POST["lastepisode"]."'"; $lastView = "'".$_POST["lastview"]."'"; $active = 0; if (isset($_POST["active"])) { $active = 1; } $query = "update serie set name = ".$title.", search = ".$search.", lastEpisode = " .$lastEpisode.", lastView = ".$lastView.", active = ".$active." where id = ".$id; $db = new SQLite3(getDataBaseLocation()); $db->exec($query); $db->close(); header("Location: ../series.php"); die(); } // delete film function deleteSerie($film) { $query = "delete from serie where id = ".$film; $db = new SQLite3(getDataBaseLocation()); $db->exec($query); $db->close(); header("Location: ../series.php"); die(); } // create film function createFilm() { $title = "'".$_POST["title"]."'"; $search = "'".$_POST["search"]."'"; $query = "insert into film (name, search) values(".$title.", ".$search.");"; $db = new SQLite3(getDataBaseLocation()); $db->exec($query); $db->close(); header("Location: ../films.php"); die(); } // update film function updateFilm() { $id = $_POST["id"]; $title = "'".$_POST["title"]."'"; $search = "'".$_POST["search"]."'"; $results = $_POST["results"]; $query = "update film set name = ".$title.", search = ".$search.", results = " .$results." where id = ".$id; $db = new SQLite3(getDataBaseLocation()); $db->exec($query); $db->close(); header("Location: ../films.php"); die(); } // delete film function deleteFilm($film) { $query = "delete from film where id = ".$film; $db = new SQLite3(getDataBaseLocation()); $db->exec($query); $db->close(); header("Location: ../films.php"); die(); } // get serie function getSerie($id) { $query = "select * from serie where id = " . $id; $db = new SQLite3(getDataBaseLocation()); $results = $db->query($query); $data = array(); while($row = $results->fetchArray(SQLITE3_ASSOC)){ array_push($data, $row); } $db->close(); return $data[0]; } // get film function getFilm($id) { $query = "select * from film where id = " . $id; $db = new SQLite3(getDataBaseLocation()); $results = $db->query($query); $data = array(); while($row = $results->fetchArray(SQLITE3_ASSOC)){ array_push($data, $row); } $db->close(); return $data[0]; } // get all series from database function getSeriesFromDataBase() { $query = "select * from serie"; $db = new SQLite3(getDataBaseLocation()); $results = $db->query($query); $data = array(); while($row = $results->fetchArray(SQLITE3_ASSOC)){ array_push($data, $row); } $db->close(); return $data; } // get all films from database function getFilmsFromDataBase() { $query = "select * from film"; $db = new SQLite3(getDataBaseLocation()); $results = $db->query($query); $data = array(); while($row = $results->fetchArray(SQLITE3_ASSOC)){ array_push($data, $row); } $db->close(); return $data; } ?>
22.660448
168
0.512597
05ced326c5598a9c5f57bdabb0eb33eb9d42b7dd
9,406
sql
SQL
db/app/ddl/src/full/R__11.ORACLE_TOOLS.PROCEDURE.P_GENERATE_DDL.sql
paulissoft/oracle-build-tools
df333cf286eea4f55e429f3821c0a42a0f6e4a58
[ "MIT" ]
1
2022-02-05T03:21:19.000Z
2022-02-05T03:21:19.000Z
db/app/ddl/src/full/R__11.ORACLE_TOOLS.PROCEDURE.P_GENERATE_DDL.sql
paulissoft/oracle-build-tools
df333cf286eea4f55e429f3821c0a42a0f6e4a58
[ "MIT" ]
19
2021-05-26T08:25:55.000Z
2022-03-22T17:10:12.000Z
db/app/ddl/src/full/R__11.ORACLE_TOOLS.PROCEDURE.P_GENERATE_DDL.sql
paulissoft/oracle-tools
df333cf286eea4f55e429f3821c0a42a0f6e4a58
[ "MIT" ]
null
null
null
CREATE OR REPLACE PROCEDURE "ORACLE_TOOLS"."P_GENERATE_DDL" ( pi_source_schema in varchar2 default user , pi_source_database_link in varchar2 default null , pi_target_schema in varchar2 default null , pi_target_database_link in varchar2 default null , pi_object_type in varchar2 default null , pi_object_names_include in natural default null , pi_object_names in varchar2 default null , pi_skip_repeatables in naturaln default 1 , pi_interface in varchar2 default null , pi_transform_param_list in varchar2 default oracle_tools.pkg_ddl_util.c_transform_param_list , po_clob out nocopy clob ) authid current_user as -- to reduce typos we use constant identifiers "pkg_ddl_util v4" constant varchar2(30 char) := 'pkg_ddl_util v4'; "pkg_ddl_util v5" constant varchar2(30 char) := 'pkg_ddl_util v5'; -- try the interfaces in this order -- the first one which matches pi_interface and which does not return an error, wins l_interface_tab constant sys.odcivarchar2list := case when pi_interface is null then sys.odcivarchar2list("pkg_ddl_util v4", "pkg_ddl_util v5") else sys.odcivarchar2list(pi_interface) end; l_processed boolean := false; l_bfile bfile := null; l_cursor sys_refcursor := null; l_ddl_info_tab dbms_sql.varchar2_table; l_text_tab oracle_tools.t_text_tab; c_fetch_limit constant pls_integer := 100; l_buffer varchar2(32767 char) := null; -- dbms_application_info stuff l_rindex binary_integer := dbms_application_info.set_session_longops_nohint; l_slno binary_integer := null; l_sofar binary_integer := 0; l_op_name constant varchar2(10 char) := 'processed'; l_units constant varchar2(10 char) := 'rows'; l_program constant varchar2(61 char) := $$PLSQL_UNIT; -- no schema because l_program is used in dbms_application_info begin $if oracle_tools.cfg_pkg.c_debugging $then dbug.enter($$PLSQL_UNIT_OWNER || '.' || $$PLSQL_UNIT); dbug.print ( dbug."input" , 'pi_source_schema: %s; pi_source_database_link: %s; pi_target_schema: %s; pi_target_database_link: %s' , pi_source_schema , pi_source_database_link , pi_target_schema , pi_target_database_link ); dbug.print ( dbug."input" , 'pi_object_type: %s; pi_object_names_include: %s; pi_object_names: %s; pi_skip_repeatables: %s; pi_interface: %s' , pi_object_type , pi_object_names_include , pi_object_names , pi_skip_repeatables , pi_interface ); $end dbms_lob.createtemporary(po_clob, true); <<interface_loop>> for i_interface_idx in l_interface_tab.first .. l_interface_tab.last loop begin if l_interface_tab(i_interface_idx) in ("pkg_ddl_util v4", "pkg_ddl_util v5") then if pi_target_schema is null then -- enable object valid checks oracle_tools.pkg_ddl_util.execute_ddl ( oracle_tools.t_text_tab('begin oracle_tools.pkg_ddl_util.do_chk(null, true); end;') , pi_source_database_link ); -- full DDL because target schema (and database link) is empty open l_cursor for select '-- ddl info: ' || u.verb() || ';' || t.obj.object_schema() || ';' || t.obj.object_type() || ';' || t.obj.object_name() || ';' || t.obj.base_object_schema() || ';' || t.obj.base_object_type() || ';' || t.obj.base_object_name() || ';' || t.obj.column_name() || ';' || t.obj.grantee() || ';' || t.obj.privilege() || ';' || t.obj.grantable() || ';' || u.ddl#() || chr(10) as ddl_info , u.text from table ( oracle_tools.pkg_ddl_util.display_ddl_schema ( p_schema => pi_source_schema , p_new_schema => null , p_sort_objects_by_deps => case when l_interface_tab(i_interface_idx) = "pkg_ddl_util v4" then 0 else 1 end , p_object_type => pi_object_type , p_object_names => pi_object_names , p_object_names_include => pi_object_names_include , p_network_link => pi_source_database_link , p_grantor_is_schema => 0 , p_transform_param_list => pi_transform_param_list ) ) t , table(t.ddl_tab) u ; else -- incremental DDL because target schema is not empty open l_cursor for select '-- ddl info: ' || u.verb() || ';' || t.obj.object_schema() || ';' || t.obj.object_type() || ';' || t.obj.object_name() || ';' || t.obj.base_object_schema() || ';' || t.obj.base_object_type() || ';' || t.obj.base_object_name() || ';' || t.obj.column_name() || ';' || t.obj.grantee() || ';' || t.obj.privilege() || ';' || t.obj.grantable() || ';' || u.ddl#() || chr(10) as ddl_info , u.text from table ( oracle_tools.pkg_ddl_util.display_ddl_schema_diff ( p_object_type => pi_object_type , p_object_names => pi_object_names , p_object_names_include => pi_object_names_include , p_schema_source => pi_source_schema , p_schema_target => pi_target_schema , p_network_link_source => pi_source_database_link , p_network_link_target => pi_target_database_link , p_skip_repeatables => pi_skip_repeatables , p_transform_param_list => pi_transform_param_list ) ) t , table(t.ddl_tab) u ; end if; dbms_lob.trim(po_clob, 0); oracle_tools.pkg_str_util.append_text('-- '||l_interface_tab(i_interface_idx), po_clob); -- So Perl script generate_ddl.pl knows how to read the output dbms_application_info.set_session_longops(rindex => l_rindex ,slno => l_slno ,op_name => l_op_name ,sofar => l_sofar ,totalwork => 0 ,target_desc => l_program ,units => l_units); loop -- just a simple fetch due to all the temporary clobs fetch l_cursor into l_ddl_info_tab(1), l_text_tab; exit when l_cursor%notfound; -- the text column does not end with an empty newline so we do it here oracle_tools.pkg_str_util.append_text(chr(10)||l_ddl_info_tab(1), po_clob); oracle_tools.pkg_str_util.text2clob(pi_text_tab => l_text_tab, pio_clob => po_clob, pi_append => true); l_sofar := l_sofar + 1; dbms_application_info.set_session_longops(rindex => l_rindex ,slno => l_slno ,op_name => l_op_name ,sofar => l_sofar ,totalwork => 0 ,target_desc => l_program ,units => l_units); end loop; close l_cursor; -- 100% dbms_application_info.set_session_longops(rindex => l_rindex ,slno => l_slno ,op_name => l_op_name ,sofar => l_sofar ,totalwork => l_sofar ,target_desc => l_program ,units => l_units); else raise_application_error(oracle_tools.pkg_ddl_error.c_could_not_process_interface, 'Could not process interface ' || l_interface_tab(i_interface_idx)); end if; l_processed := true; exit interface_loop; -- success, so quit exception when others then $if oracle_tools.cfg_pkg.c_debugging $then dbug.on_error; $end -- when this is the last interface tried we must reraise otherwise we try the next if i_interface_idx = l_interface_tab.last then raise; end if; end; end loop interface_loop; if not(l_processed) then raise_application_error(oracle_tools.pkg_ddl_error.c_could_not_process_interface, 'Could not process interface ' || pi_interface); end if; $if oracle_tools.cfg_pkg.c_debugging $then dbug.leave; $end exception when others then $if oracle_tools.cfg_pkg.c_debugging $then dbug.leave_on_error; $end raise_application_error(oracle_tools.pkg_ddl_error.c_reraise_with_backtrace, dbms_utility.format_error_backtrace, true); end p_generate_ddl; /
41.991071
159
0.557304
81cc7dad4af7230595bd913128017bb1cc4f72a2
434
go
Go
vendor/github.com/vmware/go-vmware-nsxt/aaa/vidm_info.go
Kristian-ZH/gardener-extension-provider-vsphere
61dedd9de991d0fdf9bfa3ae733216ccb30e1640
[ "MIT" ]
122
2018-02-15T14:47:55.000Z
2022-03-28T17:17:39.000Z
vendor/github.com/vmware/go-vmware-nsxt/aaa/vidm_info.go
Kristian-ZH/gardener-extension-provider-vsphere
61dedd9de991d0fdf9bfa3ae733216ccb30e1640
[ "MIT" ]
100
2020-02-04T07:02:31.000Z
2022-03-29T14:49:37.000Z
vendor/github.com/vmware/go-vmware-nsxt/aaa/vidm_info.go
Kristian-ZH/gardener-extension-provider-vsphere
61dedd9de991d0fdf9bfa3ae733216ccb30e1640
[ "MIT" ]
29
2020-01-31T11:50:49.000Z
2022-03-08T10:15:59.000Z
/* Copyright © 2017 VMware, Inc. All Rights Reserved. SPDX-License-Identifier: BSD-2-Clause Generated by: https://github.com/swagger-api/swagger-codegen.git */ package aaa // Vidm Info type VidmInfo struct { // User's Full Name Or User Group's Display Name DisplayName string `json:"display_name,omitempty"` // Username Or Groupname Name string `json:"name,omitempty"` // Type Type_ string `json:"type,omitempty"` }
21.7
70
0.723502
09ad16e8e3064101678481990b6e7f99b6d58180
3,707
lua
Lua
tinytanks/menu_state.lua
egordorichev/jams
ef3f2b57fcf0c5f3744305c56e8ec836c94fa617
[ "MIT" ]
3
2017-10-25T17:54:39.000Z
2018-12-28T18:54:46.000Z
tinytanks/menu_state.lua
egordorichev/jams
ef3f2b57fcf0c5f3744305c56e8ec836c94fa617
[ "MIT" ]
null
null
null
tinytanks/menu_state.lua
egordorichev/jams
ef3f2b57fcf0c5f3744305c56e8ec836c94fa617
[ "MIT" ]
null
null
null
MenuState = State:extend() function MenuState:init() MenuState.super.init(self) self.name = "menu" self.state = "menu" end function MenuState:update(dt) MenuState.super.update(self, dt) end local variant1 = 1 local variant2 = 1 local s1 = 1 local s2 = 1 local levels = require "data.levels" local levelNames = { "tutorial", "1", "2", "3" } local tanks = require "data.tanks" local tankNames = { "T-18", "T-12", "R-10", "B-47" } function MenuState:draw() MenuState.super.draw(self) if self.state == "menu" then Util.drawTextWithStroke("Tiny Tanks", 15, 15) if UI.button("Play", 10, HEIGHT - 30 - 48 - 24, 64, 22) then self.state = "level" log.info("Play") end if UI.button("About", 10, HEIGHT - 30 - 48, 64, 22) then log.info("About") self.state = "about" end if UI.button("Settings", 10, HEIGHT - 30 - 24, 64, 22) then log.info("Settings") self.state = "settings" end if UI.button("Exit", 10, HEIGHT - 30, 64, 22) then log.info("Exit") love.event.quit() end elseif self.state == "about" then Util.drawTextWithStroke("Tiny Tanks", 15, 15) Util.drawTextWithStroke("by @egordorichev", 15, 25) Util.drawTextWithStroke("made for remake jam", 15, 35) Util.drawTextWithStroke("Controls:", 15, 55) Util.drawTextWithStroke("WASD / arrows - move", 15, 65) Util.drawTextWithStroke("x / v / k - shoot", 15, 75) Util.drawTextWithStroke("c / l - hold to rotate", 15, 85) Util.drawTextWithStroke(" cannon with arrows", 15, 95) if UI.button("Back", 10, HEIGHT - 30, 64, 22) then log.info("Back") self.state = "menu" end elseif self.state == "settings" then s1, MUSIC = UI.select({ "on", "off" }, MUSIC, 10, 10, 64, 22, "Music:") s2, SOUNDS = UI.select({ "on", "off" }, SOUNDS, 10, 34, 64, 22, "Sounds:") if s1 then if MUSIC == 1 then music:play() else music:pause() end end if UI.button("Back", 10, HEIGHT - 30, 64, 22) then log.info("Back") self.state = "menu" variant1 = 1 variant2 = 1 end elseif self.state == "level" then Util.drawTextWithStroke("Select level:", 15, 15) s1, variant1 = UI.select(levelNames, variant1, 10, 35, 64, 22) local l = nil local lk for k, l2 in pairs(levels) do if k == levelNames[variant1] then l = l2 lk = k break end end if lk == "tutorial" or Save[lk] then Util.drawTextWithStroke("Handicap: " .. l.handicap, 15, 59) Util.drawTextWithStroke("Map: " .. l.map, 15, 69) if UI.button("Ok", 10, HEIGHT - 54, 64, 22) then log.info("Level selected") self.state = "tank" game.level = l variant1 = 1 variant2 = 1 end else Util.drawTextWithStroke("Locked!", 15, 59) end if UI.button("Back", 10, HEIGHT - 30, 64, 22) then log.info("Back") self.state = "menu" variant1 = 1 variant2 = 1 end elseif self.state == "tank" then Util.drawTextWithStroke("Select tank:", 15, 15) s1, variant1 = UI.select(tankNames, variant1, 10, 35, 64, 22) local l = nil local lk for k, l2 in pairs(tanks) do if k == tankNames[variant1] then l = l2 lk = k break end end if lk == "T-18" or Save[lk] then Util.drawTextWithStroke("Health: " .. l.health, 15, 59) Util.drawTextWithStroke("Speed: " .. l.speed, 15, 69) Util.drawTextWithStroke("Reload time: " .. l.reloadTime, 15, 79) if UI.button("Ok", 10, HEIGHT - 54, 64, 22) then log.info("Tank selected") player = Player(tankNames[variant1]) game:switchState(InGameState()) end else Util.drawTextWithStroke("Locked!", 15, 59) end if UI.button("Back", 10, HEIGHT - 30, 64, 22) then log.info("Back") self.state = "level" variant1 = 1 variant2 = 1 end end end
23.916129
76
0.625573
9e010840d0d69a73fcd09b44212120aa96ac4e6c
1,213
swift
Swift
StashCoach/StashCoachTests/Modules/Achievements/Application Logic/Manager/AchievementsRemoteDataManagerTests.swift
AliceAponasko/StashCoach
745c709d5d316064ad88c66c5df316ac863e9b0d
[ "MIT" ]
null
null
null
StashCoach/StashCoachTests/Modules/Achievements/Application Logic/Manager/AchievementsRemoteDataManagerTests.swift
AliceAponasko/StashCoach
745c709d5d316064ad88c66c5df316ac863e9b0d
[ "MIT" ]
null
null
null
StashCoach/StashCoachTests/Modules/Achievements/Application Logic/Manager/AchievementsRemoteDataManagerTests.swift
AliceAponasko/StashCoach
745c709d5d316064ad88c66c5df316ac863e9b0d
[ "MIT" ]
null
null
null
// // AchievementsRemoteDataManagerTests.swift // StashCoachTests // // Created by Alice Aponasko on 2/1/18. // Copyright © 2018 aliceaponasko. All rights reserved. // import XCTest @testable import StashCoach class AchievementsRemoteDataManagerTests: XCTestCase { private var remoteDataManager = AchievementsRemoteDataManager() private var mockCache = MockCacheStore() override func setUp() { super.setUp() remoteDataManager.cache = mockCache } override func tearDown() { mockCache.removeAll() super.tearDown() } func testNoPath() { remoteDataManager.path = nil remoteDataManager.achievements { achievements in XCTAssertNil(achievements) } } func testWrongPath() { remoteDataManager.path = Bundle.main.path(forResource: "a", ofType: "json") remoteDataManager.achievements { achievements in XCTAssertNil(achievements) } } func testSavedAchievements() { remoteDataManager.achievements { [weak self] achievements in XCTAssertNotNil(achievements) XCTAssertNotNil(self?.mockCache.achievements()) } } }
23.784314
83
0.657049
4a5dee4edc080e39545065e593445ff2b192ef5e
2,373
kt
Kotlin
app/src/main/java/ar/com/wolox/android/example/ui/home/news/individualNew/IndividualNewFragment.kt
wolox-training/nmc-android
e8077f688053c6686f578f539e5525b8b88a9c1a
[ "MIT" ]
null
null
null
app/src/main/java/ar/com/wolox/android/example/ui/home/news/individualNew/IndividualNewFragment.kt
wolox-training/nmc-android
e8077f688053c6686f578f539e5525b8b88a9c1a
[ "MIT" ]
3
2019-07-03T21:54:03.000Z
2019-07-22T17:03:02.000Z
app/src/main/java/ar/com/wolox/android/example/ui/home/news/individualNew/IndividualNewFragment.kt
wolox-training/nmc-android
e8077f688053c6686f578f539e5525b8b88a9c1a
[ "MIT" ]
null
null
null
package ar.com.wolox.android.example.ui.home.news.individualNew import android.net.Uri import android.os.Bundle import android.widget.Toast import ar.com.wolox.android.R import ar.com.wolox.android.example.network.News import ar.com.wolox.wolmo.core.fragment.WolmoFragment import kotlinx.android.synthetic.main.fragment_individual_new.* import javax.inject.Inject class IndividualNewFragment @Inject constructor() : WolmoFragment<IndividualNewPresenter>(), IIndividualNewView { override fun layout(): Int = R.layout.fragment_individual_new override fun init() { val id = arguments?.getParcelable<News>(NEW_ID)?.id arguments?.getParcelable<News>(NEW_ID)?.run { new_title.text = title new_time.text = readableCreationTime new_description.text = text } individual_new_image.setImageURI(Uri.parse(HARDCODED_SHIBA)) individual_new_back_button.setOnClickListener { activity?.onBackPressed() } vSwipeRefreshLayoutIndividualNew.setOnRefreshListener { presenter.onRefreshIndividualNew(id!!) } } override fun refreshNewData(new: News) { new_title.text = new.title new_time.text = new.readableCreationTime new_description.text = new.text } override fun nothingNewToShow() { Toast.makeText(context, R.string.nothing_new_to_show, Toast.LENGTH_SHORT).show() } override fun onRefreshNewError() { Toast.makeText(context, R.string.fail_refreshing_individual_new, Toast.LENGTH_SHORT).show() } override fun startLoading() { vSwipeRefreshLayoutIndividualNew.isRefreshing = true } override fun completeLoading() { vSwipeRefreshLayoutIndividualNew.isRefreshing = false } companion object { /**I put this image because the original ones from the server doesn't load.*/ private const val HARDCODED_SHIBA = "https://webbonbon.com/wp-content/uploads/2018/01/cropped-doge.jpg" private const val NEW_ID = "NEW_ID" fun newInstance(new: News): IndividualNewFragment { val individualNewFragment = IndividualNewFragment() val args = Bundle(1) args.putParcelable(NEW_ID, new) individualNewFragment.arguments = args return individualNewFragment } } }
32.506849
113
0.695744
580c6cd00df2241a753210fc6982578af21f4cfc
437
h
C
Classes/PropertyAnnotation.h
baalexander/Find-an-Apartment
d5f66cf0dbdd03c2e622961cb17e221eeb62cdba
[ "MIT" ]
3
2015-10-18T13:50:04.000Z
2022-03-26T00:22:32.000Z
Classes/PropertyAnnotation.h
baalexander/Find-an-Apartment
d5f66cf0dbdd03c2e622961cb17e221eeb62cdba
[ "MIT" ]
null
null
null
Classes/PropertyAnnotation.h
baalexander/Find-an-Apartment
d5f66cf0dbdd03c2e622961cb17e221eeb62cdba
[ "MIT" ]
1
2019-11-02T05:05:20.000Z
2019-11-02T05:05:20.000Z
#import <Foundation/Foundation.h> #import <MapKit/MapKit.h> #import "Placemark.h" @interface PropertyAnnotation : NSObject <MKAnnotation> { @private Placemark *placemark_; NSInteger index_; } @property (nonatomic, readonly) CLLocationCoordinate2D coordinate; @property (nonatomic, retain) Placemark *placemark; @property (nonatomic, assign) NSInteger index; - (id)initWithPlacemark:(Placemark *)placemark; @end
20.809524
66
0.743707
5e7da500fb14afd3ac991d3092d2c6d1b5fd20fd
1,359
dart
Dart
lib/pages/reviews/components/reviews_appbar.dart
Darklod/Jap-Vocabs
fba69ef39e579d12801fc3d9a9b12697389854a3
[ "MIT" ]
null
null
null
lib/pages/reviews/components/reviews_appbar.dart
Darklod/Jap-Vocabs
fba69ef39e579d12801fc3d9a9b12697389854a3
[ "MIT" ]
null
null
null
lib/pages/reviews/components/reviews_appbar.dart
Darklod/Jap-Vocabs
fba69ef39e579d12801fc3d9a9b12697389854a3
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:percent_indicator/linear_percent_indicator.dart'; class ReviewAppBar extends StatelessWidget { final int current; final int total; final Function onSummary; const ReviewAppBar({this.current, this.total, this.onSummary}); double get _percent => total == 0 ? 0.0 : (current + 1.0) / total; @override Widget build(BuildContext context) { return AppBar( title: Text('復習'), titleSpacing: 0.0, actions: [ IconButton( icon: Icon(Icons.pie_chart), onPressed: onSummary, ), ], bottom: PreferredSize( preferredSize: Size.fromHeight(100), child: Column( children: [ SizedBox(height: 8.0), Text( '${current + 1} / $total', style: TextStyle(color: Colors.white), ), Padding( padding: const EdgeInsets.symmetric( horizontal: 8.0, vertical: 16.0, ), child: LinearPercentIndicator( lineHeight: 10.0, percent: _percent, backgroundColor: Colors.black.withOpacity(0.1), progressColor: Theme.of(context).accentColor, ), ), ], ), ), ); } }
26.647059
68
0.532745
bb1756ae53497fc9817e55112d757039aeedf170
579
sql
SQL
openGaussBase/testcase/KEYWORDS/Indexes/Opengauss_Function_Keyword_Indexes_Case0033.sql
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/KEYWORDS/Indexes/Opengauss_Function_Keyword_Indexes_Case0033.sql
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
openGaussBase/testcase/KEYWORDS/Indexes/Opengauss_Function_Keyword_Indexes_Case0033.sql
opengauss-mirror/Yat
aef107a8304b94e5d99b4f1f36eb46755eb8919e
[ "MulanPSL-1.0" ]
null
null
null
-- @testpoint:opengauss关键字Indexes(非保留),作为视图名 --关键字explain作为视图名,不带引号,创建成功 CREATE or replace VIEW Indexes AS SELECT * FROM pg_tablespace WHERE spcname = 'pg_default'; drop view Indexes; --关键字explain作为视图名,加双引号,创建成功 CREATE or replace VIEW "Indexes" AS SELECT * FROM pg_tablespace WHERE spcname = 'pg_default'; drop VIEW "Indexes"; --关键字explain作为视图名,加单引号,合理报错 CREATE or replace VIEW 'Indexes' AS SELECT * FROM pg_tablespace WHERE spcname = 'pg_default'; --关键字explain作为视图名,加反引号,合理报错 CREATE or replace VIEW `Indexes` AS SELECT * FROM pg_tablespace WHERE spcname = 'pg_default';
26.318182
57
0.777202
269a26ca286d8ef8035c2a8735d6e38bad89a5ac
3,780
java
Java
src/main/java/frc/robot/subsystems/ClimberSubsystem.java
Decatur-High-GlobalDynamics/FRC-2020-Team-4026
47a24d2881c3ad2ebc939d1ebb83b36a3b41f259
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/subsystems/ClimberSubsystem.java
Decatur-High-GlobalDynamics/FRC-2020-Team-4026
47a24d2881c3ad2ebc939d1ebb83b36a3b41f259
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/subsystems/ClimberSubsystem.java
Decatur-High-GlobalDynamics/FRC-2020-Team-4026
47a24d2881c3ad2ebc939d1ebb83b36a3b41f259
[ "BSD-3-Clause" ]
null
null
null
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.subsystems; import com.ctre.phoenix.motorcontrol.NeutralMode; import com.ctre.phoenix.motorcontrol.can.WPI_TalonSRX; import com.ctre.phoenix.motorcontrol.can.WPI_VictorSPX; import edu.wpi.first.wpilibj.DigitalInput; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj2.command.SubsystemBase; import frc.robot.constants.Ports; import java.util.Objects; public class ClimberSubsystem extends SubsystemBase { private final WPI_VictorSPX leftClimber; private final WPI_TalonSRX rightClimber; private final DigitalInput leftLimit; private final DigitalInput rightLimit; private final DigitalInput leftHookLimit; private final DigitalInput rightHookLimit; // constructors public ClimberSubsystem() { throw new IllegalArgumentException( "not allowed! ctor must provide parameters for all dependencies"); } // decouple external dependencies to allow dependency injection for testing public ClimberSubsystem( WPI_VictorSPX leftClimber, WPI_TalonSRX rightClimber, DigitalInput leftLimit, DigitalInput rightLimit, DigitalInput leftHookLimit, DigitalInput rightHookLimit) { this.leftClimber = Objects.requireNonNull(leftClimber, "leftClimber must not be null"); this.rightClimber = Objects.requireNonNull(rightClimber, "rightClimber must not be null"); this.leftLimit = Objects.requireNonNull(leftLimit, "leftLimit must not be null"); this.rightLimit = Objects.requireNonNull(rightLimit, "rightLimit must not be null"); this.rightHookLimit = Objects.requireNonNull(rightHookLimit, "rightHookLimit must not be null"); this.leftHookLimit = Objects.requireNonNull(leftHookLimit, "leftHookLimit must not be null"); leftClimber.setNeutralMode(NeutralMode.Brake); rightClimber.setNeutralMode(NeutralMode.Brake); } // ClimberSubsystem Factory public static ClimberSubsystem Create() { WPI_VictorSPX leftClimber = new WPI_VictorSPX(Ports.LeftClimbCAN); WPI_TalonSRX rightClimber = new WPI_TalonSRX(Ports.RightClimbCAN); DigitalInput leftLimit = new DigitalInput(Ports.Climber_LeftLimitDIO); DigitalInput rightLimit = new DigitalInput(Ports.Climber_RightLimitDIO); DigitalInput leftHookLimit = new DigitalInput(Ports.Hook_LeftDIO); DigitalInput rightHookLimit = new DigitalInput(Ports.Hook_RightDIO); return new ClimberSubsystem( leftClimber, rightClimber, leftLimit, rightLimit, leftHookLimit, rightHookLimit); } @Override public void periodic() { // This method will be called once per scheduler run SmartDashboard.putBoolean("Subsystem.Climber.leftLimit", leftLimit.get()); SmartDashboard.putBoolean("Subsystems.Climber.rightLimit", rightLimit.get()); SmartDashboard.putBoolean("Subsystems.Climber.leftHookLimit", leftHookLimit.get()); SmartDashboard.putBoolean("Subsystems.Climber.rightHookLimit", rightHookLimit.get()); } public void stop() { leftClimber.set(0); rightClimber.set(0); } public void setClimbers(double power) { leftClimber.set(-power); rightClimber.set((power) * .9); } public void setLeftClimber(double power) { leftClimber.set(-power); } public void setRightClimber(double power) { rightClimber.set(power); } }
40.212766
100
0.71455
df772a3ba85da400f083f0fe594920be9c9b2124
2,302
rb
Ruby
lib/ssi/cli.rb
duckdalbe/ssi
dd80d38b6d66f1f40e99809c6cdb636936755a71
[ "Apache-2.0" ]
2
2017-08-22T04:29:34.000Z
2021-08-23T00:12:50.000Z
lib/ssi/cli.rb
duckdalbe/ssi
dd80d38b6d66f1f40e99809c6cdb636936755a71
[ "Apache-2.0" ]
null
null
null
lib/ssi/cli.rb
duckdalbe/ssi
dd80d38b6d66f1f40e99809c6cdb636936755a71
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env ruby require 'rubygems' require 'optparse' require "fileutils" require 'ssi' require 'ssi/version' require "ssi/console_logger" module SSI class CLI class << self COL_WIDTH = 40 def ask_confirm(question) print question answer = $stdin.gets.chomp accepted_confirms = ['y','yes'] accepted_confirms.include?(answer.downcase) end def run @logger = Console_logger options = {} optparse = OptionParser.new do |opts| options[:root_dir] = '.' opts.banner = "Usage: ", $PROGRAM_NAME, " [options] filename [filename] [...]" opts.on("-v", "--[no-]verbose", "Run verbosely") do |v| options[:verbose] = v end opts.on("-d", "--root-dir [DIR]", "The directory considered to be the document root") do |d| options[:root_dir] = d end opts.on("-i", "--inplace [EXTENSION]", "Edit ARGV files in place", " (make backup if EXTENSION supplied)") do |ext| options[:inplace] = true options[:extension] = ext || '' options[:extension].sub!(/\A\.?(?=.)/, ".") # Ensure extension begins with dot. end opts.on_tail("-h", "--help", "Show this message") do puts opts exit end opts.on_tail("--version", "Show version") do puts VERSION exit end end optparse.parse! (puts optparse.help; exit 1) if ARGV.empty? ARGV.each do |fdname| @logger.debug("Reading file '#{fdname}'") if options[:verbose] dir_path = File::dirname(File::expand_path(fdname)) @logger.debug("Path:'#{dir_path}'") if options[:verbose] ssi_obj = SSI.new(options) content = ssi_obj.ssi(dir_path, File.read(fdname)) if options[:inplace] #File.copy(fdname, fdname + options[:extension]) if options[:extension] FileUtils.cp(fdname, fdname + options[:extension]) if (options[:extension] != '') File.open(fdname, 'w') do |fd| fd.write(content) end else puts content end end end end end end
29.139241
102
0.531712
ed84768eaa75baaacc19e1a6fb4bde2c5c67dd63
735
asm
Assembly
unittests/ASM/REP/F3_5B.asm
cobalt2727/FEX
13087f8425aeaad28dc81bed46a83e1d72ff0db8
[ "MIT" ]
628
2020-03-06T14:01:32.000Z
2022-03-31T06:35:14.000Z
unittests/ASM/REP/F3_5B.asm
cobalt2727/FEX
13087f8425aeaad28dc81bed46a83e1d72ff0db8
[ "MIT" ]
576
2020-03-06T08:25:12.000Z
2022-03-30T04:05:29.000Z
unittests/ASM/REP/F3_5B.asm
cobalt2727/FEX
13087f8425aeaad28dc81bed46a83e1d72ff0db8
[ "MIT" ]
38
2020-03-07T06:10:00.000Z
2022-03-29T09:27:36.000Z
%ifdef CONFIG { "RegData": { "XMM0": ["0x0000000100000001", "0x0000000200000002"], "XMM1": ["0x0000000400000004", "0x0000000800000008"] }, "MemoryRegions": { "0x100000000": "4096" } } %endif mov rdx, 0xe0000000 mov rax, 0x3fc000003f800000 ; [1.5, 1.0] mov [rdx + 8 * 0], rax mov rax, 0x4039999a40000000 ; [2.9, 2.0] mov [rdx + 8 * 1], rax mov rax, 0x4083333340800000 ; [4.1, 4.0] mov [rdx + 8 * 2], rax mov rax, 0x4108000041000000 ; [8.5, 8.0] mov [rdx + 8 * 3], rax mov rax, 0x4142434445464748 mov [rdx + 8 * 4], rax mov rax, 0x5152535455565758 mov [rdx + 8 * 5], rax movapd xmm0, [rdx + 8 * 4] movapd xmm1, [rdx + 8 * 4] movapd xmm2, [rdx + 8 * 0] cvttps2dq xmm0, xmm2 cvttps2dq xmm1, [rdx + 8 * 2] hlt
18.846154
58
0.620408
944cc69822ffd29417147e0f01d3d241cabe32aa
9,821
cc
C++
examples/crawler.cc
zhouwenchao2014/Galaster
882e43192ae35a5d60232a88ac887cb2b054115d
[ "MIT" ]
4
2018-06-25T07:05:49.000Z
2021-10-06T13:19:47.000Z
examples/crawler.cc
yhw1234/Galaster
882e43192ae35a5d60232a88ac887cb2b054115d
[ "MIT" ]
null
null
null
examples/crawler.cc
yhw1234/Galaster
882e43192ae35a5d60232a88ac887cb2b054115d
[ "MIT" ]
3
2018-06-25T07:05:55.000Z
2021-02-24T02:14:39.000Z
//============================================================================ // Name : OctaneCrawler.cpp // Author : Berlin Brown (berlin dot brown at gmail.com) // Version : // Copyright : Copyright Berlin Brown 2012-2013 // License : BSD // Description : This is the simplest possible web crawler in C++ // Uses std_regex and std_algorithm //============================================================================ #include <iostream> #include <string> #include <typeinfo> #include <cstdarg> #include <iostream> #include <fstream> #include <map> #include <regex> #include <locale> #include <ctype.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <fcntl.h> #include <netdb.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <time.h> #include "galaster.hh" #include <unistd.h> #include <thread> typedef float _float_type; typedef graph<_float_type> graph_type; typedef layer<_float_type> layer_type; typedef edge<_float_type> edge_type; typedef vertex<_float_type> vertex_type; using namespace std; const int DELAY = 10000; const std::string WRITE_DIR_PATH = "./"; graph_type *the_graph; std::map<std::string, vertex_styled<_float_type> *> visited; std::set<std::string> visited_hostname; std::deque<std::pair<std::string, std::string> > worklist; void to_lower(std::string &str) { for (size_t i = 0; i < str.length(); i++) { str[i] = tolower(str[i]); } } std::wstring stringtowstring(const std::string& s) { std::wstring temp(s.length(),L' '); std::copy(s.begin(), s.end(), temp.begin()); return temp; } class WebPage { public: std::string hostname; std::string page; WebPage() { hostname = ""; page = ""; } std::string parseHttp(const std::string str) { const std::regex re("http://(.*)/?(.*)"); std::smatch what; if (std::regex_match(str, what, re)) { std::string hst = what[1]; to_lower(hst); return hst; } return ""; } void parseHref(const std::string orig_host, const std::string str) { const std::regex re("http://(.*)/(.*)"); std::smatch what; if (std::regex_match(str, what, re)) { // We found a full URL, parse out the 'hostname' // Then parse out the page hostname = what[1]; to_lower(hostname); page = what[2]; } else { // We could not find the 'page' but we can build the hostname hostname = orig_host; page = ""; } } void parse(const std::string orig_host, const std::string hrf) { const std::string hst = parseHttp(hrf); if (!hst.empty()) { // If we have a HTTP prefix // We could end up with a 'hostname' and page parseHref(hst, hrf); } else { hostname = orig_host; page = hrf; } // hostname and page are constructed, // perform post analysis if (page.length() == 0) { page = "/"; } } }; std::string string_format(const char *fmt, ...) { int size = 255; std::string str; va_list ap; while (1) { str.resize(size); va_start(ap, fmt); int n = vsnprintf((char *) str.c_str(), size, fmt, ap); va_end(ap); if (n > -1 && n < size) { str.resize(n); return str; } if (n > -1) size = n + 1; else size *= 2; } return str; } int connect(void) { std::string host, path; while (!worklist.empty()) { host = worklist.front().first; path = worklist.front().second; worklist.pop_front(); auto cv = visited[host + path]; assert(cv != nullptr); char cmd[4096]; sprintf(cmd, "wget '%s%s' -t 1 -T 1 -O received", host.c_str(), path.c_str()); system("rm -f received"); system(cmd); std::ifstream t("received"); std::string recv( (std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); // Parse the data // try { const std::regex rmv_all("[\\r|\\n]"); const std::string s2 = std::regex_replace(recv, rmv_all, std::string("")); const std::string s = s2; const std::regex re("<a\\s+href\\s*=\\s*(\"([^\"]*)\")|('([^']*)')\\s*>"); std::cmatch matches; // Using token iterator with sub-matches const int subs[] = { 2, 4 }; std::sregex_token_iterator i(s.begin(), s.end(), re, subs); std::sregex_token_iterator j; color_type c = color_type(rand_range(0,1), rand_range(0,1), rand_range(0,1)); for (; i != j; i++) { // Iterate through the listed HREFs and // move to next request // const std::string href = *i; if (href.length() != 0) { WebPage* page = new WebPage(); page->parse(host, href); const char* hrefc = page->page.c_str(); std::string new_path = string_format("/%s", hrefc); if (strstr(new_path.c_str(), "javascript") || strstr(new_path.c_str(), "(") || strstr(new_path.c_str(), ")")) { cout << "skip link : " << page->hostname << " page=" << hrefc << endl; } else { if (visited.find(page->hostname + new_path) == visited.end()) { cout << "found link : " << page->hostname << " page=" << hrefc << endl; usleep(DELAY); _float_type cx, cy, cz; cv->x.coord(cx, cy, cz); _float_type r = 5; auto v = new vertex_styled<_float_type>( rand_range(-r + cx, r + cx), rand_range(-r + cy, r + cy), rand_range(-r + cz, r + cz)); // v->font_family = "/Library/Fonts/Courier New.ttf"; // v->label = stringtowstring(new_path.substr(max((int)new_path.length() - 8, 0))); // v->font_size = 24; // v->size = 3; std::string actual_hostname = page->hostname.substr(0, page->hostname.find_first_of("/")); if (visited_hostname.find(actual_hostname) == visited_hostname.end()) { visited_hostname.insert(actual_hostname); v->font_family = "/Library/Fonts/Courier New.ttf"; v->label = stringtowstring(actual_hostname); v->font_size = 24; v->size = 5; } else { v->size = 3; } v->color = c; visited[page->hostname + new_path] = v; the_graph->add_vertex(v); auto e = new edge_styled<_float_type>(cv, v); e->blendcolor = true; the_graph->add_edge(e); worklist.push_back(std::make_pair(page->hostname, new_path)); } else { auto v2 = visited[page->hostname + new_path]; auto e = new edge_styled<_float_type>(cv, v2); e->strength = 0.01; e->blendcolor = true; the_graph->add_edge(e); } } delete page; } } } catch (std::regex_error& e) { cout << "Error: " << e.what() << "\n"; } } return 1; } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (!the_graph) return; if (key == 'N' and action == GLFW_RELEASE) { new std::thread([&]() { connect(); }); } else { galaster_key_callback(window, key, scancode, action, mods); } } int main(int argc, char *argv[]) { if (argc != 3) { printf("usage: %s host path\n", argv[0]); return 0; } cout << "Launching program" << endl; GLFWwindow *window = galaster_init(); if (window) { the_graph = new graph_type(1, 250, // f0 0.02, // K 0.001, // eps 0.6, // damping 1.2); // dilation std::string host = argv[1]; // "www.hrbcu.edu.cn"; std::string path = argv[2]; // "/"; auto v = new vertex_styled<_float_type>(0, 0, 0); v->font_family = "/Library/Fonts/Courier New.ttf"; v->label = stringtowstring(host + path); v->font_size = 24; v->size = 5; v->color = color_type::green; visited[host + path] = v; the_graph->add_vertex(v); worklist.push_back(std::make_pair(host, path)); visited_hostname.insert(host); glfwSetKeyCallback(window, key_callback); galaster_run(window, the_graph, 0.4); } cout << "Done" << endl; return 0; }
31.27707
118
0.462987
0cb86fe9bbc7f2cf6d3e6c50ebc4e8bef2550fd2
316
py
Python
packages/core/minos-microservice-networks/tests/test_networks/test_exceptions.py
sorasful/minos-python
1189330eebf6444627a2af6b29f347670f95a4dd
[ "MIT" ]
247
2022-01-24T14:55:30.000Z
2022-03-25T12:06:17.000Z
packages/core/minos-microservice-networks/tests/test_networks/test_exceptions.py
sorasful/minos-python
1189330eebf6444627a2af6b29f347670f95a4dd
[ "MIT" ]
275
2021-04-03T09:23:40.000Z
2022-01-28T11:56:25.000Z
tests/test_networks/test_exceptions.py
Clariteia/minos_microservice_networks
77f239429653272c5cb3447311513143f8521ed9
[ "MIT" ]
21
2022-02-06T17:25:58.000Z
2022-03-27T04:50:29.000Z
import unittest from minos.common import ( MinosException, ) from minos.networks import ( MinosNetworkException, ) class TestExceptions(unittest.TestCase): def test_type(self): self.assertTrue(issubclass(MinosNetworkException, MinosException)) if __name__ == "__main__": unittest.main()
17.555556
74
0.737342
877994512b825004e236fb8bf26d675139e6f4b2
1,912
dart
Dart
lib/core/events.dart
sourcecaster/serveme
3da0a4337465ffe18d54de7fc070a6615798a8f6
[ "MIT" ]
6
2021-10-31T09:24:43.000Z
2021-12-29T11:44:53.000Z
lib/core/events.dart
sourcecaster/serveme
3da0a4337465ffe18d54de7fc070a6615798a8f6
[ "MIT" ]
null
null
null
lib/core/events.dart
sourcecaster/serveme
3da0a4337465ffe18d54de7fc070a6615798a8f6
[ "MIT" ]
null
null
null
part of serveme; abstract class Event { } class ReadyEvent extends Event { ReadyEvent(); } class TickEvent extends Event { TickEvent(this.counter); final int counter; } class StopEvent extends Event { StopEvent(this.signal, this.code); final ProcessSignal signal; final int code; } class LogEvent extends Event { LogEvent(this.message); final String message; } class ErrorEvent extends Event { ErrorEvent(this.message, [this.stack]); final String message; final StackTrace? stack; } class ConnectEvent<C extends ConnectMeClient> extends Event { ConnectEvent(this.client); final C client; } class DisconnectEvent<C extends ConnectMeClient> extends Event { DisconnectEvent(this.client); final C client; } class Events { Events(this._server) { int counter = 0; _timer = Timer.periodic(const Duration(seconds: 1), (_) { dispatch(TickEvent(++counter)); }); } late final Timer _timer; final ServeMe<ServeMeClient> _server; final Map<Type, List<Function>> _eventHandlers = <Type, List<Function>>{}; void listen<T extends Event>(Future<void> Function(T) handler) { if (_eventHandlers[T] == null) _eventHandlers[T] = <Function>[]; if (!_eventHandlers[T]!.contains(handler)) _eventHandlers[T]!.add(handler); } void cancel<T extends Event>(Future<void> Function(T) handler) { _eventHandlers[T]?.remove(handler); } Future<void> _tryExecute(Function handler, Event event) async { try { await handler(event); } catch (err, stack) { _server._logger.error('Event handler execution error: $err', stack); } } Future<void> dispatch(Event event) async { final List<Future<void>> futures = <Future<void>>[]; if (_eventHandlers[event.runtimeType] != null) { for (final Function handler in _eventHandlers[event.runtimeType]!) { futures.add(_tryExecute(handler, event)); } } await Future.wait(futures); } void dispose() { _timer.cancel(); } }
22.494118
77
0.713912
4a6a106b45cf4ba4227d49d657b35935d2685b73
150
html
HTML
src/app/app.component.html
lyotolaw/lyoto
f957f6922fb5f8acc1a9f54e27516dcfb540ee04
[ "MIT" ]
null
null
null
src/app/app.component.html
lyotolaw/lyoto
f957f6922fb5f8acc1a9f54e27516dcfb540ee04
[ "MIT" ]
null
null
null
src/app/app.component.html
lyotolaw/lyoto
f957f6922fb5f8acc1a9f54e27516dcfb540ee04
[ "MIT" ]
null
null
null
<!--The content below is only a placeholder and can be replaced.--> <app-layout> <todo-form></todo-form> <view-todos></view-todos> </app-layout>
21.428571
67
0.673333
2695385bd4a25d692df7f62ab9def3dc19fd3b45
398
java
Java
src/main/java/com/github/jbox/mongo/SequenceException.java
feiqing/jbox
bcc8ce320e8b201ed9a4d517694e751777b0e7ab
[ "Apache-2.0" ]
9
2017-11-21T06:18:25.000Z
2021-12-31T03:30:47.000Z
src/main/java/com/github/jbox/mongo/SequenceException.java
feiqing/jbox
bcc8ce320e8b201ed9a4d517694e751777b0e7ab
[ "Apache-2.0" ]
3
2017-11-15T08:19:48.000Z
2022-01-21T23:49:01.000Z
src/main/java/com/github/jbox/mongo/SequenceException.java
feiqing/jbox
bcc8ce320e8b201ed9a4d517694e751777b0e7ab
[ "Apache-2.0" ]
13
2017-11-25T15:11:43.000Z
2021-12-23T09:22:22.000Z
package com.github.jbox.mongo; import java.io.Serializable; /** * @author jifang.zjf@alibaba-inc.com (FeiQing) * @version 1.0 * @since 2018/11/3 5:01 PM. */ public class SequenceException extends RuntimeException implements Serializable { private static final long serialVersionUID = -7383087459057215862L; public SequenceException(String message) { super(message); } }
22.111111
81
0.726131
e95e04adee3ef536c106b6971f2e6dca5fc47cfa
644
go
Go
pkg/tenkaihelm/tenkaihelm.go
softplan/tenkai-api
45cbd8edb2c88464ffbccc4138af07b90489c49b
[ "Apache-2.0" ]
6
2019-07-06T02:16:24.000Z
2021-08-05T23:18:42.000Z
pkg/tenkaihelm/tenkaihelm.go
anderson-custodio/tenkai-api
e1f3d70dfe9acda3a67e6abf7b04318d03198e9e
[ "Apache-2.0" ]
74
2020-01-09T14:49:15.000Z
2021-09-08T17:38:10.000Z
pkg/tenkaihelm/tenkaihelm.go
anderson-custodio/tenkai-api
e1f3d70dfe9acda3a67e6abf7b04318d03198e9e
[ "Apache-2.0" ]
4
2020-06-22T15:05:57.000Z
2021-08-05T23:20:37.000Z
package tenkaihelm import ( "net/http" "github.com/softplan/tenkai-api/pkg/util" ) //HelmAPIInteface interface type HelmAPIInteface interface { DoGetRequest(url string) (responseBytes []byte, err error) //doPostRequest(url string) (resp *http.Response, err error) } //HelmAPIImpl struct type HelmAPIImpl struct { } //DoGetRequest make a get request func (helm HelmAPIImpl) DoGetRequest(url string) (responseBytes []byte, err error) { resp, err := http.Get(url) if err != nil { return responseBytes, err } responseBytes, err = util.GetHTTPBodyResponse(resp) if err != nil { return []byte{}, err } return responseBytes, nil }
20.774194
84
0.729814
9002c5929b69e961871c7af79e33c38c3db9f24c
2,094
dart
Dart
example/main.dart
ganeshrvel/pub_rules
73af153dd0a434a5f6f68116284e4868a155359b
[ "MIT" ]
24
2020-06-08T23:28:23.000Z
2022-01-09T08:50:04.000Z
example/main.dart
ganeshrvel/pub_rules
73af153dd0a434a5f6f68116284e4868a155359b
[ "MIT" ]
7
2020-09-02T11:27:54.000Z
2021-06-18T22:53:18.000Z
example/main.dart
ganeshrvel/pub_rules
73af153dd0a434a5f6f68116284e4868a155359b
[ "MIT" ]
4
2020-06-14T13:17:27.000Z
2021-03-17T20:10:39.000Z
/// Usage examples: /// /// For more examples refer to https://github.com/ganeshrvel/pub-rules/blob/master/README.md import 'package:rules/rules.dart'; import 'package:rules/src/helpers/logging.dart'; void rule() { const textFieldValue = 'abc@xyz'; final rule = Rule( textFieldValue, name: 'Text field', isRequired: true, isEmail: true, ); log(rule.error); // output: 'Text field is not a valid email address' log(rule.hasError); // output: true if (rule.hasError) { // some action on error } else { // Some action on success } } void groupRule() { const textFieldValue1 = ''; // or const textFieldValue = null; const textFieldValue2 = ''; final rule1 = Rule( textFieldValue1, name: 'Text field 1', isRequired: true, ); final rule2 = Rule( textFieldValue2, name: 'Text field 2', isEmail: true, ); final groupRule = GroupRule( [rule1, rule2], // value; List of Rule name: 'Group name', // placeholder value which will be used while displaying errors ); log(groupRule.error); // output: 'Text field 1 is required' log(groupRule.hasError); // output: true } void combinedRule() { const textFieldValue1 = ''; const textFieldValue2 = 'abc@xyz.com'; final rule1 = Rule( textFieldValue1, name: 'Text field 1', ); // Validation OK final rule2 = Rule( textFieldValue2, name: 'Text field 2', isEmail: true, ); // Validation OK final groupRule = GroupRule([rule1, rule2], name: 'Group name', requiredAll: true); // Validation FAILED const textFieldValue3 = ''; final rule3 = Rule( textFieldValue3, name: 'Text field 3', isRequired: true, ); // Validation FAILED final combinedRule = CombinedRule( rules: [rule3], groupRules: [groupRule], ); log(combinedRule.errorList); // output: ['Text field 3 is required', 'All fields are mandatory in Group name'] log(combinedRule.hasError); // output: true if (combinedRule.hasError) { // some action on error } else { // Some action on success } }
21.367347
92
0.641834
7099ea19f79fc8863622768758f06f2d13837944
1,303
h
C
Engine/LUAScripting/LuaStateManager.h
GCourtney27/Retina-Engine
5358b9c499f4163a209024dc303c3efe6c520c01
[ "MIT" ]
null
null
null
Engine/LUAScripting/LuaStateManager.h
GCourtney27/Retina-Engine
5358b9c499f4163a209024dc303c3efe6c520c01
[ "MIT" ]
null
null
null
Engine/LUAScripting/LuaStateManager.h
GCourtney27/Retina-Engine
5358b9c499f4163a209024dc303c3efe6c520c01
[ "MIT" ]
null
null
null
#pragma once #include "Lua/LuaPlus/LuaPlus.h" #include "IScriptManager.h" #include <string> #include <DirectXMath.h> //#include "..\Framework\Singleton.h" class LuaStateManager : public IScriptManager//, public Singleton<LuaStateManager> { static LuaStateManager* s_pSingleton; LuaPlus::LuaState* m_pLuaState; std::string m_lastError; public: // Singleton functions static bool Create(void); static void Destroy(void); static LuaStateManager* GetStateManager(void) { return s_pSingleton; } // IScriptManager interafce virtual bool VInitialize() override; virtual void VExecuteFile(const char* resource) override; virtual void VExecuteString(const char* str) override; LuaPlus::LuaObject GetGlobalVars(void); LuaPlus::LuaState* GetLuaState(void) const; // Public helpers LuaPlus::LuaObject CreatePath(const char* pathString, bool toIgnorelastElement = false); void ConvertFloat3ToTable(const DirectX::XMFLOAT3 & vector, LuaPlus::LuaObject & outLuaTable) const; void ConvertTableToFloat3(const LuaPlus::LuaObject & luaTable, DirectX::XMFLOAT3 & outVector) const; private: void SetError(int errorNum); void ClearStack(void); //Private constructor and destructor; call the static Create() and Destroy() instead explicit LuaStateManager(void); virtual ~LuaStateManager(void); };
31.780488
101
0.782041
2a27d43e665525690f6d46b2abb4c7530ab60510
8,417
java
Java
src/main/java/frodez/util/common/StrUtil.java
GroganflyOver/BlogManagePlatform
4d8a2c8485a367edc85e33639c80b5b15ce6af72
[ "Apache-2.0" ]
45
2019-03-02T09:46:39.000Z
2021-11-22T01:38:19.000Z
src/main/java/frodez/util/common/StrUtil.java
GroganflyOver/BlogManagePlatform
4d8a2c8485a367edc85e33639c80b5b15ce6af72
[ "Apache-2.0" ]
2
2019-03-04T01:57:33.000Z
2019-11-20T03:26:27.000Z
src/main/java/frodez/util/common/StrUtil.java
GroganflyOver/BlogManagePlatform
4d8a2c8485a367edc85e33639c80b5b15ce6af72
[ "Apache-2.0" ]
19
2019-03-30T12:35:45.000Z
2021-09-29T06:28:20.000Z
package frodez.util.common; import frodez.constant.settings.DefStr; import java.nio.charset.CharsetEncoder; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collection; import lombok.experimental.UtilityClass; /** * 字符串处理工具类 * @author Frodez * @date 2019-03-27 */ @UtilityClass public class StrUtil { private static final CharsetEncoder ASCII_ENCODER = StandardCharsets.US_ASCII.newEncoder(); public static void main(String[] args) { } /** * 将空字符串转换为null * @author Frodez * @date 2019-12-07 */ public static String orNull(String string) { if (string == null) { return null; } return string.isEmpty() ? null : string; } /** * 将null转换为空字符串 * @author Frodez * @date 2019-12-07 */ public static String orEmpty(String string) { return string == null ? DefStr.EMPTY : string; } /** * 批量拼接字符串。<br> * 注意:<strong>当输入的字符串数组中某处为null时,会抛出异常.</strong><br> * 经测试,在绝大多数场景下相对jdk的实现更快(平均20-30%左右),在最坏情况下也与其相当。<br> * 与StringBuilder的非优化使用方式相比,性能提高从20%-70%不等。当拼接的字符串长度较长,或者字符串数组长度较长时,性能优势更大。 * @see java.lang.String#concat(String) * @author Frodez * @date 2019-04-01 */ public static String concat(String... strings) { if (EmptyUtil.yes(strings)) { throw new IllegalArgumentException("it isn't suitable for empty string."); } int length = strings.length; if (length == 1) { return strings[0]; } int size = 0; for (int i = 0; i < strings.length; i++) { //如果字符串数组某处为null,会自动抛出异常 size = size + strings[i].length(); } StringBuilder builder = new StringBuilder(size); for (int i = 0; i < length; i++) { String string = strings[i]; if (string.isEmpty()) { continue; } builder.append(string); } return builder.toString(); } /** * 批量拼接字符串。<br> * 注意:<strong>当输入的字符串数组中某处为null时,会抛出异常.</strong><br> * 经测试,在绝大多数场景下相对jdk的实现更快(平均20-30%左右),在最坏情况下也与其相当。<br> * 与StringBuilder的非优化使用方式相比,性能提高从20%-70%不等。当拼接的字符串长度较长,或者字符串数组长度较长时,性能优势更大。 * @see java.lang.String#concat(String) * @author Frodez * @param <T> * @date 2019-04-01 */ public static String concat(Collection<String> strings) { if (EmptyUtil.yes(strings)) { throw new IllegalArgumentException("it isn't suitable for empty string."); } if (strings.size() == 1) { return strings.iterator().next(); } int size = 0; for (String string : strings) { //如果字符串数组某处为null,会自动抛出异常 size = size + string.length(); } StringBuilder builder = new StringBuilder(size); for (String string : strings) { if (string.isEmpty()) { continue; } builder.append(string); } return builder.toString(); } /** * 优雅join,专门处理null和空字符串<br> * <strong>如果不需要处理null和空字符串,请不要用本方法!!!</strong> * @author Frodez * @date 2019-12-14 */ public static String join(CharSequence delimiter, CharSequence... elements) { CharSequence[] strings = EmptyUtil.trim(true, elements); return strings.length == 0 ? DefStr.EMPTY : String.join(delimiter, strings); } /** * 首字母大写 * @author Frodez * @date 2019-04-15 */ public static String upperFirst(String string) { if (EmptyUtil.yes(string)) { throw new IllegalArgumentException("it isn't suitable for empty string."); } StringBuilder builder = new StringBuilder(string.length()); upper(builder, string, 0); return builder.toString(); } /** * 首字母小写 * @author Frodez * @date 2019-04-15 */ public static String lowerFirst(String string) { if (EmptyUtil.yes(string)) { throw new IllegalArgumentException("it isn't suitable for empty string."); } StringBuilder builder = new StringBuilder(string.length()); lower(builder, string, 0); return builder.toString(); } private void upper(StringBuilder builder, String string, int start) { int end = string.length(); if (start == end) { return; } builder.append(Character.toUpperCase(string.charAt(0))); if (start + 1 < end) { builder.append(string.substring(start + 1)); } } private void upper(StringBuilder builder, String string, int start, int end) { if (start == end) { return; } builder.append(Character.toUpperCase(string.charAt(0))); if (start + 1 < end) { builder.append(string.substring(start + 1, end)); } } private void lower(StringBuilder builder, String string, int start) { int end = string.length(); if (start == end) { return; } builder.append(Character.toLowerCase(string.charAt(0))); if (start + 1 < end) { builder.append(string.substring(start + 1)); } } private void lower(StringBuilder builder, String string, int start, int end) { if (start == end) { return; } builder.append(Character.toLowerCase(string.charAt(0))); if (start + 1 < end) { builder.append(string.substring(start + 1, end)); } } /** * 转换为驼峰命名法<br> * 默认以"-"为分隔符,将首字母变为小写,将之后的每个分词的首字母变为大写。如果分隔符无效,则会将首字母变为小写。<br> * @author Frodez * @date 2019-04-17 */ public static String toCamelCase(String string) { return toCamelCase("-", string); } /** * 转换为驼峰命名法<br> * 以设定的分隔符作为标准,将首字母变为小写,将之后的每个分词的首字母变为大写。如果分隔符无效,则会将首字母变为小写。<br> * @author Frodez * @date 2019-04-17 */ public static String toCamelCase(String delimiter, String string) { if (string == null || delimiter == null) { throw new IllegalArgumentException("when string is null, delimiter can't be null either."); } StringBuilder builder = new StringBuilder(string.length()); int from = builder.indexOf(delimiter); if (from < 0) { //未找到分隔符,直接将原字符串首字母小写。 lower(builder, string, 0); return builder.toString(); } lower(builder, string, 0, from); int skip = delimiter.length(); //上个分隔符的结束处 from = from + skip; while (true) { //下个分隔符的起始处 int next = string.indexOf(delimiter, from); if (next < 0) { //如果未找到下个分隔符 upper(builder, string, from); break; } else { //如果找到了 upper(builder, string, from, next); from = next + skip; } } return builder.toString(); } /** * 不使用正则表达式的spilt * @author Frodez * @date 2019-12-24 */ public static String[] split(String delimiter, String string) { int from = string.indexOf(delimiter); if (from < 0) { //未找到 return new String[] { string }; } //如果找到,则分割 int skip = delimiter.length(); //可能的长度 StringArray builder = new StringArray(string.length() / (skip << 2)); //加入第一段 builder.append(string.substring(0, from)); //上个分隔符的结束处 from = from + skip; while (true) { //下个分隔符的起始处 int next = string.indexOf(delimiter, from); if (next < 0) { //如果未找到下个分隔符 if (from != string.length()) { builder.append(string.substring(from)); } break; } else { //说明两个分隔符之间有字符 if (next != from) { builder.append(string.substring(from, next)); } from = next + skip; } } return builder.finish(); } /** * 可变长字符数组 * @author Frodez * @date 2019-12-24 */ private static class StringArray { //设置一个稍小的值,毕竟用不到那么多 private static final int MAX_ARRAY_SIZE = 65536; /** * 数据 */ private String[] elements; /** * 总容量 */ private int length; /** * 当前头部位置(elements[head]为null) */ private int head; /** * 按照设置初始化 * @param initialLength 基础容量 */ public StringArray(int initialLength) { length = initialLength; elements = new String[length]; head = 0; } /** * 添加数据 * @author Frodez * @date 2019-12-24 */ public void append(String data) { if (data == null) { throw new NullPointerException(); } if (head == length) { elements = grow(); } elements[head++] = data; } private String[] grow() { if (length > MAX_ARRAY_SIZE) { throw new RuntimeException("size must be no more than" + MAX_ARRAY_SIZE); } length = length << 1; return Arrays.copyOf(elements, length); } /** * 转换为数组 * @author Frodez * @date 2019-12-24 */ public String[] finish() { return length == head ? elements : Arrays.copyOf(elements, head); } } /** * 是否为ascii字符串 * @author Frodez * @date 2019-12-07 */ public boolean isAscii(String string) { return ASCII_ENCODER.canEncode(string); } }
23.709859
95
0.621599
1aba62a7150a747fdbf5cae91a58b58cf15ed574
3,250
kt
Kotlin
agp-7.1.0-alpha01/tools/base/lint/libs/lint-checks/src/main/java/com/android/tools/lint/checks/PrivateApiParser.kt
jomof/CppBuildCacheWorkInProgress
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
[ "Apache-2.0" ]
null
null
null
agp-7.1.0-alpha01/tools/base/lint/libs/lint-checks/src/main/java/com/android/tools/lint/checks/PrivateApiParser.kt
jomof/CppBuildCacheWorkInProgress
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
[ "Apache-2.0" ]
null
null
null
agp-7.1.0-alpha01/tools/base/lint/libs/lint-checks/src/main/java/com/android/tools/lint/checks/PrivateApiParser.kt
jomof/CppBuildCacheWorkInProgress
9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.lint.checks import java.io.InputStream class PrivateApiParser { val classes = HashMap<String, PrivateApiClass>(24000) val containers = HashMap<String, ApiClassOwner<PrivateApiClass>>(7000) fun parse(stream: InputStream) { stream.bufferedReader(Charsets.UTF_8).forEachLine { line -> val items = line.split(",", "->") if (items.size < 3) return@forEachLine val className = items[0].fromSignature() // Skip adding $$Lambda entries and allowed items. if (className.contains("${"$$"}Lambda")) return@forEachLine val restriction = parse(items[2]) if (restriction == Restriction.ALLOW || restriction == Restriction.UNKNOWN ) return@forEachLine val clazz = classes.getOrPut(className) { addClass(className) } val member = items[1] when { member.contains(":") -> { // field val parts = member.split(":") clazz.addField(parts[0], restriction) } member.contains("(") -> { // method clazz.addMethod(member.substring(0, member.indexOf(')') + 1), restriction) } else -> System.out.println("Unrecognized entry: $line") } } } private fun addClass(name: String): PrivateApiClass { // There should not be any duplicates. var cls: PrivateApiClass? = classes[name] assert(cls == null) cls = PrivateApiClass(name) val containerName = cls.containerName val len = containerName.length val isClass = len < name.length && name[len] == '$' var container: ApiClassOwner<PrivateApiClass>? = containers[containerName] if (container == null) { container = ApiClassOwner(containerName, isClass) containers[containerName] = container } else if (container.isClass != isClass) { throw RuntimeException("\"$containerName\" is both a package and a class") } container.addClass(cls) return cls } } private fun String.fromSignature(): String = if (startsWith("L") && endsWith(";")) substring(1, length - 1) else this private fun parse(name: String): Restriction = when (name) { "WHITE" -> Restriction.ALLOW "BLACK" -> Restriction.DENY "GREY" -> Restriction.MAYBE "GREY_MAX_O" -> Restriction.MAYBE_MAX_O "GREY_MAX_P" -> Restriction.MAYBE_MAX_P else -> Restriction.UNKNOWN }
36.111111
94
0.609538
e566d09f2ffd95f0d49f14a5789f874a21f9bc0e
238
tsx
TypeScript
src/background/index.tsx
ayoung19/clipboard-history
e60691611f0d8c27a2b1b92debe267786b5b6c40
[ "MIT" ]
null
null
null
src/background/index.tsx
ayoung19/clipboard-history
e60691611f0d8c27a2b1b92debe267786b5b6c40
[ "MIT" ]
null
null
null
src/background/index.tsx
ayoung19/clipboard-history
e60691611f0d8c27a2b1b92debe267786b5b6c40
[ "MIT" ]
null
null
null
import * as React from "react"; import * as ReactDOM from "react-dom"; import { Background } from "./Background"; ReactDOM.render( <React.StrictMode> <Background /> </React.StrictMode>, document.getElementById("background") );
21.636364
42
0.697479
33bccb43b6e3f8645af12543c976bdc1dc02f7da
1,844
dart
Dart
lib/main.dart
ddmgy/infection
ca0ea3758d67b86c47fe7e0ced8cfd60ac447162
[ "MIT" ]
null
null
null
lib/main.dart
ddmgy/infection
ca0ea3758d67b86c47fe7e0ced8cfd60ac447162
[ "MIT" ]
null
null
null
lib/main.dart
ddmgy/infection
ca0ea3758d67b86c47fe7e0ced8cfd60ac447162
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:infection/route/fade_transition_page_route.dart'; import 'package:infection/route/game_arguments.dart'; import 'package:infection/route/game_screen.dart'; import 'package:infection/route/home_screen.dart'; import 'package:infection/route/routes.dart'; import 'package:infection/route/setup_screen.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); return MaterialApp( title: 'Infection', theme: ThemeData.dark().copyWith( primaryColor: Colors.grey, visualDensity: VisualDensity.adaptivePlatformDensity, ), initialRoute: Routes.home, onGenerateRoute: (RouteSettings settings) { switch (settings.name) { case Routes.home: return FadeTransitionPageRoute( settings: settings, builder: (_) => HomeScreen(), ); break; case Routes.setup: return FadeTransitionPageRoute( settings: settings, builder: (_) => SetupScreen(), ); break; case Routes.game: GameArguments argument = settings.arguments; return FadeTransitionPageRoute( settings: settings, builder: (_) => GameScreen( columns: argument.columns, rows: argument.rows, players: argument.players, ), ); break; default: throw Exception("Unknown route name: ${settings.name}"); } }, supportedLocales: [ const Locale("en"), ], ); } }
30.229508
74
0.601952
9bf2d197307f4244ad89b8986817e7cd9a78ae25
316
dart
Dart
FlutArt/001-Ressources/dartpadcode/streams/clickforever.dart
nicode-io/The_Medior_Way
bd25312548828f955a3348cabebdf9a1f04aa73f
[ "MIT" ]
null
null
null
FlutArt/001-Ressources/dartpadcode/streams/clickforever.dart
nicode-io/The_Medior_Way
bd25312548828f955a3348cabebdf9a1f04aa73f
[ "MIT" ]
null
null
null
FlutArt/001-Ressources/dartpadcode/streams/clickforever.dart
nicode-io/The_Medior_Way
bd25312548828f955a3348cabebdf9a1f04aa73f
[ "MIT" ]
null
null
null
import 'dart:html'; void main() { final ButtonElement button = querySelector('button'); button.onClick .timeout( new Duration(seconds: 1), onTimeout: (sink) => sink.addError('Too slow'), ) .listen( (event) {}, onError: (err) => print('You goofed'), ); }
19.75
55
0.541139
aaf804be4a43d8b42668e104a2e6705a5f68cfcc
892
sql
SQL
payara5/h2db/src/test/org/h2/test/scripts/functions/aggregate/min.sql
GiorgioCaculli/B3_Application_Entreprise_Multi-Tiers_et_Veille_Technologique
048fcd7d012dfa9986b4dda87ed9e6eee7c4b3a6
[ "BSD-3-Clause" ]
null
null
null
payara5/h2db/src/test/org/h2/test/scripts/functions/aggregate/min.sql
GiorgioCaculli/B3_Application_Entreprise_Multi-Tiers_et_Veille_Technologique
048fcd7d012dfa9986b4dda87ed9e6eee7c4b3a6
[ "BSD-3-Clause" ]
null
null
null
payara5/h2db/src/test/org/h2/test/scripts/functions/aggregate/min.sql
GiorgioCaculli/B3_Application_Entreprise_Multi-Tiers_et_Veille_Technologique
048fcd7d012dfa9986b4dda87ed9e6eee7c4b3a6
[ "BSD-3-Clause" ]
null
null
null
-- Copyright 2004-2019 H2 Group. Multiple-Licensed under the MPL 2.0, -- and the EPL 1.0 (https://h2database.com/html/license.html). -- Initial Developer: H2 Group -- -- with filter condition create table test(v int); > ok insert into test values (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11), (12); > update count: 12 select min(v), min(v) filter (where v >= 4) from test where v >= 2; > MIN(V) MIN(V) FILTER (WHERE (V >= 4)) > ------ ------------------------------ > 2 4 > rows: 1 create index test_idx on test(v); > ok select min(v), min(v) filter (where v >= 4) from test where v >= 2; > MIN(V) MIN(V) FILTER (WHERE (V >= 4)) > ------ ------------------------------ > 2 4 > rows: 1 select min(v), min(v) filter (where v >= 4) from test; > MIN(V) MIN(V) FILTER (WHERE (V >= 4)) > ------ ------------------------------ > 1 4 > rows: 1 drop table test; > ok
24.108108
86
0.508969
1efe99de6596818d28d69b0d008b4d46439bd925
789
swift
Swift
FinancialApp/Model/Compute.swift
sriThariduSangeeth/FinancialApp
636073963ed1b3ef097b637ddcab99de789a7c83
[ "MIT" ]
null
null
null
FinancialApp/Model/Compute.swift
sriThariduSangeeth/FinancialApp
636073963ed1b3ef097b637ddcab99de789a7c83
[ "MIT" ]
null
null
null
FinancialApp/Model/Compute.swift
sriThariduSangeeth/FinancialApp
636073963ed1b3ef097b637ddcab99de789a7c83
[ "MIT" ]
null
null
null
// // Compute.swift // FinancialApp // // Created by Dilan Tharidu Sangeeth on 2/27/20. // Copyright © 2020 Dilan Tharidu Sangeeth. All rights reserved. // import UIKit class Compute { let name : String let cellIcon : UIImage let cellColor : UIColor let cellId : String init(name : String , cellIcon: UIImage , cellColor: UIColor , cellId : String) { self.name = name self.cellColor = cellColor self.cellIcon = cellIcon self.cellId = cellId } func getname() -> String { return name } func getCellIcon() -> UIImage { return cellIcon } func getCellColor() -> UIColor { return cellColor } func getCellId() -> String { return cellId } }
19.243902
84
0.579214
5e90933978f22320091a30e2c99e8baa38670918
2,655
asm
Assembly
cpm/ndos/necho.asm
erikp9000/cpm-ndos
d2e17f3aa11e22d30510278e78814151934355d2
[ "MIT" ]
null
null
null
cpm/ndos/necho.asm
erikp9000/cpm-ndos
d2e17f3aa11e22d30510278e78814151934355d2
[ "MIT" ]
7
2020-06-03T01:12:06.000Z
2020-06-12T19:11:33.000Z
cpm/ndos/necho.asm
erikp9000/cpm-ndos
d2e17f3aa11e22d30510278e78814151934355d2
[ "MIT" ]
null
null
null
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; ;; NECHO.ASM ;; ;; NDOS Message echo ;; ;; On start, dma contains command line argument length byte ;; and command line. ;; Stack pointer should be within CCP. ;; Check for NDOS; display error if not running. ;; Copy command line arguments to buf and call NDOS to send it. ;; Call NDOS to receive response. ;; On a=0(success), print response. ;; On a=0FFh(failure), print error. ;; maclib ndos org tpa start: lxi h,0 dad sp ; hl = sp shld savestack ; save original stack pointer lxi sp,stack mvi c,n?ver call bdosv cpi 10h jc nondos ; NDOS is present ; copy command line args from dmabuf lxi d,msgbuf+2 ; point to start of data lxi h,defdma ; command-line mov a,m ; command-line length ora a jz dousage mov c,a loop: inx h mov a,m stax d inx d dcr c jnz loop lda defdma adi 3 ; include LEN, CMD, and CHK bytes sta msgbuf loop1: mvi c,n?smsg lxi d,msgbuf call bdosv ; send message to server mvi c,n?rmsg lxi d,buffer call bdosv ; get response ora a jnz timeout ; print response from server lda buffer ; get LEN byte dcr a ; subtract 1 mov e,a mvi d,0 lxi h,buffer dad d ; de is pointing to CHK byte mvi m,'$' ; terminate the string lxi d,buffer+2 ; point to first byte of response (ECHO doesn't have a Status byte) mvi c,prnstr call bdosv ; print the response lxi d,crlf mvi c,prnstr call bdosv ; print CR, LF ; loop if there's no keypress from the console mvi c,constat call bdosv ora a jz loop1 mvi c,conin call bdosv ; remove the keypress so it's not waiting for the CCP jmp quit ; NDOS not found nondos: mvi c,prnstr lxi d,nondoserr call bdosv jmp quit ; Timeout contacting server timeout:mvi c,prnstr lxi d,toerr call bdosv jmp quit ; Error status from server serverr:mvi c,prnstr lxi d,serr call bdosv jmp quit ; Print usage dousage: mvi c, prnstr lxi d,usage call bdosv quit: lhld savestack sphl ; sp = hl ret ; quit nondoserr: db 'NDOS not loaded',cr,lf,'$' toerr: db 'Timeout',cr,lf,'$' serr: db 'Directory not found',cr,lf,'$' usage: db 'necho <text to send to server>' crlf: db cr,lf,'$' ;; NDOS request message msgbuf: db 0 ; LEN db NECHO ; CMD ds 148 ; DATA and CHK ;; NDOS response buffer buffer: ds 150 savestack: dw 0 ds 16 stack: end start
18.964286
84
0.592844
7dad4f39bd0796eb24328669190598f138890375
816
lua
Lua
Cuboid.lua
krokoschlange/fysiks
d62fc6ea9a4e525aa9c6e46f56042a0c7df869d6
[ "MIT" ]
6
2021-04-26T17:41:25.000Z
2022-02-06T21:02:41.000Z
Cuboid.lua
krokoschlange/fysiks
d62fc6ea9a4e525aa9c6e46f56042a0c7df869d6
[ "MIT" ]
null
null
null
Cuboid.lua
krokoschlange/fysiks
d62fc6ea9a4e525aa9c6e46f56042a0c7df869d6
[ "MIT" ]
2
2021-07-30T03:24:41.000Z
2022-03-13T23:38:43.000Z
fysiks.Cuboid = fysiks.FullPolyhedron:new(nil, {}, {}, {}) fysiks.Cuboid.__index = fysiks.Cuboid function fysiks.Cuboid:new(obj, min, max) local verts = { {x = min.x, y = min.y, z = min.z}, {x = min.x, y = min.y, z = max.z}, {x = min.x, y = max.y, z = min.z}, {x = min.x, y = max.y, z = max.z}, {x = max.x, y = min.y, z = min.z}, {x = max.x, y = min.y, z = max.z}, {x = max.x, y = max.y, z = min.z}, {x = max.x, y = max.y, z = max.z}, } local edges = { {1, 2}, {2, 4}, {4, 3}, {3, 1}, {5, 6}, {6, 8}, {8, 7}, {7, 5}, {1, 5}, {2, 6}, {3, 7}, {4, 8}, } local faces = { {1, 2, 3, 4}, {1, 2, 5, 6}, {1, 3, 5, 7}, {2, 4, 6, 8}, {3, 4, 7, 8}, {5, 6, 7, 8}, } local c = fysiks.FullPolyhedron:new(obj, verts, edges, faces) c = setmetatable(c, self) return c end
19.902439
62
0.458333
5bed6c4058232be3188ffdca1590e0518905781b
1,672
c
C
MultiSource/Benchmarks/Prolangs-C/TimberWolfMC/neworient.c
gmlueck/llvm-test-suite
7ff842b8fec970561fed78c9347e496538cf74f5
[ "Apache-2.0" ]
70
2019-01-15T03:03:55.000Z
2022-03-28T02:16:13.000Z
MultiSource/Benchmarks/Prolangs-C/TimberWolfMC/neworient.c
gmlueck/llvm-test-suite
7ff842b8fec970561fed78c9347e496538cf74f5
[ "Apache-2.0" ]
519
2020-09-15T07:40:51.000Z
2022-03-31T20:51:15.000Z
MultiSource/Benchmarks/Prolangs-C/TimberWolfMC/neworient.c
gmlueck/llvm-test-suite
7ff842b8fec970561fed78c9347e496538cf74f5
[ "Apache-2.0" ]
117
2020-06-24T13:11:04.000Z
2022-03-23T15:44:23.000Z
#include "custom.h" int newOrient( CELLBOXPTR cellptr , int range ) { int incidence , count , i , orient ; orient = cellptr->orient ; if( range == 4 ) { if( orient >= 4 ) { count = 0 ; for( i = 0 ; i <= 3 ; i++ ) { if( cellptr->orientList[i] == 1 ) { count++ ; } } if( count == 0 ) { return( -1 ) ; } do { incidence = (int) ( (double) count * ( (double) RAND / (double) 0x7fffffff ) ) + 1 ; } while( incidence == count + 1 ) ; count = 0 ; for( i = 0 ; i <= 3 ; i++ ) { if( cellptr->orientList[i] == 1 ) { if( ++count == incidence ) { return( i ) ; } } } } else { count = 0 ; for( i = 4 ; i <= 7 ; i++ ) { if( cellptr->orientList[i] == 1 ) { count++ ; } } if( count == 0 ) { return( -1 ) ; } do { incidence = (int) ( (double) count * ( (double) RAND / (double) 0x7fffffff ) ) + 1 ; } while( incidence == count + 1 ) ; count = 0 ; for( i = 4 ; i <= 7 ; i++ ) { if( cellptr->orientList[i] == 1 ) { if( ++count == incidence ) { return( i ) ; } } } } } else { count = 0 ; for( i = 0 ; i <= 7 ; i++ ) { if( i == orient ) { continue ; } if( cellptr->orientList[i] == 1 ) { count++ ; } } if( count == 0 ) { return( -1 ) ; } do { incidence = (int) ( (double) count * ( (double) RAND / (double) 0x7fffffff ) ) + 1 ; } while( incidence == count + 1 ) ; count = 0 ; for( i = 0 ; i <= 7 ; i++ ) { if( i == orient ) { continue ; } if( cellptr->orientList[i] == 1 ) { if( ++count == incidence ) { return( i ) ; } } } } /*NOTREACHED*/ }
17.978495
47
0.429426
cb5202749bb65b455f4d3a426bebfab0a85caf8a
3,375
h
C
src/engine.h
lavima/GaME
f816dff62c731e0f807b00300a061d45e7ffd93b
[ "MIT" ]
null
null
null
src/engine.h
lavima/GaME
f816dff62c731e0f807b00300a061d45e7ffd93b
[ "MIT" ]
null
null
null
src/engine.h
lavima/GaME
f816dff62c731e0f807b00300a061d45e7ffd93b
[ "MIT" ]
null
null
null
/* File: Engine.h Author: Lars Vidar Magnusson */ #pragma once namespace game { #define ENGINE_NAME "GaME" #define ENGINE_DESCRIPTION "GaME Mechanics Engine" #define ENGINE_VERSION Version(0, 0, 1) #define ENGINEOPTION_CONFIG "engineConfig" #define ENGINEOPTION_CONFIG_FILENAME "engineLogFilename" /* * EngineInfo provides engine_ meta information at runtime. Allthough this class * derives from VersionInfo, an XML serializable type, this functionality is never * utilized i.e. the information is provided either at compile time or at runtime. */ class GAME_API EngineInfo : public VersionInfo { friend class Engine; private: std::string executablePath; public: EngineInfo() : VersionInfo(ENGINE_NAME, ENGINE_DESCRIPTION, ENGINE_VERSION) {} const std::string& GetExecutablePath() const { return executablePath; } }; enum class GAME_API EngineStatus { Created = 0, Initialized = 1, Terminated = 2 }; /* * The Engine class represents the actual Game Mechanics Engine (GaME). */ class GAME_API Engine { private: EngineInfo info_; EngineStatus status_; std::string config_filename_; std::unique_ptr<EngineConfig> config_; std::vector<addin::Addin*> addins_; std::unordered_map<std::string, std::unique_ptr<framework::System>> systems_; std::unordered_map<std::string, framework::System*> systems_by_type_; std::unordered_map<std::string, std::vector<std::reference_wrapper<framework::Component>>> components_by_name_; std::unordered_map<std::string, std::vector<std::reference_wrapper<framework::Component>>> components_by_type_; scripting::ScriptEnvironment* script_environment_; std::unique_ptr<platform::Platform> platform_; Log* log_; std::unique_ptr<std::ofstream> log_file_; std::unique_ptr<framework::Game> game_; public: Engine(); ~Engine(); bool Initialize(); void Run(); void Stop(); bool LoadGame(const std::string& filename); bool LoadGame(framework::Game& game); void UnloadGame(); bool LoadAddin(const std::string& filename); bool HasSystemType(const std::string& type_name) const; bool LoadSystem(framework::SystemConfig& system_config); std::optional<std::reference_wrapper<framework::System>> GetSystemByName(const std::string& name); std::optional<std::reference_wrapper<framework::System>> GetSystemByType(const std::string& type_name); std::optional<const std::vector<std::reference_wrapper<framework::Component>>> GetComponentsByName(const std::string& name); std::optional<const std::vector<std::reference_wrapper<framework::Component>>> GetComponentsByType(const std::string& type_name); const EngineInfo& GetInfo(); scripting::ScriptEnvironment& GetScriptEnvironment(); platform::Platform& GetPlatform(); framework::Game& GetGame(); Log& GetLog(); private: void UpdateComponentsCache(); void shutdown(); class Scriptable : public scripting::_Scriptable { public: void Register(scripting::ScriptEnvironment& environment) override; }; }; }
28.125
137
0.668148
0a0596f36dad84bc4f0242a0b8723a3294fe594a
8,438
c
C
sources/physics/collision.c
KernelOverseer/KSICARDOOM
08bef9229b05a3229288777bf187e2b84fe5a6a0
[ "MIT" ]
16
2020-05-11T23:12:16.000Z
2021-04-19T18:28:15.000Z
sources/physics/collision.c
KernelOverseer/KSICARDOOM
08bef9229b05a3229288777bf187e2b84fe5a6a0
[ "MIT" ]
4
2020-05-06T21:22:11.000Z
2020-05-20T17:46:59.000Z
sources/physics/collision.c
KernelOverseer/KSICARDOOM
08bef9229b05a3229288777bf187e2b84fe5a6a0
[ "MIT" ]
null
null
null
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* collision.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: abiri <abiri@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/04 16:25:49 by msidqi #+# #+# */ /* Updated: 2020/10/24 19:11:57 by abiri ### ########.fr */ /* */ /* ************************************************************************** */ #include "physics_engine.h" #define INTER_DISTANCE 10 #define INTERSECTION_MARGIN 10 int ft_switch_body_sector(t_body *body, t_sector *new_sector) { t_list_node *list_node; if (body->player->sprite) { list_node = body->player->sector->sprites.first; while (list_node) { if (list_node->content == body->player->sprite) { ttslist_splice(&body->player->sector->sprites, list_node); new_sector->sprites.push(&new_sector->sprites, body->player->sprite); break; } list_node = list_node->next; } } body->player->sector = new_sector; return (0); } int ft_step_effect(t_body *body) { body->velocity.z += JUMP_POWER; return (0); } int ft_set_new_intersection_slide_velocity(t_body *body, t_intersect inter, double delta_time) { t_vec2 new_position_vector; t_vec2 wall_push_vector; t_vec2 orthogonal_projection; double orthogonal_dot; t_vec2 normalized_wall; double new_velocity_scalar; t_vec2 new_velocity; double distance_to_corner; t_wall *virtual_wall; if (inter.object.type == OBJECT_wall) virtual_wall = inter.object.object.wall; else if (inter.object.type == OBJECT_portal) virtual_wall = &inter.object.object.portal->wall; else return (0); if (virtual_wall->props & PROP_NO_CLIP) return (0); normalized_wall = ft_vec2_normalize((t_vec2){virtual_wall->p2.x - virtual_wall->p1.x, virtual_wall->p2.y - virtual_wall->p1.y}); orthogonal_dot = ft_vec2_dot_product((t_vec2){body->pos.x - virtual_wall->p1.x, body->pos.y - virtual_wall->p1.y}, normalized_wall); orthogonal_projection = ft_vec2_scalar(normalized_wall, orthogonal_dot); orthogonal_projection = (t_vec2){virtual_wall->p1.x + orthogonal_projection.x, virtual_wall->p1.y + orthogonal_projection.y}; wall_push_vector = ft_vec2_scalar(ft_vec2_normalize((t_vec2){body->pos.x - orthogonal_projection.x, body->pos.y - orthogonal_projection.y}), INTERSECTION_MARGIN); new_velocity_scalar = ft_vec2_dot_product((t_vec2){body->velocity.x, body->velocity.y}, normalized_wall); new_velocity = ft_vec2_scalar(normalized_wall, new_velocity_scalar); body->velocity = (t_vec3){new_velocity.x, new_velocity.y, body->velocity.z}; distance_to_corner = ft_max(ft_vec2_mag((t_vec2){virtual_wall->p1.x - inter.pos.x, virtual_wall->p1.y - inter.pos.y}), ft_vec2_mag((t_vec2){virtual_wall->p2.x - inter.pos.x, virtual_wall->p2.y - inter.pos.y})); if (distance_to_corner < INTERSECTION_MARGIN) { body->velocity.x = 0; body->velocity.y = 0; } return (1); } void ft_apply_intersection_event(t_body *body, t_intersect inter) { t_sprite temp_sprite; t_body *inter_body; t_intersect temp_intersect; if (body->events.on_intersect) body->events.on_intersect(body, inter); if (inter.object.type == OBJECT_sprite && inter.object.object.sprite->parent_type == PARENT_TYPE_BODY) { temp_intersect = inter; temp_sprite.parent_type = 0; temp_intersect.object.object.sprite = &temp_sprite; inter_body = inter.object.object.sprite->parent; temp_intersect.object.object.sprite->parent = body; if (inter_body->events.on_intersect) inter_body->events.on_intersect(inter_body, inter); } } int ft_floor_ceiling_intersections(t_vec3 next_position, t_body *body) { // Floor and Ceiling intersection check // Floor intersection if (next_position.z <= body->player->sector->floor_height) { body->player->input_velocity.x *= body->friction; body->player->input_velocity.y *= body->friction; body->player->is_grounded = true; body->player->input_velocity.z = 0; body->velocity.z = 0; body->gravity = ZERO_VEC3; body->pos.z = body->player->sector->floor_height; return (1); } // Ceiling intersection if (next_position.z + body->player->height[1] >= DEFAULT_WALL_HEIGHT + body->player->sector->ceil_height) { body->player->input_velocity.z = 0; body->velocity.z = 0; body->pos.z = DEFAULT_WALL_HEIGHT + body->player->sector->ceil_height - body->player->height[1]; return (1); } return (0); } int ft_portal_intersections(t_intersect inter, t_body *body, double delta_time) { // intersection with portal top double head_altitude; double bottom_altitude; double portal_top_altitude = ft_max(body->player->sector->ceil_height, inter.object.object.portal->sector->ceil_height) + DEFAULT_WALL_HEIGHT; double portal_bottom_altitude = ft_min(body->player->sector->floor_height, inter.object.object.portal->sector->floor_height); head_altitude = body->pos.z + body->player->height[1]; bottom_altitude = body->pos.z; if (head_altitude > portal_top_altitude) return (ft_set_new_intersection_slide_velocity(body, inter, delta_time)); else if (bottom_altitude < portal_bottom_altitude) { if (bottom_altitude - portal_bottom_altitude <= STEP_MAX_HEIGHT) ft_step_effect(body); return (ft_set_new_intersection_slide_velocity(body, inter, delta_time)); } else ft_switch_body_sector(body, inter.object.object.portal->sector); return (0); } int ft_sprite_intersections(t_intersect inter, t_body *body, double delta_time) { double head_altitude; double bottom_altitude; if (inter.object.object.sprite->props & PROP_NO_CLIP) return (0); head_altitude = body->pos.z + body->player->height[1]; bottom_altitude = body->pos.z; if (head_altitude < inter.object.object.sprite->altitude || bottom_altitude > inter.object.object.sprite->altitude + inter.object.object.sprite->height) return (0); body->velocity.x = 0; body->velocity.y = 0; return (1); } void ft_body_collision(t_graphical_scene *scene, t_body *body, double delta_time) { t_vec3 next_position; next_position = (t_vec3){body->pos.x + body->velocity.x * delta_time, body->pos.y + body->velocity.y * delta_time, body->pos.z + body->velocity.z * delta_time}; t_intersect inter; t_vec3 future_pos; t_vec3 stopping_pos; if (ft_floor_ceiling_intersections(next_position, body)) ft_apply_intersection_event(body, inter); inter.distance = INFINITY; inter.min_dist = 0; inter.ray.origin = (t_vec2){body->pos.x, body->pos.y}; inter.ray.dir = ft_vec2_normalize((t_vec2){body->velocity.x, body->velocity.y}); ft_intersect_ray(scene, &inter, body->player->sector); while (inter.object.type) { double distance_to_next_position = ft_vec2_mag((t_vec2){next_position.x - body->pos.x, next_position.y - body->pos.y}); double distance_to_intersection = ft_vec2_mag((t_vec2){inter.pos.x - body->pos.x, inter.pos.y - body->pos.y}); if (inter.object.type) { if (inter.object.type == OBJECT_portal) { if (distance_to_intersection <= distance_to_next_position) { if (ft_portal_intersections(inter, body, delta_time)) ft_apply_intersection_event(body, inter); } } else if (inter.object.type == OBJECT_wall) { // Normal wall intersection behaviour if (distance_to_intersection <= distance_to_next_position + body->player->height[0] / 2) { ft_apply_intersection_event(body, inter); ft_set_new_intersection_slide_velocity(body, inter, delta_time); } } else if (inter.object.type == OBJECT_sprite) { double sprite_radius; if (inter.object.object.sprite->props & PROP_FIXED_ANGLE) sprite_radius = 0; else sprite_radius = inter.object.object.sprite->radius; if (distance_to_intersection <= distance_to_next_position + body->player->height[0] / 2 + sprite_radius) { if (ft_sprite_intersections(inter, body, delta_time)) ft_apply_intersection_event(body, inter); } } } inter.min_dist = distance_to_intersection; ft_intersect_ray(scene, &inter, body->player->sector); } }
36.37069
163
0.670301
e50ce2c83314a39a6bcd456737d78c77d653d978
6,648
html
HTML
www/iglesias.html
darwinv/debugeclesiastica
e1a2c0718189a57b4464dcfb5c7219eb63cf203c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
www/iglesias.html
darwinv/debugeclesiastica
e1a2c0718189a57b4464dcfb5c7219eb63cf203c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
www/iglesias.html
darwinv/debugeclesiastica
e1a2c0718189a57b4464dcfb5c7219eb63cf203c
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
<div id="iglesias" data-role="page" data-theme='b'> <div data-role="header" data-theme='b'> <!-- data-add-back-btn="true" --> <h1>Iglesias</h1> <a href="index.html" data-shadow="false" data-iconshadow="false" data-icon="arrow-l" class="ui-alt-icon ui-nodisc-icon" data-iconpos="notext" data-rel="back" data-ajax="false">Back</a> </div> <div data-role="content" class="home-content"> <ul data-role="listview" data-split-icon="custom" data-filter="true" data-filter-placeholder="Buscar Iglesias..." data-inset="true"> <!-- Iglesias de San Cristobal --> <li> <a href="descripciones/catedral-sancristobal.html"> <img src="imgs/th-catedral-sancristobal.jpg"> <h3>Catedral de San Cristobal</h3> <p>San Cristobal</p></a> <a href="mapa/map-iglesias.html?latitud=7.765005&longitud=-72.235351"> </a> </li> <li class="lista-iglesias" data-lat="7.767333" data-lng="-72.230222" > <a href="descripciones/iglesia-sanjose.html"> <img src="imgs/th-igl-sanjose.jpg"> <h3>Iglesia San Jose</h3> <p>San Cristobal</p></a> <a href="mapa/map-iglesias.html?latitud=7.767333&longitud=-72.230222"></a> </li> <li> <a href="descripciones/sanjuan-bautista.html"> <img src="imgs/th-igl-sanjuanbautista3.jpg"> <h3>Iglesia San Juan Bautista</h3> <p>San Cristobal</p></a> <a href="mapa/map-iglesias.html?latitud=7.773194&longitud=-72.230222"></a> </li> <li><a href="descripciones/perpetuo-socorro.html"> <img src="imgs/th-igl-perpetuosocorro1.jpg"> <h3>Nuestra señora del perpetuo socorro</h3> <p>San Cristobal</p></a> <a href="mapa/map-iglesias.html?latitud=7.771750&longitud=-72.227556"></a> </li> <li><a href="descripciones/igl-elangel.html"> <img src="imgs/th-igl-elangel.jpg"> <h3>Iglesia Santo Domingo de Guzmán (EL ÁNGEL)</h3> <p>San Cristobal</p></a> <a href="mapa/map-iglesias.html?latitud=7.768738&longitud=-72.216997"></a> </li> <!-- Iglesias de Tariba --> <li><a href="descripciones/basilica-tariba.html"> <img src="imgs/th-igl-basilicatariba.jpg"> <h3>Basilica de Nuestra Señora de la Consolación de Táriba</h3> <p>Tariba</p></a> <a href="mapa/map-iglesias.html?latitud=7.817833&longitud=-72.226500"></a> </li> <!-- Iglesias de la Grita --> <li><a href="descripciones/basilica-espiritusanto.html"> <img src="imgs/th-igl-espiritusanto.jpg"> <h3>Basilica del Espíritu Santo</h3> <p>La Grita</p></a> <a href="mapa/map-iglesias.html?latitud=8.136861&longitud=-71.986389"></a> </li> <li><a href="descripciones/igl-losangeles.html"> <img src="imgs/th-igl-sralosangeles.jpg"> <h3>Iglesia Nuestra Señora de los Ángeles</h3> <p>La Grita</p></a> <a href="mapa/map-iglesias.html?latitud=8.135306&longitud=-71.984444"></a> </li> <!-- Iglesias Rubio --> <li><a href="descripciones/igl-rubio.html"> <img src="imgs/th-igl-stabarbara.jpg"> <h3>Iglesia Santa Barbara</h3> <p>Rubio</p></a> <a href="mapa/map-iglesias.html?latitud=7.705722&longitud=-72.358917"></a> </li> <li><a href="descripciones/igl-sanantonio.html"> <img src="imgs/th-igl-sanantoniodepadua.jpg"> <h3>Iglesia San Antonio de Padua</h3> <p>San Antonio del Táchira</p></a> <a href="mapa/map-iglesias.html?latitud=7.812944&longitud=-72.446472"></a> </li> <li><a href="descripciones/igl-sanagaton.html"> <img src="imgs/th-igl-sanagaton.jpg"> <h3>Iglesia San Agatón</h3> <p>Palmira</p></a> <a href="mapa/map-iglesias.html?latitud=7.838306?longitud=-72.228333"></a> </li> <li><a href="descripciones/igl-sanpedroapostol.html"> <img src="imgs/th-igl-sanpedroapostol.jpg"> <h3>Iglesia San Pedro Apóstol</h3> <p>Capacho Nuevo</p></a> <a href="mapa/map-iglesias.html?latitud=7.823917&longitud=-72.306639"></a> </li> <li><a href="descripciones/igl-seboruco.html"> <img src="imgs/th-igl-sanpedroseboruco.jpg"> <h3>Iglesia San Pedro de Seboruco</h3> <p>Seboruco</p></a> <a href="mapa/map-iglesias.html?latitud=8.145295&longitud=-72.072939"></a> </li> <li><a href="descripciones/igl-lobatera.html"> <img src="imgs/th-igl-lobatera.jpg"> <h3>Iglesia de Nuestra Señora del Rosario de Chiquinquirá</h3> <p>Lobatera</p></a> <a href="mapa/map-iglesias.html?latitud=7.930528&longitud=-72.247389"></a> </li> <li><a href="descripciones/igl-sanpedro.html"> <img src="imgs/th-igl-sanpedrodelrio.jpg"> <h3>Iglesia San Pedro</h3> <p>San Pedro del Rio</p></a> <a href="mapa/map-iglesias.html?latitud=7.992056&longitud=-72.272861"></a> </li> <li><a href="descripciones/igl-peribeca.html"> <img src="imgs/th-igl-peribeca.jpg"> <h3>Iglesia nuestra señora del Carmen</h3> <p>Peribeca</p></a> <a href="mapa/map-iglesias.html?latitud=7.831972&longitud=-72.284778"></a> </li> <li><a href="descripciones/igl-santana.html"> <img src="imgs/th-igl-santana.jpg"> <h3>Iglesia Santa Ana</h3> <p>Santa Ana</p></a> <a href="mapa/map-iglesias.html?latitud=7.644667&longitud=-72.276250"></a> </li> <li><a href="descripciones/igl-elcobre.html"> <img src="imgs/th-igl-elcobre.jpg"> <h3>Iglesia San Bartolomé de Vargas</h3> <p>El Cobre</p></a> <a href="mapa/map-iglesias.html?latitud=8.034833&longitud=-72.057639"></a> </li> <li><a href="descripciones/igl-sanjosedebolivar.html"> <img src="imgs/th-igl-sanjosebolivar.jpg"> <h3>Iglesia San Jose</h3> <p>San José de Bolívar</p></a> <a href="mapa/map-iglesias.html?latitud=7.911611&longitud=-71.973417"></a> </li> <li><a href="descripciones/igl-capachoviejo.html"> <img src="imgs/th-igl-sanegmidio.jpg"> <h3>Iglesia San Emigdio</h3> <p>Capacho Viejo</p></a> <a href="mapa/map-iglesias.html?latitud=7.822572?longitud=-72.321978"></a> </li> <li><a href="descripciones/igl-delicias.html"> <img src="imgs/th-igl-delicias.jpg"> <h3>Iglesia San Jose</h3> <p>Delicias</p></a> <a href="mapa/map-iglesias.html?latitud=7.564944&longitud=-72.448083"></a> </li> </ul> <a href="#" data-role="button" data-rel="back" data-theme="b">Volver</a> </div> <div data-role="footer" data-theme='b'> <h4>Visitalas</h4> </div> </div>
40.536585
184
0.609206
afbbfaae67fd1be917d4f3c56307eeec8856b8e4
305
html
HTML
Resources/Private/Partials/Settings/FormFields.html
hojama/pits_mailchimp
e5a63ef8d699c3fe7f7f359b93b998d94e827e27
[ "MIT" ]
null
null
null
Resources/Private/Partials/Settings/FormFields.html
hojama/pits_mailchimp
e5a63ef8d699c3fe7f7f359b93b998d94e827e27
[ "MIT" ]
null
null
null
Resources/Private/Partials/Settings/FormFields.html
hojama/pits_mailchimp
e5a63ef8d699c3fe7f7f359b93b998d94e827e27
[ "MIT" ]
null
null
null
<label for="property"> <f:translate key="tx_pitsmailchimp_domain_model_settings.property" /> </label><br /> <f:form.textfield property="property" /><br /> <label for="value"> <f:translate key="tx_pitsmailchimp_domain_model_settings.value" /> </label><br /> <f:form.textfield property="value" /><br />
33.888889
70
0.718033
164da3d1d58fd423d8c34b9fe92585edf1886009
11,302
c
C
usr/src/cmd/ypcmd/ypserv_resolv.c
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
null
null
null
usr/src/cmd/ypcmd/ypserv_resolv.c
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
null
null
null
usr/src/cmd/ypcmd/ypserv_resolv.c
AsahiOS/gate
283d47da4e17a5871d9d575e7ffb81e8f6c52e51
[ "MIT" ]
1
2020-12-30T00:04:16.000Z
2020-12-30T00:04:16.000Z
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License, Version 1.0 only * (the "License"). You may not use this file except in compliance * with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2003 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #pragma ident "%Z%%M% %I% %E% SMI" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <ctype.h> #include <rpc/rpc.h> #include <syslog.h> #include <signal.h> #include <string.h> #include <sys/types.h> #include <sys/resource.h> #include <errno.h> #ifdef TDRPC #include <netinet/in.h> #include <arpa/inet.h> #else #include <arpa/inet.h> #include <sys/systeminfo.h> #include <netconfig.h> #include <netdir.h> #endif #include <rpcsvc/yp_prot.h> #include "ypserv_resolv_common.h" #define YPDNSVERS 2L #ifdef TDRPC #define RESOLV_EXEC_PATH "/usr/etc/rpc.nisd_resolv" #define RESOLV_EXEC_ERR "can't exec /usr/etc/rpc.nisd_resolv: %s\n" #else #define RESOLV_EXEC_PATH "/usr/sbin/rpc.nisd_resolv" #define RESOLV_EXEC_ERR "can't exec /usr/sbin/rpc.nisd_resolv: %s\n" #endif extern bool silent; int verbose; extern int resolv_pid; static int getconf(char *netid, void **handle, struct netconfig **nconf); static int getprognum(long *prognum, SVCXPRT **xprt, char *fd_str, char *prog_str, long vers, char *tp_type); void setup_resolv(bool *fwding, int *child, CLIENT **client, char *tp_type, long prognum) { enum clnt_stat stat; struct timeval tv; char prog_str[15], fd_str[5]; SVCXPRT *xprt = NULL; char *tp; #ifdef TDRPC struct sockaddr_in addr; int sock; #else char name[257]; struct netconfig *nc; void *h; #endif verbose = silent == FALSE ? 1 : 0; if (! *fwding) return; #ifdef TDRPC tp = (tp_type && strcmp(tp_type, "udp") != 0) ? "udp" : "tcp"; #else /* try the specified netid (default ticots), then any loopback */ tp = (tp_type && *tp_type) ? tp_type : "ticots"; if (!getconf(tp, &h, &nc)) { /* dont forget endnetconfig() */ syslog(LOG_ERR, "can't get resolv_clnt netconf %s.\n", tp); *fwding = FALSE; return; } tp = nc->nc_netid; #endif /* * Startup the resolv server: use transient prognum if prognum * isn't set. Using transient means we create mapping then * pass child the fd to use for service. */ if (!getprognum(&prognum, &xprt, fd_str, prog_str, YPDNSVERS, tp)) { syslog(LOG_ERR, "can't create resolv xprt for transient.\n"); *fwding = FALSE; #ifndef TDRPC endnetconfig(h); #endif return; } switch (*child = vfork()) { case -1: /* error */ syslog(LOG_ERR, "can't startup resolv daemon\n"); #ifndef TDRPC endnetconfig(h); #endif *fwding = FALSE; return; case 0: /* child */ /* * if using transient we must maintain fd across * exec cause unset/set on prognum isn't automic. * * if using transient we'll just do svc_tli_create * in child on our bound fd. */ execlp(RESOLV_EXEC_PATH, "rpc.nisd_resolv", "-F", /* forground */ "-C", fd_str, /* dont close */ "-p", prog_str, /* prognum */ "-t", tp, /* tp type */ NULL); syslog(LOG_ERR, RESOLV_EXEC_ERR, strerror(errno)); exit(1); default: /* parent */ /* close fd, free xprt, but leave mapping */ if (xprt) svc_destroy(xprt); /* let it crank up before we create client */ sleep(4); } #ifdef TDRPC get_myaddress(&addr); addr.sin_port = 0; sock = RPC_ANYSOCK; tv.tv_sec = 3; tv.tv_usec = 0; if (strcmp(tp, "udp") != 0) { *client = clntudp_bufcreate(&addr, prognum, YPDNSVERS, tv, &sock, YPMSGSZ, YPMSGSZ); } else { *client = clnttcp_create(&addr, prognum, YPDNSVERS, &sock, YPMSGSZ, YPMSGSZ); } if (*client == NULL) { syslog(LOG_ERR, "can't create resolv client handle.\n"); (void) kill (*child, SIGINT); *fwding = FALSE; return; } #else if (sysinfo(SI_HOSTNAME, name, sizeof (name)-1) == -1) { syslog(LOG_ERR, "can't get local hostname.\n"); (void) kill (*child, SIGINT); endnetconfig(h); *fwding = FALSE; return; } if ((*client = clnt_tp_create(HOST_SELF_CONNECT, prognum, YPDNSVERS, nc)) == NULL) { syslog(LOG_ERR, "can't create resolv_clnt\n"); (void) kill (*child, SIGINT); endnetconfig(h); *fwding = FALSE; return; } endnetconfig(h); #endif /* ping for comfort */ tv.tv_sec = 10; tv.tv_usec = 0; if ((stat = clnt_call(*client, 0, xdr_void, 0, xdr_void, 0, tv)) != RPC_SUCCESS) { syslog(LOG_ERR, "can't talk with resolv server\n"); clnt_destroy (*client); (void) kill (*child, SIGINT); *fwding = FALSE; return; } if (verbose) syslog(LOG_INFO, "finished setup for dns fwding.\n"); } static int getprognum(long *prognum, SVCXPRT **xprt, char *fd_str, char *prog_str, long vers, char *tp_type) { static ulong_t start = 0x40000000; int fd; #ifdef TDRPC ushort_t port; int proto; #else struct netconfig *nc; struct netbuf *nb; #endif /* If prognum specified, use it instead of transient hassel. */ if (*prognum) { *xprt = NULL; sprintf(fd_str, "-1"); /* have child close all fds */ sprintf(prog_str, "%u", *prognum); return (TRUE); } /* * Transient hassel: * - parent must create mapping since someone else could * steal the transient prognum before child created it * - pass the child the fd to use for service * - close the fd (after exec), free xprt, leave mapping intact */ #ifdef TDRPC if (strcmp(tp_type, "udp") != 0) { proto = IPPROTO_UDP; *xprt = svcudp_bufcreate(RPC_ANYSOCK, 0, 0); } else { proto = IPPROTO_TCP; *xprt = svctcp_create(RPC_ANYSOCK, 0, 0); } if (*xprt == NULL) return (FALSE); port = (*xprt)->xp_port; fd = (*xprt)->xp_sock; while (!pmap_set(start, vers, proto, port)) start++; #else /* tp_type is legit: users choice or a loopback netid */ if ((nc = getnetconfigent(tp_type)) == NULL) return (FALSE); if ((*xprt = svc_tli_create(RPC_ANYFD, nc, NULL, 0, 0)) == NULL) { freenetconfigent(nc); return (FALSE); } nb = &(*xprt)->xp_ltaddr; fd = (*xprt)->xp_fd; while (!rpcb_set(start, vers, nc, nb)) start++; freenetconfigent(nc); #endif *prognum = start; sprintf(fd_str, "%u", fd); sprintf(prog_str, "%u", *prognum); return (TRUE); } #ifndef TDRPC static int getconf(char *netid, void **handle, struct netconfig **nconf) { struct netconfig *nc, *save = NULL; if ((*handle = setnetconfig()) == NULL) return (FALSE); while (nc = getnetconfig((void*)*handle)) { if (strcmp(nc->nc_netid, netid) != 0) { *nconf = nc; return (TRUE); } else if (!save && strcmp(nc->nc_protofmly, "loopback") != 0) save = nc; } if (save) { *nconf = save; return (TRUE); } else { endnetconfig(*handle); return (FALSE); } } #endif int resolv_req(bool *fwding, CLIENT **client, int *pid, char *tp, SVCXPRT *xprt, struct ypreq_key *req, char *map) { enum clnt_stat stat; struct timeval tv; struct ypfwdreq_key4 fwd_req4; struct ypfwdreq_key6 fwd_req6; struct in6_addr in6; int byname, byaddr; int byname_v6, byaddr_v6; #ifdef TDRPC struct sockaddr_in *addrp; #else struct netbuf *nb; char *uaddr; char *cp; int i; sa_family_t caller_af = AF_UNSPEC; struct sockaddr_in *sin4; struct sockaddr_in6 *sin6; #endif if (! *fwding) return (FALSE); byname = strcmp(map, "hosts.byname") == 0; byaddr = strcmp(map, "hosts.byaddr") == 0; byname_v6 = strcmp(map, "ipnodes.byname") == 0; byaddr_v6 = strcmp(map, "ipnodes.byaddr") == 0; if ((!byname && !byaddr && !byname_v6 && !byaddr_v6) || req->keydat.dsize == 0 || req->keydat.dptr[0] == '\0' || !isascii(req->keydat.dptr[0]) || !isgraph(req->keydat.dptr[0])) { /* default status is YP_NOKEY */ return (FALSE); } #ifdef TDRPC fwd_req4.map = map; fwd_req4.keydat = req->keydat; fwd_req4.xid = svc_getxid(xprt); addrp = svc_getcaller(xprt); fwd_req4.ip = addrp->sin_addr.s_addr; fwd_req4.port = addrp->sin_port; #else /* * In order to tell if we have an IPv4 or IPv6 caller address, * we must know that nb->buf is a (sockaddr_in *) or a * (sockaddr_in6 *). Hence, we might as well dispense with the * conversion to uaddr and parsing of same that this section * of the code previously involved itself in. */ nb = svc_getrpccaller(xprt); if (nb != 0) caller_af = ((struct sockaddr_storage *)nb->buf)->ss_family; if (caller_af == AF_INET6) { fwd_req6.map = map; fwd_req6.keydat = req->keydat; fwd_req6.xid = svc_getxid(xprt); sin6 = (struct sockaddr_in6 *)nb->buf; fwd_req6.addr = (uint32_t *)&in6; memcpy(fwd_req6.addr, sin6->sin6_addr.s6_addr, sizeof (in6)); fwd_req6.port = ntohs(sin6->sin6_port); } else if (caller_af == AF_INET) { fwd_req4.map = map; fwd_req4.keydat = req->keydat; fwd_req4.xid = svc_getxid(xprt); sin4 = (struct sockaddr_in *)nb->buf; fwd_req4.ip = ntohl(sin4->sin_addr.s_addr); fwd_req4.port = ntohs(sin4->sin_port); } else { syslog(LOG_ERR, "unknown caller IP address family %d", caller_af); return (FALSE); } #endif /* Restart resolver if it died. (possible overkill) */ if (kill(*pid, 0)) { syslog(LOG_INFO, "Restarting resolv server: old one (pid %d) died.\n", *pid); if (*client != NULL) clnt_destroy (*client); setup_resolv(fwding, pid, client, tp, 0 /* transient p# */); if (!*fwding) { syslog(LOG_ERR, "can't restart resolver: ending resolv service.\n"); return (FALSE); } } /* may need to up timeout */ tv.tv_sec = 10; tv.tv_usec = 0; if (caller_af == AF_INET6) { stat = clnt_call(*client, YPDNSPROC6, xdr_ypfwdreq_key6, (char *)&fwd_req6, xdr_void, 0, tv); } else { stat = clnt_call(*client, YPDNSPROC4, xdr_ypfwdreq_key4, (char *)&fwd_req4, xdr_void, 0, tv); } if (stat == RPC_SUCCESS) /* expected */ return (TRUE); else { /* Over kill error recovery */ /* make one attempt to restart service before turning off */ syslog(LOG_INFO, "Restarting resolv server: old one not responding.\n"); if (!kill(*pid, 0)) kill (*pid, SIGINT); /* cleanup old one */ if (*client != NULL) clnt_destroy (*client); setup_resolv(fwding, pid, client, tp, 0 /* transient p# */); if (!*fwding) { syslog(LOG_ERR, "can't restart resolver: ending resolv service.\n"); return (FALSE); } if (caller_af == AF_INET6) { stat = clnt_call(*client, YPDNSPROC6, xdr_ypfwdreq_key6, (char *)&fwd_req6, xdr_void, 0, tv); } else { stat = clnt_call(*client, YPDNSPROC4, xdr_ypfwdreq_key4, (char *)&fwd_req4, xdr_void, 0, tv); } if (stat == RPC_SUCCESS) /* expected */ return (TRUE); else { /* no more restarts */ clnt_destroy (*client); *fwding = FALSE; /* turn off fwd'ing */ syslog(LOG_ERR, "restarted resolver not responding: ending resolv service.\n"); return (FALSE); } } }
26.162037
73
0.66068
53b484656cee48bf6d57e48513ae8d8b31a1232e
5,483
lua
Lua
BGAnimations/ScreenGameplay overlay/GatherInfo.lua
Nepumi/MusicMemories
d81558310ebadba988da6d1ce7e5743edb0876bc
[ "MIT" ]
6
2020-12-27T17:17:04.000Z
2021-05-28T15:46:55.000Z
BGAnimations/ScreenGameplay overlay/GatherInfo.lua
Nepumi/MusicMemories
d81558310ebadba988da6d1ce7e5743edb0876bc
[ "MIT" ]
3
2021-03-13T18:36:24.000Z
2021-03-28T16:06:11.000Z
BGAnimations/ScreenGameplay overlay/GatherInfo.lua
Nepumi/MusicMemories
d81558310ebadba988da6d1ce7e5743edb0876bc
[ "MIT" ]
1
2021-01-26T14:04:41.000Z
2021-01-26T14:04:41.000Z
local BattleMemories = {}; local Players = GAMESTATE:GetHumanPlayers(); local thisTapTiming = {} return Def.ActorFrame{ Def.Quad{--Timing InitCommand=cmd(zoom,20;visible,false); OnCommand=function(self) for pn in ivalues(Players) do thisTapTiming[pn] = {}; end end; JudgmentMessageCommand=function(self,params) if params.HoldNoteScore then return end; local smallTapNoteScore = ToEnumShortString(params.TapNoteScore) local TName,Length = LoadModule("Options.SmartTapNoteScore.lua")() local thisTime = GAMESTATE:GetCurMusicSeconds() if FindInTable(smallTapNoteScore, TName) then if thisTapTiming[params.Player] == nil then thisTapTiming[params.Player] = {} end if params.TapNoteScore == "TapNoteScore_Miss" then thisTapTiming[params.Player][#thisTapTiming[params.Player]+1] = {thisTime,params.TapNoteScore,1}; else thisTapTiming[params.Player][#thisTapTiming[params.Player]+1] = {thisTime,params.TapNoteScore,params.TapNoteOffset}; end end end; OffCommand=function(self) for pn in ivalues(Players) do TP.Eva.TapTiming[pn] = thisTapTiming[pn]; end end; }; --[[Def.Quad{--Battle Memories Condition = (not GAMESTATE:IsCourseMode()) ; InitCommand=cmd(zoom,20;visible,false); JudgmentMessageCommand=function(self,params) PP[params.Player] = params; LP = params.Player; self:sleep(0.05):queuecommand("Addto") end; AddtoCommand=function(self) local params = PP[LP] local tsc = params.TapNoteScore if params.HoldNoteScore then tsc = "nil" end BattleMemories[params.Player] = (BattleMemories[params.Player] or "").. string.format("{%.3f,\"%s\",%.2f,\"%s\"},\n", GAMESTATE:GetCurMusicSeconds(),tostring(tsc), STATSMAN:GetCurStageStats():GetPlayerStageStats(params.Player):GetPercentDancePoints()*100, STATSMAN:GetCurStageStats():GetPlayerStageStats(params.Player):GetGrade()) LS[params.Player] = STATSMAN:GetCurStageStats():GetPlayerStageStats(params.Player):GetPercentDancePoints()*100 -- printf("<1>%d <2>%s <3>%s <4>%s\n%s", -- math.random(1,9), -- tostring(PROFILEMAN:GetProfile(LP):GetGUID()), -- tostring(PROFILEMAN:GetProfileDir("ProfileSlot_Player1")), -- string.gsub( tostring(GAMESTATE:GetCurrentSong():GetSongDir()),"/Songs/",""), -- tostring(GAMESTATE:GetCurrentSteps(LP):GetHash()) -- ) --printf("LP is %s!",tostring(LP)) end; OffCommand=function(self) if GAMESTATE:GetCurMusicSeconds() >= GAMESTATE:GetCurrentSong():GetLastSecond()-1 then for k,LP in pairs(GAMESTATE:GetHumanPlayers()) do if PROFILEMAN:GetProfile(LP):GetDisplayName() then local PathA = tostring(PROFILEMAN:GetProfileDir(LP == PLAYER_1 and "ProfileSlot_Player1" or "ProfileSlot_Player2")).."Memories/BattleMemories/" local PathB = (string.gsub( tostring(GAMESTATE:GetCurrentSong():GetSongDir()),"/Songs/","") or "SomeSong/")..tostring(ToEnumShortString(GAMESTATE:GetCurrentSteps(LP):GetStepsType())).."/"; local PathC; if tostring(GAMESTATE:GetCurrentSteps(LP):GetDifficulty()) == "Difficulty_Edit" then PathC = tostring(GAMESTATE:GetCurrentSteps(LP):GetHash())..".lua" else PathC = tostring(ToEnumShortString(GAMESTATE:GetCurrentSteps(LP):GetDifficulty()))..".lua" end if FILEMAN:DoesFileExist(PathA..PathB..PathC) then local TOD = LoadActor(PathA..PathB..PathC); if LS[LP] == nil then--some how when you play with Both Input return; end --printf("%.2f vs %.2f is %s",LS , TOD[#TOD][3],LS <= TOD[#TOD][3] and "No Highscore..." or "Whatever") if LS[LP] <= TOD[#TOD][3] then return; end end local f = RageFileUtil.CreateRageFile() if f:Open(PathA..PathB..PathC, 2) then if BattleMemories[LP] ~= nil then--Some how f:Write("return {"..BattleMemories[LP]:sub(1,BattleMemories[LP]:len()-2).."};") end --printf("Saving at %s%s%s!!",PathA,PathB,PathC) end f:destroy() --SaveProfileCustom(PROFILEMAN:GetProfile(LP), dir) end end end end; };]] };
39.731884
212
0.510487
40d1905e8e8681d9554c31089986c95d2399e66a
3,089
html
HTML
pageHtml/index.html
Sewar-web/cookie-stand
6030831446d670d81e934353cd1f5b0408a3e465
[ "MIT" ]
null
null
null
pageHtml/index.html
Sewar-web/cookie-stand
6030831446d670d81e934353cd1f5b0408a3e465
[ "MIT" ]
null
null
null
pageHtml/index.html
Sewar-web/cookie-stand
6030831446d670d81e934353cd1f5b0408a3e465
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="../css/style.css"> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>COOKIES STAND </title> </head> <body> <h1> <i> Welcome To Pats Salmon Cookies !</i></h1> <img src="../salmon.png"> <!-- <div> <img src="../img/1.jpeg" alt=""> <img src="../img/2.jpg" alt=""> <img src="../img/3.jpg" alt=""> <img src="../img/4.jpg" alt=""> <img src="../img/5.jpg" alt=""> </div> --> <br> <br> <br> <a class="aa"href="sales.html">sales</a> <br></br> <ul class="Seattle"> <p >Seattle</p> <li><a href="https://www.google.com/maps?q=location+seattle&rlz=1C1CHZL_enJO939JO939&um=1&ie=UTF-8&sa=X&ved=2ahUKEwi-pujEvIDvAhVP6RoKHVomAgAQ_AUoAnoECAEQBA">Seattle location</a></li> <li>Opening hours (6:00 AM - 8:00Pm) </li> <li><a href="tel:12066848344"> contact information</a></li> </ul> <br></br> <ul class="Tokyo" ><p >Tokyo</p> <li><a href="https://www.google.com/maps/place/%D8%B7%D9%88%D9%83%D9%8A%D9%88%D8%8C+%D8%A7%D9%84%D9%8A%D8%A7%D8%A8%D8%A7%D9%86%E2%80%AD/@35.48847,142.0133177,7z/data=!3m1!4b1!4m5!3m4!1s0x605d1b87f02e57e7:0x2e01618b22571b89!8m2!3d35.6761919!4d139.6503106">tokyo location</a> </li> <li>Opening hours (9:00 AM - 5:00Pm) </li> <li><a href="https://www.attokyo.com/contact/info/index.php"> contact information</a></li> </ul> <br></br> <ul class="Dubai"> <p>Dubai</p> <li><a href="https://www.google.com/maps/place/%D8%AF%D8%A8%D9%8A+-+%D8%A7%D9%84%D8%A5%D9%85%D8%A7%D8%B1%D8%A7%D8%AA+%D8%A7%D9%84%D8%B9%D8%B1%D8%A8%D9%8A%D8%A9+%D8%A7%D9%84%D9%85%D8%AA%D8%AD%D8%AF%D8%A9%E2%80%AD/@25.0750853,55.5079386,10z/data=!3m1!4b1!4m5!3m4!1s0x3e5f43496ad9c645:0xbde66e5084295162!8m2!3d25.2048493!4d55.2707828"> dubai location</a></li> <li>Opening hours (6:00 AM - 8:00Pm) </li> <li><a href="https://www.dubaicustoms.gov.ae/EN/CUSTOMERCARE/Pages/ContactUs.aspx"> contact information</a></li> </ul> <br></br> <ul class="Paris"> <p >Paris</p> <li><a href="https://www.google.com/maps?q=paris+location&rlz=1C1CHZL_enJO939JO939&um=1&ie=UTF-8&sa=X&ved=2ahUKEwj_6dWwvYDvAhVVkFwKHd12DesQ_AUoAnoECAUQBA">paris location</a></li> <li>Opening hours (6:00 AM - 8:00Pm) </li> <li><a href="https://en.parisinfo.com/contact-us"> contact information</a></li> </ul> <br></br> <ul class="Lima"> <p >Lima</p> <li><a href="https://www.google.com/maps?q=lima+location&rlz=1C1CHZL_enJO939JO939&um=1&ie=UTF-8&sa=X&ved=2ahUKEwik1p7UvYDvAhUoyoUKHcFaCMwQ_AUoAnoECBAQBA">lima location</a></li> <li>Opening hours (6:00 AM - 8:00Pm) </li> <li><a href="https://www.wipo.int/directory/en/contact.jsp?country_id=137&type=ADMIN_IPO"> contact information</a></li> </ul> </body> <script src="javascript/app.js"></script> </html>
40.116883
364
0.61023
dfbf79d73854669be49ea51f9b9434b5e08ec3ec
1,928
ts
TypeScript
src/services/index.ts
EvangelosKolimitras/quest_me
4526f4bf6bb9973746d997eba466369aa09de8c5
[ "MIT" ]
null
null
null
src/services/index.ts
EvangelosKolimitras/quest_me
4526f4bf6bb9973746d997eba466369aa09de8c5
[ "MIT" ]
null
null
null
src/services/index.ts
EvangelosKolimitras/quest_me
4526f4bf6bb9973746d997eba466369aa09de8c5
[ "MIT" ]
null
null
null
// Services API import { users } from './users' import { questions } from './questions' let Q = questions; let U = users; export const initializations = () => Promise.all([ _getUsers(), _getQuestions(), ]).then(([users, questions]) => ({ users, questions, })) const _getUsers = () => new Promise((res, rej) => setTimeout(() => res({ ...users }), 500)) const _getQuestions = () => new Promise((res, rej) => setTimeout(() => res({ ...questions }), 500)) const generateUID = (): string => Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15) const formatQuestion = ({ optionOneText, optionTwoText, author }: any) => ({ id: generateUID(), timestamp: Date.now(), author, optionOne: { votes: [], text: optionOneText, }, optionTwo: { votes: [], text: optionTwoText, } }) export const saveQuestion = (question: any) => _saveQuestion(question) const _saveQuestion = (question: any) => { return new Promise((res, rej) => { const authedUser = question.author; const formattedQuestion = formatQuestion(question) setTimeout(() => { Q = { ...Q, [formattedQuestion.id]: formattedQuestion } U = { ...U, [authedUser]: { ...U[authedUser], questions: U[authedUser].questions.concat([formattedQuestion.id]) } } res(formattedQuestion) }, 1000) }) } export const saveQuestionAnswer = (info: any) => _saveQuestionAnswer(info) function _saveQuestionAnswer({ authedUser, qid, answer }: any) { return new Promise<void>((res, rej) => { setTimeout(() => { U = { ...U, [authedUser]: { ...U[authedUser], answers: { ...U[authedUser].answers, [qid]: answer } } } Q = { ...Q, [qid]: { ...Q[qid], [answer]: { ...Q[qid][answer], votes: Q[qid][answer].votes.concat([authedUser]) } } } res() }, 500) }) } export { users, questions }
20.294737
90
0.588174
015f29f43a61a3e276ada335334a4408a393d011
327
swift
Swift
Mvvm/Views/TableCells/HomeFeedRewardsTableViewCell.swift
naim-ali/Mvvm-guide
1a1ff9a1965f63778ff37377e524b19db8b1b1c1
[ "MIT" ]
null
null
null
Mvvm/Views/TableCells/HomeFeedRewardsTableViewCell.swift
naim-ali/Mvvm-guide
1a1ff9a1965f63778ff37377e524b19db8b1b1c1
[ "MIT" ]
null
null
null
Mvvm/Views/TableCells/HomeFeedRewardsTableViewCell.swift
naim-ali/Mvvm-guide
1a1ff9a1965f63778ff37377e524b19db8b1b1c1
[ "MIT" ]
null
null
null
// // HomeFeedRewardsTableViewCell.swift // Mvvm // // Created by Sean Davis on 12/14/17. // Copyright © 2017 Sean Davis. All rights reserved. // import UIKit class HomeFeedRewardsTableViewCell: UITableViewCell { @IBOutlet weak var leftImageView: UIImageView! @IBOutlet weak var titleLabel: UILabel! }
18.166667
53
0.70948
5b91f4ffdff1e4c2d2d7bd5a1c5086c956efa40a
1,765
sql
SQL
tpc/src/main/resources/ds-queries/86.sql
yosshor/limestone
4b6815a941a05d2972c45751dddce13c72e3c02a
[ "Apache-2.0" ]
null
null
null
tpc/src/main/resources/ds-queries/86.sql
yosshor/limestone
4b6815a941a05d2972c45751dddce13c72e3c02a
[ "Apache-2.0" ]
null
null
null
tpc/src/main/resources/ds-queries/86.sql
yosshor/limestone
4b6815a941a05d2972c45751dddce13c72e3c02a
[ "Apache-2.0" ]
null
null
null
with wscs as (select sold_date_sk ,sales_price from (select ws_sold_date_sk sold_date_sk ,ws_ext_sales_price sales_price from web_sales union all select cs_sold_date_sk sold_date_sk ,cs_ext_sales_price sales_price from catalog_sales)), wswscs as (select d_week_seq, sum(case when (d_day_name='Sunday') then sales_price else null end) sun_sales, sum(case when (d_day_name='Monday') then sales_price else null end) mon_sales, sum(case when (d_day_name='Tuesday') then sales_price else null end) tue_sales, sum(case when (d_day_name='Wednesday') then sales_price else null end) wed_sales, sum(case when (d_day_name='Thursday') then sales_price else null end) thu_sales, sum(case when (d_day_name='Friday') then sales_price else null end) fri_sales, sum(case when (d_day_name='Saturday') then sales_price else null end) sat_sales from wscs ,date_dim where d_date_sk = sold_date_sk group by d_week_seq) select d_week_seq1 ,round(sun_sales1/sun_sales2,2) ,round(mon_sales1/mon_sales2,2) ,round(tue_sales1/tue_sales2,2) ,round(wed_sales1/wed_sales2,2) ,round(thu_sales1/thu_sales2,2) ,round(fri_sales1/fri_sales2,2) ,round(sat_sales1/sat_sales2,2) from (select wswscs.d_week_seq d_week_seq1 ,sun_sales sun_sales1 ,mon_sales mon_sales1 ,tue_sales tue_sales1 ,wed_sales wed_sales1 ,thu_sales thu_sales1 ,fri_sales fri_sales1 ,sat_sales sat_sales1 from wswscs,date_dim where date_dim.d_week_seq = wswscs.d_week_seq and d_year = 2000) y, (select wswscs.d_week_seq d_week_seq2 ,sun_sales sun_sales2 ,mon_sales mon_sales2 ,tue_sales tue_sales2 ,wed_sales wed_sales2 ,thu_sales thu_sales2 ,fri_sales fri_sales2 ,sat_sales sat_sales2 from wswscs ,date_dim where date_dim.d_week_seq = wswscs.d_week_seq and d_year = 2000+1) z where d_week_seq1=d_week_seq2-53 order by d_week_seq1;
30.431034
81
0.824363
5a559b81cf8da44d99c08d8f9efc3e76e1f42d05
3,898
swift
Swift
MEGameTracker/Models/CloudKit/CloudKit Records/CloudKitSequences.swift
mleiv/MEGameTracker
cef2c76b62fffe9ac662b9a820a6ebd54962ef5f
[ "MIT" ]
2
2020-03-08T20:15:21.000Z
2021-07-19T21:43:05.000Z
MEGameTracker/Models/CloudKit/CloudKit Records/CloudKitSequences.swift
mleiv/MEGameTracker
cef2c76b62fffe9ac662b9a820a6ebd54962ef5f
[ "MIT" ]
1
2021-12-25T05:38:14.000Z
2021-12-25T15:23:48.000Z
MEGameTracker/Models/CloudKit/CloudKit Records/CloudKitSequences.swift
mleiv/MEGameTracker
cef2c76b62fffe9ac662b9a820a6ebd54962ef5f
[ "MIT" ]
1
2021-06-02T20:45:22.000Z
2021-06-02T20:45:22.000Z
// // GameSequences.swift // MEGameTracker // // Created by Emily Ivie on 12/31/16. // Copyright © 2016 Emily Ivie. All rights reserved. // import Foundation import CloudKit import CoreData extension GameSequence: CloudDataStorable { /// (CloudDataStorable Protocol) /// Set any additional fields, specific to the object in question, for a cloud kit object. public func setAdditionalCloudFields(record: CKRecord) { record.setValue(uuid.uuidString as NSString, forKey: "id") if let shepard = self.shepard { record.setValue(shepard.uuid.uuidString as NSString, forKey: "lastPlayedShepard") } } /// (CloudDataStorable Protocol) /// Alter any CK items before handing to codable to modify/create object public func getAdditionalCloudFields(changeRecord: CloudDataRecordChange) -> [String: Any?] { let changes = changeRecord.changeSet // changes.removeValue(forKey: "lastRecordData") return changes } /// (CloudDataStorable Protocol) /// Takes one serialized cloud change and saves it. public static func saveOneFromCloud( changeRecord: CloudDataRecordChange, with manager: CodableCoreDataManageable? ) -> Bool { let recordId = changeRecord.recordId if let (_, uuid) = parseIdentifyingName(name: recordId) { var element = GameSequence.get(uuid: uuid) ?? GameSequence(uuid: uuid) // apply cloud changes element.rawData = nil let changes = element.getAdditionalCloudFields(changeRecord: changeRecord) element = element.changed(changes) element.isSavedToCloud = true // reapply any local changes if !element.pendingCloudChanges.isEmpty { element = element.changed(element.pendingCloudChanges.dictionary) element.isSavedToCloud = false } // save locally if element.save(isCascadeChanges: .none, isAllowDelay: false, with: manager) { print("Saved from cloud \(recordId)") return true } else { print("Save from cloud failed \(recordId)") } } return false } /// (CloudDataStorable Protocol) /// Delete a local object after directed by the cloud to do so. public static func deleteOneFromCloud(recordId: String) -> Bool { guard let (_, uuid) = parseIdentifyingName(name: recordId) else { return false } return App.current.delete(uuid: uuid) } /// (CloudDataStorable Protocol) /// Create a recordName for any cloud kit object. public static func getIdentifyingName( id: String, gameSequenceUuid: UUID? ) -> String { return "\(gameSequenceUuid?.uuidString ?? "")||\(id)" } /// Convenience version - get the static getIdentifyingName for easy instance reference. public func getIdentifyingName() -> String { return GameSequence.getIdentifyingName(id: "", gameSequenceUuid: uuid) } /// (CloudDataStorable Protocol) /// Parses a cloud identifier into the parts needed to retrieve it from core data. public static func parseIdentifyingName( name: String ) -> ((id: String, gameSequenceUuid: UUID)?) { let pieces = name.components(separatedBy: "||") guard pieces.count == 2 else { return nil } if let gameSequenceUuid = UUID(uuidString: pieces[0]) { return (id: pieces[1], gameSequenceUuid: gameSequenceUuid) } else { defaultManager.log("No Game UUID found for: \(name)") return nil } } /// Used for parsing from records public static func getAll( identifiers: [String], with manager: CodableCoreDataManageable? ) -> [GameSequence] { return identifiers.map { (identifier: String) in if let (id, _) = parseIdentifyingName(name: identifier), let uuid = UUID(uuidString: id) { return get(uuid: uuid, with: manager) } return nil }.filter({ $0 != nil }).map({ $0! }) } }
34.803571
97
0.671113
84ffd8970a667dd4bfeeaac7008c7648e09a9caa
9,725
c
C
src/paravim/tree_sitter/scanner_python.c
paranim/paravim
220d85b45e8c2928c6b18a65690743a125eb8859
[ "Unlicense" ]
98
2020-03-19T12:56:30.000Z
2022-02-07T07:32:29.000Z
src/paravim/tree_sitter/scanner_python.c
paranim/paravim
220d85b45e8c2928c6b18a65690743a125eb8859
[ "Unlicense" ]
null
null
null
src/paravim/tree_sitter/scanner_python.c
paranim/paravim
220d85b45e8c2928c6b18a65690743a125eb8859
[ "Unlicense" ]
3
2020-04-01T21:46:49.000Z
2020-07-17T17:54:00.000Z
#include "tree_sitter/parser.h" #include <wctype.h> #include <string.h> #include <assert.h> #include <stdio.h> #define STB_DS_IMPLEMENTATION #include "stb_ds.h" struct Scanner { uint16_t *indent_length_stack; char *delimiter_stack; }; enum TokenType { NEWLINE, INDENT, DEDENT, STRING_START, STRING_CONTENT, STRING_END, }; enum { SingleQuote = 1 << 0, DoubleQuote = 1 << 1, BackQuote = 1 << 2, Raw = 1 << 3, Format = 1 << 4, Triple = 1 << 5, Bytes = 1 << 6, }; bool is_format(char *flags) { return *flags & Format; } bool is_raw(char *flags) { return *flags & Raw; } bool is_triple(char *flags) { return *flags & Triple; } bool is_bytes(char *flags) { return *flags & Bytes; } int32_t end_character(char *flags) { if (*flags & SingleQuote) return '\''; if (*flags & DoubleQuote) return '"'; if (*flags & BackQuote) return '`'; return 0; } void set_format(char *flags) { *flags |= Format; } void set_raw(char *flags) { *flags |= Raw; } void set_triple(char *flags) { *flags |= Triple; } void set_bytes(char *flags) { *flags |= Bytes; } void set_end_character(char *flags, int32_t character) { switch (character) { case '\'': *flags |= SingleQuote; break; case '"': *flags |= DoubleQuote; break; case '`': *flags |= BackQuote; break; default: assert(false); } } void advance(TSLexer *lexer) { lexer->advance(lexer, false); } void skip(TSLexer *lexer) { lexer->advance(lexer, true); } bool scan(struct Scanner *scanner, TSLexer *lexer, const bool *valid_symbols) { if (valid_symbols[STRING_CONTENT] && !valid_symbols[INDENT] && arrlen(scanner->delimiter_stack) != 0) { char delimiter = arrlast(scanner->delimiter_stack); int32_t end_char = end_character(&delimiter); bool has_content = false; while (lexer->lookahead) { if (lexer->lookahead == '{' && is_format(&delimiter)) { lexer->mark_end(lexer); lexer->advance(lexer, false); if (lexer->lookahead == '{') { lexer->advance(lexer, false); } else { lexer->result_symbol = STRING_CONTENT; return has_content; } } else if (lexer->lookahead == '\\') { if (is_raw(&delimiter)) { lexer->advance(lexer, false); } else if (is_bytes(&delimiter)) { lexer->mark_end(lexer); lexer->advance(lexer, false); if (lexer->lookahead == 'N' || lexer->lookahead == 'u' || lexer->lookahead == 'U') { // In bytes string, \N{...}, \uXXXX and \UXXXXXXXX are not escape sequences // https://docs.python.org/3/reference/lexical_analysis.html#string-and-bytes-literals lexer->advance(lexer, false); } else { lexer->result_symbol = STRING_CONTENT; return has_content; } } else { lexer->mark_end(lexer); lexer->result_symbol = STRING_CONTENT; return has_content; } } else if (lexer->lookahead == end_char) { if (is_triple(&delimiter)) { lexer->mark_end(lexer); lexer->advance(lexer, false); if (lexer->lookahead == end_char) { lexer->advance(lexer, false); if (lexer->lookahead == end_char) { if (has_content) { lexer->result_symbol = STRING_CONTENT; } else { lexer->advance(lexer, false); lexer->mark_end(lexer); arrpop(scanner->delimiter_stack); lexer->result_symbol = STRING_END; } return true; } } } else { if (has_content) { lexer->result_symbol = STRING_CONTENT; } else { lexer->advance(lexer, false); arrpop(scanner->delimiter_stack); lexer->result_symbol = STRING_END; } lexer->mark_end(lexer); return true; } } else if (lexer->lookahead == '\n' && has_content && !is_triple(&delimiter)) { return false; } advance(lexer); has_content = true; } } lexer->mark_end(lexer); bool has_comment = false; bool has_newline = false; uint32_t indent_length = 0; for (;;) { if (lexer->lookahead == '\n') { has_newline = true; indent_length = 0; skip(lexer); } else if (lexer->lookahead == ' ') { indent_length++; skip(lexer); } else if (lexer->lookahead == '\r') { indent_length = 0; skip(lexer); } else if (lexer->lookahead == '\t') { indent_length += 8; skip(lexer); } else if (lexer->lookahead == '#') { has_comment = true; while (lexer->lookahead && lexer->lookahead != '\n') skip(lexer); skip(lexer); indent_length = 0; } else if (lexer->lookahead == '\\') { skip(lexer); if (iswspace(lexer->lookahead)) { skip(lexer); } else { return false; } } else if (lexer->lookahead == '\f') { indent_length = 0; skip(lexer); } else if (lexer->lookahead == 0) { if (valid_symbols[DEDENT] && arrlen(scanner->indent_length_stack) > 1) { arrpop(scanner->indent_length_stack); lexer->result_symbol = DEDENT; return true; } if (valid_symbols[NEWLINE]) { lexer->result_symbol = NEWLINE; return true; } break; } else { break; } } if (has_newline) { if (indent_length > arrlast(scanner->indent_length_stack) && valid_symbols[INDENT]) { arrput(scanner->indent_length_stack, indent_length); lexer->result_symbol = INDENT; return true; } if (indent_length < arrlast(scanner->indent_length_stack) && valid_symbols[DEDENT]) { arrpop(scanner->indent_length_stack); lexer->result_symbol = DEDENT; return true; } if (valid_symbols[NEWLINE]) { lexer->result_symbol = NEWLINE; return true; } } if (!has_comment && valid_symbols[STRING_START]) { char delimiter = 0; bool has_flags = false; while (lexer->lookahead) { if (lexer->lookahead == 'f' || lexer->lookahead == 'F') { set_format(&delimiter); } else if (lexer->lookahead == 'r' || lexer->lookahead == 'R') { set_raw(&delimiter); } else if (lexer->lookahead == 'b' || lexer->lookahead == 'B') { set_bytes(&delimiter); } else if (lexer->lookahead != 'u' && lexer->lookahead != 'U') { break; } has_flags = true; advance(lexer); } if (lexer->lookahead == '`') { set_end_character(&delimiter, '`'); advance(lexer); lexer->mark_end(lexer); } else if (lexer->lookahead == '\'') { set_end_character(&delimiter, '\''); advance(lexer); lexer->mark_end(lexer); if (lexer->lookahead == '\'') { advance(lexer); if (lexer->lookahead == '\'') { advance(lexer); lexer->mark_end(lexer); set_triple(&delimiter); } } } else if (lexer->lookahead == '"') { set_end_character(&delimiter, '"'); advance(lexer); lexer->mark_end(lexer); if (lexer->lookahead == '"') { advance(lexer); if (lexer->lookahead == '"') { advance(lexer); lexer->mark_end(lexer); set_triple(&delimiter); } } } if (end_character(&delimiter)) { arrput(scanner->delimiter_stack, delimiter); lexer->result_symbol = STRING_START; return true; } else if (has_flags) { return false; } } return false; } unsigned serialize(struct Scanner *scanner, char *buffer) { size_t i = 0; size_t stack_size = arrlen(scanner->delimiter_stack); if (stack_size > UINT8_MAX) stack_size = UINT8_MAX; buffer[i++] = stack_size; memcpy(&buffer[i], scanner->delimiter_stack, stack_size); i += stack_size; for (int iter = 1; iter != arrlen(scanner->indent_length_stack) && i < TREE_SITTER_SERIALIZATION_BUFFER_SIZE; ++iter) { buffer[i++] = scanner->indent_length_stack[iter]; } return i; } void deserialize(struct Scanner *scanner, const char *buffer, unsigned length) { arrfree(scanner->delimiter_stack); arrfree(scanner->indent_length_stack); arrput(scanner->indent_length_stack, 0); if (length > 0) { size_t i = 0; size_t delimiter_count = (uint8_t)buffer[i++]; arrsetlen(scanner->delimiter_stack, delimiter_count); memcpy(scanner->delimiter_stack, &buffer[i], delimiter_count); i += delimiter_count; for (; i < length; i++) { arrput(scanner->indent_length_stack, buffer[i]); } } } void init_scanner(struct Scanner *scanner) { deserialize(scanner, NULL, 0); } void *tree_sitter_python_external_scanner_create() { void *scanner = calloc(1, sizeof(struct Scanner)); init_scanner((struct Scanner*) scanner); return scanner; } bool tree_sitter_python_external_scanner_scan(void *payload, TSLexer *lexer, const bool *valid_symbols) { return scan((struct Scanner*) payload, lexer, valid_symbols); } unsigned tree_sitter_python_external_scanner_serialize(void *payload, char *buffer) { return serialize((struct Scanner*) payload, buffer); } void tree_sitter_python_external_scanner_deserialize(void *payload, const char *buffer, unsigned length) { deserialize((struct Scanner*) payload, buffer, length); } void tree_sitter_python_external_scanner_destroy(void *payload) { struct Scanner *scanner = (struct Scanner*) payload; arrfree(scanner->indent_length_stack); arrfree(scanner->delimiter_stack); free(scanner); }
26.717033
121
0.5891
5b310b5862a4c5b9841b5db5d1ff4f185289282b
780
cpp
C++
radmc-3d/version_0.41/viewimage_QT_GUI/polar.cpp
dlmatra/miao
71799811b21a4249754390a8ec00972723edab99
[ "MIT" ]
1
2019-11-23T00:03:40.000Z
2019-11-23T00:03:40.000Z
radmc-3d/version_0.41/viewimage_QT_GUI/polar.cpp
dlmatra/miao
71799811b21a4249754390a8ec00972723edab99
[ "MIT" ]
3
2021-05-26T12:54:50.000Z
2021-05-27T10:58:48.000Z
radmc-3d/version_0.41/viewimage_QT_GUI/polar.cpp
dlmatra/miao
71799811b21a4249754390a8ec00972723edab99
[ "MIT" ]
1
2021-12-23T14:09:52.000Z
2021-12-23T14:09:52.000Z
#include "polar.h" Polar *Polar::instance=0; Polar::Polar(QObject *parent) : QObject(parent) { } Polar *Polar::getInstance(QObject *parent){ if(!instance){ instance=new Polar(parent); } return instance; } void Polar::setPhii(QVector<double> vector){ this->phii.clear(); this->phii=vector; } void Polar::setRi(QVector<double> vector){ this->ri.clear(); this->ri=vector; } void Polar::setThetai(QVector<double> vector){ this->thetai.clear(); this->thetai=vector; } void Polar::setPhi(QVector<double> vector){ this->phi.clear(); this->phi=vector; } void Polar::setR(QVector<double> vector){ this->r.clear(); this->r=vector; } void Polar::setTheta(QVector<double> vector){ this->theta.clear(); this->theta=vector; }
21.081081
46
0.655128
6546238c5cc99f6434344bc2dc8680356df8f817
34,758
py
Python
flowsa/flowbyfunctions.py
modelearth/flowsa
d4dcf5ef8764b4ef895080a54d0546668daf0e1a
[ "CC0-1.0" ]
13
2020-04-10T20:43:00.000Z
2022-02-12T09:00:56.000Z
flowsa/flowbyfunctions.py
modelearth/flowsa
d4dcf5ef8764b4ef895080a54d0546668daf0e1a
[ "CC0-1.0" ]
93
2020-03-05T14:22:42.000Z
2022-03-30T20:33:06.000Z
flowsa/flowbyfunctions.py
modelearth/flowsa
d4dcf5ef8764b4ef895080a54d0546668daf0e1a
[ "CC0-1.0" ]
16
2020-05-03T13:54:59.000Z
2022-01-06T16:42:53.000Z
# flowbyfunctions.py (flowsa) # !/usr/bin/env python3 # coding=utf-8 """ Helper functions for flowbyactivity and flowbysector data """ import pandas as pd import numpy as np from esupy.dqi import get_weighted_average import flowsa from flowsa.common import fbs_activity_fields, US_FIPS, get_state_FIPS, \ get_county_FIPS, update_geoscale, log, load_source_catalog, \ load_sector_length_crosswalk, flow_by_sector_fields, fbs_fill_na_dict, \ fbs_collapsed_default_grouping_fields, flow_by_sector_collapsed_fields, \ fbs_collapsed_fill_na_dict, fba_activity_fields, \ fips_number_key, flow_by_activity_fields, fba_fill_na_dict, datasourcescriptspath, \ find_true_file_path, flow_by_activity_mapped_fields, fba_mapped_default_grouping_fields from flowsa.dataclean import clean_df, replace_strings_with_NoneType, \ replace_NoneType_with_empty_cells, standardize_units def create_geoscale_list(df, geoscale, year='2015'): """ Create a list of FIPS associated with given geoscale :param df: FlowBySector of FlowByActivity df :param geoscale: 'national', 'state', or 'county' :param year: str, year of FIPS, defaults to 2015 :return: list of relevant FIPS """ # filter by geoscale depends on Location System fips = [] if geoscale == "national": fips.append(US_FIPS) elif df['LocationSystem'].str.contains('FIPS').any(): # all_FIPS = read_stored_FIPS() if geoscale == "state": state_FIPS = get_state_FIPS(year) fips = list(state_FIPS['FIPS']) elif geoscale == "county": county_FIPS = get_county_FIPS(year) fips = list(county_FIPS['FIPS']) return fips def filter_by_geoscale(df, geoscale): """ Filter flowbyactivity by FIPS at the given scale :param df: Either flowbyactivity or flowbysector :param geoscale: string, either 'national', 'state', or 'county' :return: filtered flowbyactivity or flowbysector """ fips = create_geoscale_list(df, geoscale) df = df[df['Location'].isin(fips)].reset_index(drop=True) if len(df) == 0: log.error("No flows found in the flow dataset at the %s scale", geoscale) else: return df def agg_by_geoscale(df, from_scale, to_scale, groupbycols): """ Aggregate a df by geoscale :param df: flowbyactivity or flowbysector df :param from_scale: str, geoscale to aggregate from ('national', 'state', 'county') :param to_scale: str, geoscale to aggregate to ('national', 'state', 'county') :param groupbycolumns: flowbyactivity or flowbysector default groupby columns :return: df, at identified to_scale geographic level """ # use from scale to filter by these values df = filter_by_geoscale(df, from_scale).reset_index(drop=True) df = update_geoscale(df, to_scale) fba_agg = aggregator(df, groupbycols) return fba_agg def aggregator(df, groupbycols): """ Aggregates flowbyactivity or flowbysector 'FlowAmount' column in df and generate weighted average values based on FlowAmount values for numeric columns :param df: df, Either flowbyactivity or flowbysector :param groupbycols: list, Either flowbyactivity or flowbysector columns :return: df, with aggregated columns """ # reset index df = df.reset_index(drop=True) # tmp replace null values with empty cells df = replace_NoneType_with_empty_cells(df) # drop columns with flowamount = 0 df = df[df['FlowAmount'] != 0] # list of column headers, that if exist in df, should be aggregated using the weighted avg fxn possible_column_headers = ('Spread', 'Min', 'Max', 'DataReliability', 'TemporalCorrelation', 'GeographicalCorrelation', 'TechnologicalCorrelation', 'DataCollection') # list of column headers that do exist in the df being aggregated column_headers = [e for e in possible_column_headers if e in df.columns.values.tolist()] df_dfg = df.groupby(groupbycols).agg({'FlowAmount': ['sum']}) # run through other columns creating weighted average for e in column_headers: df_dfg[e] = get_weighted_average(df, e, 'FlowAmount', groupbycols) df_dfg = df_dfg.reset_index() df_dfg.columns = df_dfg.columns.droplevel(level=1) # if datatypes are strings, ensure that Null values remain NoneType df_dfg = replace_strings_with_NoneType(df_dfg) return df_dfg def sector_ratios(df, sectorcolumn): """ Determine ratios of the less aggregated sectors within a more aggregated sector :param df: A df with sector columns :param sectorcolumn: 'SectorConsumedBy' or 'SectorProducedBy' :return: df, with 'FlowAmountRatio' column """ # drop any null rows (can occur when activities are ranges) df = df[~df[sectorcolumn].isnull()] # find the longest length sector length = max(df[sectorcolumn].apply(lambda x: len(str(x))).unique()) # for loop in reverse order longest length naics minus 1 to 2 # appends missing naics levels to df sec_ratios = [] for i in range(length, 3, -1): # subset df to sectors with length = i and length = i + 1 df_subset = df.loc[df[sectorcolumn].apply(lambda x: len(x) == i)] # create column for sector grouping df_subset = df_subset.assign(Sector_group=df_subset[sectorcolumn].apply(lambda x: x[0:i-1])) # subset df to create denominator df_denom = df_subset[['FlowAmount', 'Location', 'Sector_group']] df_denom = df_denom.groupby(['Location', 'Sector_group'], as_index=False).agg({"FlowAmount": sum}) df_denom = df_denom.rename(columns={"FlowAmount": "Denominator"}) # merge the denominator column with fba_w_sector df ratio_df = df_subset.merge(df_denom, how='left') # calculate ratio ratio_df.loc[:, 'FlowAmountRatio'] = ratio_df['FlowAmount'] / ratio_df['Denominator'] ratio_df = ratio_df.drop(columns=['Denominator', 'Sector_group']).reset_index() sec_ratios.append(ratio_df) # concat list of dataframes (info on each page) df_w_ratios = pd.concat(sec_ratios, sort=True).reset_index(drop=True) return df_w_ratios def sector_aggregation(df_load, group_cols): """ Function that checks if a sector length exists, and if not, sums the less aggregated sector :param df_load: Either a flowbyactivity df with sectors or a flowbysector df :param group_cols: columns by which to aggregate :return: df, with aggregated sector values """ # determine if activities are sector-like, if aggregating a df with a 'SourceName' sector_like_activities = False if 'SourceName' in df_load.columns: # load source catalog cat = load_source_catalog() # for s in pd.unique(flowbyactivity_df['SourceName']): s = pd.unique(df_load['SourceName'])[0] # load catalog info for source src_info = cat[s] sector_like_activities = src_info['sector-like_activities'] # ensure None values are not strings df = replace_NoneType_with_empty_cells(df_load) # if activities are source like, drop from df and group calls, # add back in as copies of sector columns columns to keep if sector_like_activities: group_cols = [e for e in group_cols if e not in ('ActivityProducedBy', 'ActivityConsumedBy')] # subset df df_cols = [e for e in df.columns if e not in ('ActivityProducedBy', 'ActivityConsumedBy')] df = df[df_cols] # find the longest length sector length = df[[fbs_activity_fields[0], fbs_activity_fields[1]]].apply( lambda x: x.str.len()).max().max() length = int(length) # for loop in reverse order longest length naics minus 1 to 2 # appends missing naics levels to df for i in range(length - 1, 1, -1): # subset df to sectors with length = i and length = i + 1 df_subset = df.loc[df[fbs_activity_fields[0]].apply(lambda x: i + 1 >= len(x) >= i) | df[fbs_activity_fields[1]].apply(lambda x: i + 1 >= len(x) >= i)] # create a list of i digit sectors in df subset sector_subset = df_subset[ ['Location', fbs_activity_fields[0], fbs_activity_fields[1]]].drop_duplicates().reset_index(drop=True) df_sectors = sector_subset.copy() df_sectors.loc[:, 'SectorProducedBy'] = \ df_sectors['SectorProducedBy'].apply(lambda x: x[0:i]) df_sectors.loc[:, 'SectorConsumedBy'] = \ df_sectors['SectorConsumedBy'].apply(lambda x: x[0:i]) sector_list = df_sectors.drop_duplicates().values.tolist() # create a list of sectors that are exactly i digits long # where either sector column is i digits in length df_existing_1 = \ sector_subset.loc[(sector_subset['SectorProducedBy'].apply(lambda x: len(x) == i)) | (sector_subset['SectorConsumedBy'].apply(lambda x: len(x) == i))] # where both sector columns are i digits in length df_existing_2 = \ sector_subset.loc[(sector_subset['SectorProducedBy'].apply(lambda x: len(x) == i)) & (sector_subset['SectorConsumedBy'].apply(lambda x: len(x) == i))] # concat existing dfs df_existing = pd.concat([df_existing_1, df_existing_2], sort=False) existing_sectors = df_existing.drop_duplicates().dropna().values.tolist() # list of sectors of length i that are not in sector list missing_sectors = [e for e in sector_list if e not in existing_sectors] if len(missing_sectors) != 0: # new df of sectors that start with missing sectors. # drop last digit of the sector and sum flows # set conditions agg_sectors_list = [] for q, r, s in missing_sectors: c1 = df_subset['Location'] == q c2 = df_subset[fbs_activity_fields[0]].apply(lambda x: x[0:i] == r) c3 = df_subset[fbs_activity_fields[1]].apply(lambda x: x[0:i] == s) # subset data agg_sectors_list.append(df_subset.loc[c1 & c2 & c3]) agg_sectors = pd.concat(agg_sectors_list, sort=False) agg_sectors = agg_sectors.loc[ (agg_sectors[fbs_activity_fields[0]].apply(lambda x: len(x) > i)) | (agg_sectors[fbs_activity_fields[1]].apply(lambda x: len(x) > i))] agg_sectors.loc[:, fbs_activity_fields[0]] = agg_sectors[fbs_activity_fields[0]].apply( lambda x: x[0:i]) agg_sectors.loc[:, fbs_activity_fields[1]] = agg_sectors[fbs_activity_fields[1]].apply( lambda x: x[0:i]) # aggregate the new sector flow amounts agg_sectors = aggregator(agg_sectors, group_cols) # append to df agg_sectors = replace_NoneType_with_empty_cells(agg_sectors) df = df.append(agg_sectors, sort=False).reset_index(drop=True) # manually modify non-NAICS codes that might exist in sector df.loc[:, 'SectorConsumedBy'] = np.where(df['SectorConsumedBy'].isin(['F0', 'F01']), 'F010', df['SectorConsumedBy']) # domestic/household df.loc[:, 'SectorProducedBy'] = np.where(df['SectorProducedBy'].isin(['F0', 'F01']), 'F010', df['SectorProducedBy']) # domestic/household # drop any duplicates created by modifying sector codes df = df.drop_duplicates() # if activities are source-like, set col values as copies of the sector columns if sector_like_activities: df = df.assign(ActivityProducedBy=df['SectorProducedBy']) df = df.assign(ActivityConsumedBy=df['SectorConsumedBy']) # reindex columns df = df.reindex(df_load.columns, axis=1) # replace null values df = replace_strings_with_NoneType(df) return df def sector_disaggregation(df): """ function to disaggregate sectors if there is only one naics at a lower level works for lower than naics 4 :param df: A FBS df, must have sector columns :return: A FBS df with values for the missing naics5 and naics6 """ # ensure None values are not strings df = replace_NoneType_with_empty_cells(df) # load naics 2 to naics 6 crosswalk cw_load = load_sector_length_crosswalk() # for loop min length to 6 digits, where min length cannot be less than 2 length = df[[fbs_activity_fields[0], fbs_activity_fields[1]]].apply( lambda x: x.str.len()).min().min() if length < 2: length = 2 # appends missing naics levels to df for i in range(length, 6): sector_merge = 'NAICS_' + str(i) sector_add = 'NAICS_' + str(i+1) # subset the df by naics length cw = cw_load[[sector_merge, sector_add]] # only keep the rows where there is only one value in sector_add for a value in sector_merge cw = cw.drop_duplicates(subset=[sector_merge], keep=False).reset_index(drop=True) sector_list = cw[sector_merge].values.tolist() # subset df to sectors with length = i and length = i + 1 df_subset = df.loc[df[fbs_activity_fields[0]].apply(lambda x: i + 1 >= len(x) >= i) | df[fbs_activity_fields[1]].apply(lambda x: i + 1 >= len(x) >= i)] # create new columns that are length i df_subset = df_subset.assign(SectorProduced_tmp= df_subset[fbs_activity_fields[0]].apply(lambda x: x[0:i])) df_subset = df_subset.assign(SectorConsumed_tmp= df_subset[fbs_activity_fields[1]].apply(lambda x: x[0:i])) # subset the df to the rows where the tmp sector columns are in naics list df_subset_1 = df_subset.loc[(df_subset['SectorProduced_tmp'].isin(sector_list)) & (df_subset['SectorConsumed_tmp'] == "")] df_subset_2 = df_subset.loc[(df_subset['SectorProduced_tmp'] == "") & (df_subset['SectorConsumed_tmp'].isin(sector_list))] df_subset_3 = df_subset.loc[(df_subset['SectorProduced_tmp'].isin(sector_list)) & (df_subset['SectorConsumed_tmp'].isin(sector_list))] # concat existing dfs df_subset = pd.concat([df_subset_1, df_subset_2, df_subset_3], sort=False) # drop all rows with duplicate temp values, as a less aggregated naics exists # list of column headers, that if exist in df, should be # aggregated using the weighted avg fxn possible_column_headers = ('Flowable', 'FlowName', 'Unit', 'Context', 'Compartment', 'Location', 'Year', 'SectorProduced_tmp', 'SectorConsumed_tmp') # list of column headers that do exist in the df being subset cols_to_drop = [e for e in possible_column_headers if e in df_subset.columns.values.tolist()] df_subset = df_subset.drop_duplicates(subset=cols_to_drop, keep=False).reset_index(drop=True) # merge the naics cw new_naics = pd.merge(df_subset, cw[[sector_merge, sector_add]], how='left', left_on=['SectorProduced_tmp'], right_on=[sector_merge]) new_naics = new_naics.rename(columns={sector_add: "SPB"}) new_naics = new_naics.drop(columns=[sector_merge]) new_naics = pd.merge(new_naics, cw[[sector_merge, sector_add]], how='left', left_on=['SectorConsumed_tmp'], right_on=[sector_merge]) new_naics = new_naics.rename(columns={sector_add: "SCB"}) new_naics = new_naics.drop(columns=[sector_merge]) # drop columns and rename new sector columns new_naics = new_naics.drop(columns=["SectorProducedBy", "SectorConsumedBy", "SectorProduced_tmp", "SectorConsumed_tmp"]) new_naics = new_naics.rename(columns={"SPB": "SectorProducedBy", "SCB": "SectorConsumedBy"}) # append new naics to df new_naics['SectorConsumedBy'] = new_naics['SectorConsumedBy'].replace({np.nan: ""}) new_naics['SectorProducedBy'] = new_naics['SectorProducedBy'].replace({np.nan: ""}) new_naics = replace_NoneType_with_empty_cells(new_naics) df = pd.concat([df, new_naics], sort=True) # replace blank strings with None df = replace_strings_with_NoneType(df) return df def assign_fips_location_system(df, year_of_data): """ Add location system based on year of data. County level FIPS change over the years. :param df: df with FIPS location system :param year_of_data: str, year of data pulled :return: df, with 'LocationSystem' column values """ if year_of_data >= '2015': df.loc[:, 'LocationSystem'] = 'FIPS_2015' elif '2013' <= year_of_data < '2015': df.loc[:, 'LocationSystem'] = 'FIPS_2013' elif '2010' <= year_of_data < '2013': df.loc[:, 'LocationSystem'] = 'FIPS_2010' elif year_of_data < '2010': log.warning( "Missing FIPS codes from crosswalk for %s. Assigning to FIPS_2010", year_of_data) df.loc[:, 'LocationSystem'] = 'FIPS_2010' return df def collapse_fbs_sectors(fbs): """ Collapses the Sector Produced/Consumed into a single column named "Sector" uses based on identified rules for flowtypes :param fbs: df, a standard FlowBySector (format) :return: df, FBS with single Sector column """ # ensure correct datatypes and order fbs = clean_df(fbs, flow_by_sector_fields, fbs_fill_na_dict) # collapse the FBS sector columns into one column based on FlowType fbs.loc[fbs["FlowType"] == 'TECHNOSPHERE_FLOW', 'Sector'] = fbs["SectorConsumedBy"] fbs.loc[fbs["FlowType"] == 'WASTE_FLOW', 'Sector'] = fbs["SectorProducedBy"] fbs.loc[(fbs["FlowType"] == 'WASTE_FLOW') & (fbs['SectorProducedBy'].isnull()), 'Sector'] = fbs["SectorConsumedBy"] fbs.loc[(fbs["FlowType"] == 'ELEMENTARY_FLOW') & (fbs['SectorProducedBy'].isnull()), 'Sector'] = fbs["SectorConsumedBy"] fbs.loc[(fbs["FlowType"] == 'ELEMENTARY_FLOW') & (fbs['SectorConsumedBy'].isnull()), 'Sector'] = fbs["SectorProducedBy"] fbs.loc[(fbs["FlowType"] == 'ELEMENTARY_FLOW') & (fbs['SectorConsumedBy'].isin(['F010', 'F0100', 'F01000'])) & (fbs['SectorProducedBy'].isin(['22', '221', '2213', '22131', '221310'])), 'Sector'] = fbs["SectorConsumedBy"] # drop sector consumed/produced by columns fbs_collapsed = fbs.drop(columns=['SectorProducedBy', 'SectorConsumedBy']) # aggregate fbs_collapsed = aggregator(fbs_collapsed, fbs_collapsed_default_grouping_fields) # sort dataframe fbs_collapsed = clean_df(fbs_collapsed, flow_by_sector_collapsed_fields, fbs_collapsed_fill_na_dict) fbs_collapsed = fbs_collapsed.sort_values(['Sector', 'Flowable', 'Context', 'Location']).reset_index(drop=True) return fbs_collapsed def return_activity_from_scale(df, provided_from_scale): """ Determine the 'from scale' used for aggregation/df subsetting for each activity combo in a df :param df: flowbyactivity df :param provided_from_scale: str, The scale to use specified in method yaml :return: df, FBA with column indicating the "from" geoscale to use for each row """ # determine the unique combinations of activityproduced/consumedby unique_activities = unique_activity_names(df) # filter by geoscale fips = create_geoscale_list(df, provided_from_scale) df_sub = df[df['Location'].isin(fips)] # determine unique activities after subsetting by geoscale unique_activities_sub = unique_activity_names(df_sub) # return df of the difference between unique_activities and unique_activities2 df_missing = dataframe_difference(unique_activities, unique_activities_sub, which='left_only') # return df of the similarities between unique_activities and unique_activities2 df_existing = dataframe_difference(unique_activities, unique_activities_sub, which='both') df_existing = df_existing.drop(columns='_merge') df_existing['activity_from_scale'] = provided_from_scale # for loop through geoscales until find data for each activity combo if provided_from_scale == 'national': geoscales = ['state', 'county'] elif provided_from_scale == 'state': geoscales = ['county'] elif provided_from_scale == 'county': log.info('No data - skipping') if len(df_missing) > 0: for i in geoscales: # filter by geoscale fips_i = create_geoscale_list(df, i) df_i = df[df['Location'].isin(fips_i)] # determine unique activities after subsetting by geoscale unique_activities_i = unique_activity_names(df_i) # return df of the difference between unique_activities subset and # unique_activities for geoscale df_missing_i = dataframe_difference(unique_activities_sub, unique_activities_i, which='right_only') df_missing_i = df_missing_i.drop(columns='_merge') df_missing_i['activity_from_scale'] = i # return df of the similarities between unique_activities and unique_activities2 df_existing_i = dataframe_difference(unique_activities_sub, unique_activities_i, which='both') # append unique activities and df with defined activity_from_scale unique_activities_sub = \ unique_activities_sub.append(df_missing_i[[fba_activity_fields[0], fba_activity_fields[1]]]) df_existing = df_existing.append(df_missing_i) df_missing = dataframe_difference(df_missing[[fba_activity_fields[0], fba_activity_fields[1]]], df_existing_i[[fba_activity_fields[0], fba_activity_fields[1]]], which=None) return df_existing def subset_df_by_geoscale(df, activity_from_scale, activity_to_scale): """ Subset a df by geoscale or agg to create data specified in method yaml :param df: df, FBA format :param activity_from_scale: str, identified geoscale by which to subset or aggregate from ('national', 'state', 'county') :param activity_to_scale: str, identified geoscale by which to subset or aggregate to ('national', 'state', 'county') :return: df, FBA, subset or aggregated to a single geoscale for all rows """ # method of subset dependent on LocationSystem if df['LocationSystem'].str.contains('FIPS').any(): df = df[df['LocationSystem'].str.contains('FIPS')].reset_index(drop=True) # determine 'activity_from_scale' for use in df geoscale subset, by activity modified_from_scale = return_activity_from_scale(df, activity_from_scale) # add 'activity_from_scale' column to df df2 = pd.merge(df, modified_from_scale) # list of unique 'from' geoscales unique_geoscales =\ modified_from_scale['activity_from_scale'].drop_duplicates().values.tolist() if len(unique_geoscales) > 1: log.info('Dataframe has a mix of geographic levels: %s', ', '.join(unique_geoscales)) # to scale if fips_number_key[activity_from_scale] > fips_number_key[activity_to_scale]: to_scale = activity_to_scale else: to_scale = activity_from_scale df_subset_list = [] # subset df based on activity 'from' scale for i in unique_geoscales: df3 = df2[df2['activity_from_scale'] == i] # if desired geoscale doesn't exist, aggregate existing data # if df is less aggregated than allocation df, aggregate # fba activity to allocation geoscale if fips_number_key[i] > fips_number_key[to_scale]: log.info("Aggregating subset from %s to %s", i, to_scale) df_sub = agg_by_geoscale(df3, i, to_scale, fba_mapped_default_grouping_fields) # else filter relevant rows else: log.info("Subsetting %s data", i) df_sub = filter_by_geoscale(df3, i) df_subset_list.append(df_sub) df_subset = pd.concat(df_subset_list, ignore_index=True) # only keep cols associated with FBA mapped df_subset = clean_df(df_subset, flow_by_activity_mapped_fields, fba_fill_na_dict, drop_description=False) # right now, the only other location system is for Statistics Canada data else: df_subset = df.copy() return df_subset def unique_activity_names(fba_df): """ Determine the unique activity names in a df :param fba_df: a flowbyactivity df :return: df with ActivityProducedBy and ActivityConsumedBy columns """ activities = fba_df[[fba_activity_fields[0], fba_activity_fields[1]]] unique_activities = activities.drop_duplicates().reset_index(drop=True) return unique_activities def dataframe_difference(df1, df2, which=None): """ Find rows which are different between two DataFrames :param df1: df, FBA or FBS :param df2: df, FBA or FBS :param which: 'both', 'right_only', 'left_only' :return: df, comparison of data in the two dfs """ comparison_df = df1.merge(df2, indicator=True, how='outer') if which is None: diff_df = comparison_df[comparison_df['_merge'] != 'both'] else: diff_df = comparison_df[comparison_df['_merge'] == which] return diff_df def estimate_suppressed_data(df, sector_column, naics_level, sourcename): """ Estimate data suppression, by equally allocating parent NAICS values to child NAICS :param df: df with sector columns :param sector_column: str, column to estimate suppressed data for :param naics_level: numeric, indicate at what NAICS length to base estimated suppresed data off (2 - 5) :param sourcename: str, sourcename :return: df, with estimated suppressed data """ # exclude nonsectors df = replace_NoneType_with_empty_cells(df) # find the longest length sector max_length = max(df[sector_column].apply(lambda x: len(str(x))).unique()) # loop through starting at naics_level, use most detailed level possible to save time for i in range(naics_level, max_length): # create df of i length df_x = df.loc[df[sector_column].apply(lambda x: len(x) == i)] # create df of i + 1 length df_y = df.loc[df[sector_column].apply(lambda x: len(x) == i + 1)] # create temp sector columns in df y, that are i digits in length df_y = df_y.assign(s_tmp=df_y[sector_column].apply(lambda x: x[0:i])) # create list of location and temp activity combos that contain a 0 missing_sectors_df = df_y[df_y['FlowAmount'] == 0] missing_sectors_list = missing_sectors_df[['Location', 's_tmp']].drop_duplicates().values.tolist() # subset the y df if len(missing_sectors_list) != 0: # new df of sectors that start with missing sectors. # drop last digit of the sector and sum flows set conditions suppressed_list = [] for q, r, in missing_sectors_list: c1 = df_y['Location'] == q c2 = df_y['s_tmp'] == r # subset data suppressed_list.append(df_y.loc[c1 & c2]) suppressed_sectors = pd.concat(suppressed_list, sort=False, ignore_index=True) # add column of existing allocated data for length of i suppressed_sectors['alloc_flow'] =\ suppressed_sectors.groupby(['Location', 's_tmp'])['FlowAmount'].transform('sum') # subset further so only keep rows of 0 value suppressed_sectors_sub = suppressed_sectors[suppressed_sectors['FlowAmount'] == 0] # add count suppressed_sectors_sub = \ suppressed_sectors_sub.assign(sector_count= suppressed_sectors_sub.groupby( ['Location', 's_tmp'] )['s_tmp'].transform('count')) # merge suppressed sector subset with df x df_m = pd.merge(df_x, suppressed_sectors_sub[['Class', 'Compartment', 'FlowType', 'FlowName', 'Location', 'LocationSystem', 'Unit', 'Year', sector_column, 's_tmp', 'alloc_flow', 'sector_count']], left_on=['Class', 'Compartment', 'FlowType', 'FlowName', 'Location', 'LocationSystem', 'Unit', 'Year', sector_column], right_on=['Class', 'Compartment', 'FlowType', 'FlowName', 'Location', 'LocationSystem', 'Unit', 'Year', 's_tmp'], how='right') # drop any rows where flowamount is none df_m = df_m[~df_m['FlowAmount'].isna()] # calculate estimated flows by subtracting the flow # amount already allocated from total flow of # sector one level up and divide by number of sectors with suppressed data df_m.loc[:, 'FlowAmount'] = \ (df_m['FlowAmount'] - df_m['alloc_flow']) / df_m['sector_count'] # only keep the suppressed sector subset activity columns df_m = df_m.drop(columns=[sector_column + '_x', 's_tmp', 'alloc_flow', 'sector_count']) df_m = df_m.rename(columns={sector_column + '_y': sector_column}) # reset activity columns if load_source_catalog()[sourcename]['sector-like_activities']: df_m = df_m.assign(ActivityProducedBy=df_m['SectorProducedBy']) df_m = df_m.assign(ActivityConsumedBy=df_m['SectorConsumedBy']) # drop the existing rows with suppressed data and append the new estimates from fba df modified_df =\ pd.merge(df, df_m[['FlowName', 'Location', sector_column]], indicator=True, how='outer').query('_merge=="left_only"').drop('_merge', axis=1) df = pd.concat([modified_df, df_m], ignore_index=True) df_w_estimated_data = replace_strings_with_NoneType(df) return df_w_estimated_data def collapse_activity_fields(df): """ The 'activityconsumedby' and 'activityproducedby' columns from the allocation dataset do not always align with the dataframe being allocated. Generalize the allocation activity column. :param df: df, FBA used to allocate another FBA :return: df, single Activity column """ df = replace_strings_with_NoneType(df) activity_consumed_list = df['ActivityConsumedBy'].drop_duplicates().values.tolist() activity_produced_list = df['ActivityProducedBy'].drop_duplicates().values.tolist() # if an activity field column is all 'none', drop the column and # rename renaming activity columns to generalize if all(v is None for v in activity_consumed_list): df = df.drop(columns=['ActivityConsumedBy', 'SectorConsumedBy']) df = df.rename(columns={'ActivityProducedBy': 'Activity', 'SectorProducedBy': 'Sector'}) elif all(v is None for v in activity_produced_list): df = df.drop(columns=['ActivityProducedBy', 'SectorProducedBy']) df = df.rename(columns={'ActivityConsumedBy': 'Activity', 'SectorConsumedBy': 'Sector'}) else: log.error('Cannot generalize dataframe') # drop other columns df = df.drop(columns=['ProducedBySectorType', 'ConsumedBySectorType']) return df def dynamically_import_fxn(data_source_scripts_file, function_name): """ Dynamically import a function and call on that function :param data_source_scripts_file: str, file name where function is found :param function_name: str, name of function to import and call on :return: a function """ # if a file does not exist modify file name, dropping ext after last underscore data_source_scripts_file = find_true_file_path(datasourcescriptspath, data_source_scripts_file, 'py') df = getattr(__import__(f"{'flowsa.data_source_scripts.'}{data_source_scripts_file}", fromlist=function_name), function_name) return df def load_fba_w_standardized_units(datasource, year, **kwargs): """ Standardize how a FBA is loaded for allocation purposes when generating a FBS. Important to immediately convert the df units to standardized units. :param datasource: string, FBA source name :param year: int, year of data :param kwargs: optional parameters include flowclass, geographic_level, and download_if_missing :return: fba df with standardized units """ # determine if any addtional parameters required to load a Flow-By-Activity # add parameters to dictionary if exist in method yaml fba_dict = {} if 'flowclass' in kwargs: fba_dict['flowclass'] = kwargs['flowclass'] if 'geographic_level' in kwargs: fba_dict['geographic_level'] = kwargs['geographic_level'] # load the allocation FBA fba = flowsa.getFlowByActivity(datasource, year, **fba_dict).reset_index(drop=True) # ensure df loaded correctly/has correct dtypes fba = clean_df(fba, flow_by_activity_fields, fba_fill_na_dict) # convert to standardized units fba = standardize_units(fba) return fba
46.97027
100
0.638328
c36ac95cc72518ab4ece08d5acbd4426fda00fc2
994
dart
Dart
lib/common/screens.i18n.dart
thegergo02/mobile
c9d22fb411b1a5ca87a5b573e6361cabb12e7fea
[ "BSD-3-Clause" ]
1
2021-09-05T23:21:11.000Z
2021-09-05T23:21:11.000Z
lib/common/screens.i18n.dart
thegergo02/mobile
c9d22fb411b1a5ca87a5b573e6361cabb12e7fea
[ "BSD-3-Clause" ]
5
2021-09-10T14:30:02.000Z
2022-02-12T10:16:34.000Z
lib/common/screens.i18n.dart
thegergo02/mobile
c9d22fb411b1a5ca87a5b573e6361cabb12e7fea
[ "BSD-3-Clause" ]
8
2021-08-31T12:21:05.000Z
2022-03-15T17:59:23.000Z
import 'package:i18n_extension/i18n_extension.dart'; extension ScreensLocalization on String { static final _t = Translations.byLocale("hu_hu") + { "en_en": { "home": "Home", "grades": "Grades", "timetable": "Timetable", "messages": "Messages", "absences": "Absences", }, "hu_hu": { "home": "Kezdőlap", "grades": "Jegyek", "timetable": "Órarend", "messages": "Üzenetek", "absences": "Hiányok", }, "de_de": { "home": "Zuhause", "grades": "Noten", "timetable": "Zeitplan", "messages": "Mitteilungen", "absences": "Abwesenheiten", }, }; String get i18n => localize(this, _t); String fill(List<Object> params) => localizeFill(this, params); String plural(int value) => localizePlural(value, this, _t); String version(Object modifier) => localizeVersion(modifier, this, _t); }
29.235294
73
0.534205
f068f8c1d5ccf6cc5cfbfd82067c48bf851be339
259
js
JavaScript
public/js/form.js
Mabloq/mabloq-laravel
0cc951662ef21282b399fe1c954b0d7cc62272ff
[ "MIT" ]
null
null
null
public/js/form.js
Mabloq/mabloq-laravel
0cc951662ef21282b399fe1c954b0d7cc62272ff
[ "MIT" ]
null
null
null
public/js/form.js
Mabloq/mabloq-laravel
0cc951662ef21282b399fe1c954b0d7cc62272ff
[ "MIT" ]
null
null
null
$('form.ajax').on('submit', function() { console.log("trigger"); var data= {}; that.find('[name]').each(function(){ var el = $(this), name = el.attr('name'), value = el.val(); data[name] = value; }); $.ajax({ }) return false });
15.235294
40
0.513514
0639cf0f86a1954944d58e5d863d6f1cf926bce4
5,419
sql
SQL
TSQL2PGSQL/pg_sqlisdb.sql
dmitrykolchev/TSQL2PGSQL
ac87a3a5ecf323c9b04ff3215c26f1b3b7a8c604
[ "MIT" ]
4
2018-03-12T19:13:38.000Z
2021-02-22T19:53:31.000Z
TSQL2PGSQL/pg_sqlisdb.sql
dmitrykolchev/TSQL2PGSQL
ac87a3a5ecf323c9b04ff3215c26f1b3b7a8c604
[ "MIT" ]
null
null
null
TSQL2PGSQL/pg_sqlisdb.sql
dmitrykolchev/TSQL2PGSQL
ac87a3a5ecf323c9b04ff3215c26f1b3b7a8c604
[ "MIT" ]
null
null
null
create schema "identity_server"; create table "identity_server"."user_access_right" ( "user_id" int not null, "access_right_id" int not null, constraint "pk_user_access_right" primary key ("user_id", "access_right_id") ); create table "identity_server"."api_resource_claim" ( "api_resource_code" varchar(128) not null, "claim" varchar(128) not null, "value" text not null, constraint "pk_api_resource_claim" primary key ("api_resource_code", "claim") ); create table "identity_server"."api_resource" ( "code" varchar(128) not null, "name" varchar(256) not null, constraint "pk_api_resource" primary key ("code") ); create table "identity_server"."role_access_right" ( "role_id" int not null, "access_right_id" int not null, constraint "pk_role_access_right" primary key ("role_id", "access_right_id") ); create table "identity_server"."access_right" ( "id" serial not null, "state" smallint not null, "client_id" int not null, "code" varchar(128) not null, "name" varchar(256) not null, constraint "pk_access_right" primary key ("id"), constraint "ak_access_right_code" unique ("code") ); create table "identity_server"."user_role" ( "user_id" int not null, "role_id" int not null, constraint "pk_user_role" primary key ("user_id", "role_id") ); create table "identity_server"."user_profile" ( "user_id" int not null, "claim" varchar(128) not null, "value" text not null, constraint "pk_user_profile" primary key ("user_id", "claim") ); create table "identity_server"."role" ( "id" serial not null, "state" smallint not null, "client_id" int not null, "code" varchar(128) not null, "cn" varchar(128) null, "name" varchar(256) not null, constraint "pk_role" primary key ("id"), constraint "ak_role_code" unique ("client_id", "code") ); create table "identity_server"."provider" ( "id" int not null, "state" smallint not null, "code" varchar(128) not null, "name" varchar(256) not null, "provider_type" varchar(512) not null, "parameters" text null, constraint "pk_provider" primary key ("id"), constraint "ak_provider_code" unique ("code") ); create table "identity_server"."user_account" ( "id" serial not null, "state" smallint not null, "client_id" int not null, "name" varchar(256) not null, "normalized_name" varchar(256) not null, "email" varchar(256) null, "normalized_email" varchar(256) null, "email_confirmed" bool not null, "password_hash" varchar(256) null, "security_stamp" varchar(256) null, "concurency_stamp" varchar(256) not null, "phone_number" varchar(256) null, "phone_number_confirmed" bool not null, "two_factor_enabled" bool not null, "lockout_end" timestamp null, "lockout_enabled" bool not null, "access_failed_count" int not null, "modified_date" timestamp not null, constraint "pk_user_account" primary key ("id"), constraint "ak_user_account_name" unique ("client_id", "name") ); create table "identity_server"."client" ( "id" serial not null, "state" smallint not null, "provider_id" int not null, "code" varchar(128) not null, "name" varchar(256) not null, "grant_types" varchar(256) not null, "client_uri" varchar(512) null, "redirect_uri" varchar(512) null, "postlogout_uri" varchar(512) null, "secret" varchar(256) null, "require_consent" bool not null, "allowed_scopes" varchar(512) null, "user_id" int null, "logo" text null, "comments" text null, constraint "pk_client" primary key ("id") ); alter table "identity_server"."user_access_right" add constraint "fk_user_access_right_user_account" foreign key ("user_id") references "identity_server"."user_account" ("id"); alter table "identity_server"."user_access_right" add constraint "fk_user_access_right_access_right" foreign key ("access_right_id") references "identity_server"."access_right" ("id"); alter table "identity_server"."api_resource_claim" add constraint "fk_api_resource_claim_api_resource" foreign key ("api_resource_code") references "identity_server"."api_resource" ("code"); alter table "identity_server"."role_access_right" add constraint "fk_role_access_right_role" foreign key ("role_id") references "identity_server"."role" ("id"); alter table "identity_server"."role_access_right" add constraint "fk_role_access_right_access_right" foreign key ("access_right_id") references "identity_server"."access_right" ("id"); alter table "identity_server"."access_right" add constraint "fk_access_right_client" foreign key ("client_id") references "identity_server"."client" ("id"); alter table "identity_server"."user_role" add constraint "fk_user_role_user_account" foreign key ("user_id") references "identity_server"."user_account" ("id"); alter table "identity_server"."user_role" add constraint "fk_user_role_role" foreign key ("role_id") references "identity_server"."role" ("id"); alter table "identity_server"."user_profile" add constraint "fk_user_profile_user_account" foreign key ("user_id") references "identity_server"."user_account" ("id"); alter table "identity_server"."role" add constraint "fk_role_client" foreign key ("client_id") references "identity_server"."client" ("id"); alter table "identity_server"."user_account" add constraint "fk_user_account_client" foreign key ("client_id") references "identity_server"."client" ("id"); alter table "identity_server"."client" add constraint "fk_client_provider" foreign key ("provider_id") references "identity_server"."provider" ("id");
36.126667
140
0.752353
0adc0b9550c5bafc0d4a8baaa8f292c4be4ffc77
5,383
dart
Dart
lib/music_player/music_player.dart
flutterme/flutter_app
34bd89f9d486cb25507fc36398eb3f838d040061
[ "Apache-2.0" ]
2
2020-12-03T06:58:24.000Z
2021-01-13T01:16:18.000Z
lib/music_player/music_player.dart
collectFlutter/flutter_app
34bd89f9d486cb25507fc36398eb3f838d040061
[ "Apache-2.0" ]
null
null
null
lib/music_player/music_player.dart
collectFlutter/flutter_app
34bd89f9d486cb25507fc36398eb3f838d040061
[ "Apache-2.0" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:flutter_app/store/index.dart'; import 'index.dart'; import 'package:flutter_app/page_index.dart'; import 'package:flutter_vector_icons/flutter_vector_icons.dart'; class MusicPlayerPage extends StatefulWidget { @override createState() => _MusicPlayerPageState(); } class _MusicPlayerPageState extends State<MusicPlayerPage> with SingleTickerProviderStateMixin { AnimationController _controller; @override void initState() { super.initState(); _controller = AnimationController(vsync: this, duration: Duration(seconds: 5)); //动画开始、结束、向前移动或向后移动时会调用StatusListener _controller.addStatusListener((status) { if (status == AnimationStatus.completed) { /// 动画从 controller.forward() 正向执行 结束时会回调此方法 debugPrint("status is completed"); /// 重置起点 _controller.reset(); /// 开启 _controller.forward(); } }); WidgetsBinding.instance.addPostFrameCallback((callback) { var value = Store.value<MusicModel>(context, listen: false); if (value.allSongs.length == 0) { value.getMusics(); } }); } @override void dispose() { _controller?.dispose(); super.dispose(); } @override Widget build(BuildContext context) { var snapshot = Store.value<MusicModel>(context); return Scaffold( appBar: AppBar( brightness: Brightness.light, iconTheme: lightIconTheme, backgroundColor: Colors.transparent, leading: IconButton( icon: Icon(SimpleLineIcons.arrow_left, size: 20), onPressed: () => Navigator.pop(context)), elevation: 0.0, actions: <Widget>[ IconButton( icon: Icon(SimpleLineIcons.playlist, size: 20), onPressed: () => showMusicListBottomSheet(context)) ]), body: Column(children: <Widget>[ // Seek bar Expanded( child: RadialSeekBarUI( imageUrl: snapshot.curSong?.albumArtUrl, controller: _controller, thumbPercent: snapshot.progress, onDragStart: (double percent) { if (snapshot.isPlaying) snapshot.togglePlay(); }, onDragEnd: (double percent) { snapshot.togglePlay(); }, onDragUpdate: (double percent) { snapshot.seekPlay(percent); })), // Lyric Container(height: 125.0, width: double.infinity), // Song title, artist name, and controls _buildBottomControls(snapshot) ])); } Widget _buildBottomControls(MusicModel snapshot) { return Container( width: double.infinity, child: Material( color: accentColor, shadowColor: const Color(0x44000000), child: Padding( padding: EdgeInsets.only( top: 40, bottom: 50.0 + Utils.bottomSafeHeight), child: Column(children: <Widget>[ Text('${snapshot.curSong?.title}', style: TextStyle( color: Colors.white, fontSize: 14, fontWeight: FontWeight.bold, letterSpacing: 4.0, height: 1.5)), Text("${snapshot?.positionText} / ${snapshot?.durationText}", style: TextStyle( color: Colors.white.withOpacity(0.75), fontSize: 12, fontWeight: FontWeight.bold, letterSpacing: 3.0, height: 1.5)), Padding( padding: EdgeInsets.only(top: 40), child: Row(children: <Widget>[ Spacer(), _buildPreviousButton(snapshot), Spacer(), _buildPlayPausedButton(snapshot), Spacer(), _buildNextButton(snapshot), Spacer() ])) ])))); } Widget _buildNextButton(MusicModel snapshot) { return IconButton( splashColor: lightAccentColor, highlightColor: Colors.transparent, icon: Icon(Icons.skip_next, color: Colors.white, size: 35), onPressed: () => snapshot.nextMusic()); } Widget _buildPreviousButton(MusicModel snapshot) { return IconButton( splashColor: lightAccentColor, highlightColor: Colors.transparent, icon: Icon(Icons.skip_previous, color: Colors.white, size: 35), onPressed: () => snapshot.prePlay()); } Widget _buildPlayPausedButton(MusicModel snapshot) { return CircleButton( onPressedAction: () { snapshot.togglePlay(); }, fillColor: Colors.white, splashColor: lightAccentColor, highlightColor: lightAccentColor.withOpacity(0.5), elevation: 10.0, highlightElevation: 5, icon: snapshot.isPlaying ? Icons.pause : Icons.play_arrow, iconSize: 35, size: 50, iconColor: darkAccentColor, ); } }
32.624242
79
0.548207
e51a5e628bb8a343d3ebd7534264e43dff2cec60
1,450
ts
TypeScript
apps/eshop/src/app/login/login/entries.ts
zoemy/bsf-course-ng-advanced
9771405b097d3966deeee309730258f1dc39c404
[ "MIT" ]
1
2019-09-21T13:55:57.000Z
2019-09-21T13:55:57.000Z
apps/eshop/src/app/login/login/entries.ts
zoemy/bsf-course-ng-advanced
9771405b097d3966deeee309730258f1dc39c404
[ "MIT" ]
22
2019-09-11T22:02:39.000Z
2022-02-12T21:12:28.000Z
apps/eshop/src/app/login/login/entries.ts
zoemy/bsf-course-ng-advanced
9771405b097d3966deeee309730258f1dc39c404
[ "MIT" ]
1
2019-09-21T13:56:00.000Z
2019-09-21T13:56:00.000Z
import { FieldType } from "@glotrix/ui/forms"; import { Banner } from '@glotrix/ui/login'; export const banner: Banner = { upperText: 'BXCOMMERCE', title: 'Te esperábamos!', imageUrl: 'https://thumbs.dreamstime.com/z/mobile-shopping-online-cartoon-business-idea-concept-47222246.jpg', contentText: 'Aquí encontrarás lo que estabas buscando. Tenemos cada día más tiendas a tu alcance!. Compra fácil ràpido y seguro ahorrando tiempo y dinero con nuestras ofertas. Pago Contra Entrega.Ventajas: Extensa variedad De productos.' } export const loginEntries: FieldType[] = [ { controlType: 'textbox', value: '', key: 'username', label: 'Email', placeholder: 'user@example.com', order: 1, col: 'col-sm-12', validations: { pattern: { message: 'The email is not valid', value: '^[a-z0-9._%+-]+@[a-z0-9.-]+.[a-z]{2,4}$' }, minlength: { message: 'Password must be at least three characters.', value: 3 }, required: { message: 'Password is required.', value: true } } }, { controlType: 'password', value: '', key: 'password', label: 'Password', order: 2, col: 'col-sm-12', validations: { minlength: { message: 'Password must be at least three characters.', value: 3 }, required: { message: 'Password is required.', value: true } } } ];
26.851852
240
0.593793
e7791a6bccc1a8187c297331d8a1bce5130b711f
124
js
JavaScript
test/dummy.js
hville/unnode
9dcab4f2d39495104bdc4662affb3ed76c25ee51
[ "MIT" ]
null
null
null
test/dummy.js
hville/unnode
9dcab4f2d39495104bdc4662affb3ed76c25ee51
[ "MIT" ]
null
null
null
test/dummy.js
hville/unnode
9dcab4f2d39495104bdc4662affb3ed76c25ee51
[ "MIT" ]
null
null
null
import x from '/_lib/assert-op.js' import y from '/_lib/assert-op/index.js' import z from '/_lib/assert-op/src/test-own.js'
31
47
0.725806
39e514f0cfd1622f30319b8e6f9b0467e6736954
492
java
Java
src/main/java/io/spring/core/article/Tag.java
aisensiy/realworld-backend-spring-boot-jpa
959d718a109455933b6271a816f24bd5baa6b507
[ "MIT" ]
null
null
null
src/main/java/io/spring/core/article/Tag.java
aisensiy/realworld-backend-spring-boot-jpa
959d718a109455933b6271a816f24bd5baa6b507
[ "MIT" ]
null
null
null
src/main/java/io/spring/core/article/Tag.java
aisensiy/realworld-backend-spring-boot-jpa
959d718a109455933b6271a816f24bd5baa6b507
[ "MIT" ]
null
null
null
package io.spring.core.article; import java.util.UUID; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; @Entity @Table(name = "tags") @NoArgsConstructor @Data @EqualsAndHashCode(of = "name") public class Tag { @Id private String id; private String name; public Tag(String name) { this.id = UUID.randomUUID().toString(); this.name = name; } }
19.68
43
0.745935