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
57d2d6cd9a8eccbfdecd48bb08dc7c6b2d993c5c
1,477
dart
Dart
lib/common/compress_process.dart
n7484443/image_cropping
3367d13cebdf1b3139c277c75fbbb6d7307e97f4
[ "MIT" ]
null
null
null
lib/common/compress_process.dart
n7484443/image_cropping
3367d13cebdf1b3139c277c75fbbb6d7307e97f4
[ "MIT" ]
null
null
null
lib/common/compress_process.dart
n7484443/image_cropping
3367d13cebdf1b3139c277c75fbbb6d7307e97f4
[ "MIT" ]
null
null
null
import 'dart:typed_data'; import 'package:image/image.dart' as Library; /// compressing cropping process is done here class ImageProcess { /// image bytes which will be of user's picked image. Uint8List imageBytes; ImageProcess(this.imageBytes); /// compressed image is shown for user's reference void compress(Function() onBytesLoaded, Function(Library.Image) onLibraryImageLoaded) async { final libraryImage = getCompressedImage(imageBytes); onBytesLoaded.call(); onLibraryImageLoaded.call(libraryImage); } /// Image cropping will be done by crop method void crop( Library.Image libraryImage, int imageCropX, int imageCropY, int imageCropWidth, int imageCropHeight, Function(Library.Image, Uint8List) onImageLoaded) async { libraryImage = Library.copyCrop( libraryImage, imageCropX, imageCropY, imageCropWidth, imageCropHeight, ); final _libraryUInt8List = Uint8List.fromList( Library.encodeJpg( libraryImage, quality: 100, ), ); onImageLoaded.call(libraryImage, _libraryUInt8List); } static Library.Image getCompressedImage(Uint8List _imageData) { Library.Image image = Library.decodeImage(_imageData)!; if (image.width > 1920) { image = Library.copyResize(image, width: 1920); } else if (image.height > 1920) { image = Library.copyResize(image, height: 1920); } return image; } }
26.854545
65
0.687204
2f3405511cfb3c4a53bf9283346fbbcf991c3c21
1,318
java
Java
tests/de/ethasia/exorions/interactors/mocks/MockPresentersFactory.java
TheYaumrDevR/Exorions
8384df470c53fcbf6268da6f2f850b898ebcf254
[ "MIT" ]
2
2019-05-31T22:26:07.000Z
2019-06-01T08:44:16.000Z
tests/de/ethasia/exorions/interactors/mocks/MockPresentersFactory.java
TheYaumrDevR/Exorions
8384df470c53fcbf6268da6f2f850b898ebcf254
[ "MIT" ]
8
2018-12-23T13:30:09.000Z
2019-10-09T20:45:59.000Z
tests/de/ethasia/exorions/interactors/mocks/MockPresentersFactory.java
TheYaumrDevR/Exorions
8384df470c53fcbf6268da6f2f850b898ebcf254
[ "MIT" ]
null
null
null
package de.ethasia.exorions.interactors.mocks; import de.ethasia.exorions.interactors.crosslayer.DebugWarningLogPresenter; import de.ethasia.exorions.interactors.crosslayer.DialogWindowPresenter; import de.ethasia.exorions.interactors.crosslayer.FatalErrorPresenter; import de.ethasia.exorions.interactors.crosslayer.OverworldStatePresenter; import de.ethasia.exorions.interactors.crosslayer.PlayerAvatarMovementPresenter; import de.ethasia.exorions.interactors.interfaces.PresentersFactory; public class MockPresentersFactory extends PresentersFactory { @Override public DialogWindowPresenter createDialogWindowPresenter() { return new DialogWindowPresenterMock(); } @Override public OverworldStatePresenter createOverworldStatePresenter() { return new OverworldStatePresenterMock(); } @Override public FatalErrorPresenter createFatalErrorPresenter() { return new FatalErrorPresenterMock(); } @Override public PlayerAvatarMovementPresenter createPlayerAvatarMovementPresenter() { return new PlayerAvatarMovementPresenterMock(); } @Override public DebugWarningLogPresenter getDebugWarningLogPresenterSingletonInstance() { return new DebugWarningLogPresenterMock(); } }
36.611111
85
0.7739
19a13f2d1239a47f8d456d029a1dedbe3ae381e1
161
sql
SQL
src/test/resources/sql/select/f83b869d.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
66
2018-06-15T11:34:03.000Z
2022-03-16T09:24:49.000Z
src/test/resources/sql/select/f83b869d.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
13
2019-03-19T11:56:28.000Z
2020-08-05T04:20:50.000Z
src/test/resources/sql/select/f83b869d.sql
Shuttl-Tech/antlr_psql
fcf83192300abe723f3fd3709aff5b0c8118ad12
[ "MIT" ]
28
2019-01-05T19:59:02.000Z
2022-03-24T11:55:50.000Z
-- file:password.sql ln:76 expect:true SELECT rolname, rolpassword FROM pg_authid WHERE rolname LIKE 'regress_passwd%' ORDER BY rolname, rolpassword
26.833333
40
0.751553
0a0f74d53105e1b9837119339b4bbb2ffd472fc4
354
asm
Assembly
oeis/059/A059837.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/059/A059837.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/059/A059837.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A059837: Diagonal T(s,s) of triangle A059836. ; Submitted by Jon Maiga ; 1,1,4,18,144,1200,14400,176400,2822400,45722880,914457600,18441561600,442597478400,10685567692800,299195895398400,8414884558080000,269276305858560000,8646761377013760000,311283409572495360000 mov $1,1 mov $2,$0 lpb $0 sub $0,1 mul $1,$2 sub $2,$3 cmp $3,0 lpe mov $0,$1
25.285714
193
0.759887
dc0a649e7ed3a9b0579b02c80ff4a594bc97c646
1,727
dart
Dart
example/lib/main.dart
mono424/oex
3734fa8162a96bdbed13529d863aa3c2d1b1a650
[ "MIT" ]
null
null
null
example/lib/main.dart
mono424/oex
3734fa8162a96bdbed13529d863aa3c2d1b1a650
[ "MIT" ]
null
null
null
example/lib/main.dart
mono424/oex
3734fa8162a96bdbed13529d863aa3c2d1b1a650
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:oex/models/OEXEngine.dart'; import 'package:oex/oex.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'Flutter Demo', theme: ThemeData( primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key? key, required this.title}) : super(key: key); final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { List<OEXEngine> engines = []; Future<void> getEngines() async { final result = await OEX.search(); setState(() { engines = result; }); } void start(OEXEngine engine) async { Stream output = await engine.start(); output.listen((out) {print(out);}); Future.delayed(Duration(milliseconds: 500)); engine.send("uci"); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: ListView.builder( itemCount: engines.length, itemBuilder: (context, index) { OEXEngine engine = engines[index]; return ListTile( title: Text(engine.name), subtitle: Text("${engine.versionCode} / ${engine.enginePath}"), onTap: () => start(engine), ); } ), floatingActionButton: FloatingActionButton( onPressed: getEngines, tooltip: 'Search', child: Icon(Icons.power_settings_new), ), ); } }
23.657534
75
0.619572
965cfa87e6fa260a94aa89d439806f6ee3d5653a
1,747
php
PHP
application/index/controller/seller_kefu/Kefu.php
zhugenihao/tp5
03ecc88fbdb0fc0d8e711940f9f239a902555567
[ "Apache-2.0" ]
null
null
null
application/index/controller/seller_kefu/Kefu.php
zhugenihao/tp5
03ecc88fbdb0fc0d8e711940f9f239a902555567
[ "Apache-2.0" ]
null
null
null
application/index/controller/seller_kefu/Kefu.php
zhugenihao/tp5
03ecc88fbdb0fc0d8e711940f9f239a902555567
[ "Apache-2.0" ]
null
null
null
<?php /** * 客服信息 */ namespace app\index\controller\seller_kefu; use app\index\controller\SellerCommon; use \think\Db; use app\index\model\Kefu as kefuModel; class Kefu extends SellerCommon { public function kefu_list() { $store = $this->store; $kefu = kefuModel::getList(['store_id' => $store['id']], 10); $this->assign('kefu', $kefu->toArray()); $this->assign('page', $kefu->render()); return $this->fetch(); } public function kefu_add() { $store = $this->store; if ($this->request->isAjax()) { $result = kefuModel::kefuAddMd($store['id']); if ($result) { Tobesuccess('添加成功'); } else { Tiperror("添加失败!"); } } return $this->fetch(); } public function kefu_details() { if ($this->request->isAjax()) { $result = kefuModel::kefuEditMd(); if ($result) { Tobesuccess('编辑成功'); } else { Tiperror("编辑失败!"); } } $info = kefuModel::get(input('kefu_id')); $this->assign('info', $info); return $this->fetch(); } /** * 删除客服 */ public function delKefu() { if ($this->request->isAjax()) { $id_str = input('id_str'); $id_arr = explode(",", $id_str); if (empty($id_arr)) { Tiperror("您未选择!"); } $result = kefuModel::destroy($id_arr); if ($result) { Tobesuccess('删除成功'); } else { Tiperror("删除失败"); } } } }
24.605634
70
0.439038
17c71cdb7dec54c962d4bee48aaf387ae4060400
1,061
cs
C#
Mediator/Mediator.Core/PipelineBehaviours/ValidationPipelineBehaviour.cs
jokk-itu/BookVacation
563e269e9e5dff8920275cab8a6082bd8f8c3859
[ "Apache-2.0" ]
null
null
null
Mediator/Mediator.Core/PipelineBehaviours/ValidationPipelineBehaviour.cs
jokk-itu/BookVacation
563e269e9e5dff8920275cab8a6082bd8f8c3859
[ "Apache-2.0" ]
null
null
null
Mediator/Mediator.Core/PipelineBehaviours/ValidationPipelineBehaviour.cs
jokk-itu/BookVacation
563e269e9e5dff8920275cab8a6082bd8f8c3859
[ "Apache-2.0" ]
null
null
null
using FluentValidation; using MediatR; namespace Mediator.PipelineBehaviours; public class ValidationPipelineBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : IRequest<TResponse> { private readonly IEnumerable<IValidator<TRequest>> _validators; public ValidationPipelineBehaviour(IEnumerable<IValidator<TRequest>> validators) { _validators = validators; } public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next) { if (!_validators.Any()) return await next(); var context = new ValidationContext<TRequest>(request); var validationResults = await Task.WhenAll(_validators.Select(v => v.ValidateAsync(context, cancellationToken))); var failures = validationResults.SelectMany(x => x.Errors).Where(y => y is not null).ToList(); if (failures.Any()) throw new ValidationException(failures); return await next(); } }
34.225806
102
0.704995
5ee3e6be6cb03cb3ba4b43a886a3517c5e3ad560
628
swift
Swift
LikePicsKit/Sources/LikePicsCore/Sources/Services/ImageLoadSource/Value/WebImageUrlSet/Provider/WebImageProvider.swift
tasuwo/LikePics
fec88fae0d3a0dd879cb29580699805521b68bee
[ "MIT" ]
3
2021-02-05T12:32:20.000Z
2021-05-26T10:12:59.000Z
LikePicsKit/Sources/LikePicsCore/Sources/Services/ImageLoadSource/Value/WebImageUrlSet/Provider/WebImageProvider.swift
tasuwo/LikePics
fec88fae0d3a0dd879cb29580699805521b68bee
[ "MIT" ]
30
2021-02-09T13:12:31.000Z
2022-03-23T10:49:19.000Z
LikePicsKit/Sources/LikePicsCore/Sources/Services/ImageLoadSource/Value/WebImageUrlSet/Provider/WebImageProvider.swift
tasuwo/LikePics
fec88fae0d3a0dd879cb29580699805521b68bee
[ "MIT" ]
2
2021-04-02T01:44:04.000Z
2021-04-11T01:04:40.000Z
// // Copyright © 2020 Tasuku Tozawa. All rights reserved. // import Combine import Erik import Foundation /// @mockable public protocol WebImageProvider { static func isProviding(url: URL) -> Bool static func modifyUrlForProcessing(_ url: URL) -> URL static func shouldPreprocess(for url: URL) -> Bool static func preprocess(_ browser: Erik, document: Document) -> AnyPublisher<Void, WebImageUrlSetFinderError> static func resolveHighQualityImageUrl(of url: URL) -> URL? static func shouldModifyRequest(for url: URL) -> Bool static func modifyRequest(_ request: URLRequest) -> URLRequest }
25.12
112
0.732484
bdb3802ef273ebf5b742d11cb86b21732fed247c
1,229
ps1
PowerShell
XpandPwsh/Public/DotNet/Update-Version.ps1
eXpandFramework/XpandPwsh
6f02c91466143be6b75982074390edf9eabbfe40
[ "Apache-2.0" ]
11
2019-10-25T09:08:29.000Z
2022-03-27T13:25:23.000Z
XpandPwsh/Public/DotNet/Update-Version.ps1
eXpandFramework/XpandPwsh
6f02c91466143be6b75982074390edf9eabbfe40
[ "Apache-2.0" ]
5
2019-06-09T16:04:21.000Z
2020-02-24T17:53:53.000Z
XpandPwsh/Public/DotNet/Update-Version.ps1
eXpandFramework/XpandPosh
af1c98afb11b941c242a36d881fc0e41d11dbf1d
[ "Apache-2.0" ]
7
2020-01-03T21:43:11.000Z
2021-02-27T11:18:50.000Z
function Update-Version { [CmdletBinding()] [CmdLetTag(("#dotnet","#dotnetcore"))] param ( [parameter(Mandatory)] [string]$Version, [switch]$Major, [switch]$Minor, [switch]$Build, [switch]$KeepBuild, [switch]$Revision ) begin { $PSCmdlet|Write-PSCmdLetBegin } process { $newVersion=[version]$Version $versionMajor=$newVersion.Major $versionMinor=$newVersion.Minor $versionBuild=$newVersion.Build $versionRevision=$newVersion.Revision if ($Major){ $versionMajor++ $versionMinor=0 if (!$KeepBuild){ $versionBuild=0 } $versionRevision=0 } elseif ($Minor){ $versionMinor++ if (!$KeepBuild){ $versionBuild=0 } $versionRevision=0 } elseif ($Build){ $versionBuild++ $versionRevision=0 } elseif ($Revision){ $versionRevision++ } [version]"$($versionMajor).$versionMinor.$versionBuild.$versionRevision" } end { } }
23.634615
80
0.485761
556b0aee0e5025b55dd840cb25eb79093ca78b3e
242
sql
SQL
init.sql
samllzhuzhu/cao
8c2311926409f0d7cfab1a564500b7d42a013d7c
[ "Apache-2.0" ]
null
null
null
init.sql
samllzhuzhu/cao
8c2311926409f0d7cfab1a564500b7d42a013d7c
[ "Apache-2.0" ]
null
null
null
init.sql
samllzhuzhu/cao
8c2311926409f0d7cfab1a564500b7d42a013d7c
[ "Apache-2.0" ]
null
null
null
create table "user" ( id serial not null constraint user_pk primary key, name varchar(20), age integer ); alter table "user" owner to postgres; insert into "user" values (1, 'sam', 19), (2, '阿坤', 20);
17.285714
56
0.578512
fb75a7d031dd421600b924cd82f3d12712248065
7,316
c
C
Drivers/KETCube/core/ketCube_uart.c
MartinUbl/KETCube-fw
fbd0f6af803c889363b5553a5dc3e159af6372ad
[ "BSD-3-Clause" ]
null
null
null
Drivers/KETCube/core/ketCube_uart.c
MartinUbl/KETCube-fw
fbd0f6af803c889363b5553a5dc3e159af6372ad
[ "BSD-3-Clause" ]
null
null
null
Drivers/KETCube/core/ketCube_uart.c
MartinUbl/KETCube-fw
fbd0f6af803c889363b5553a5dc3e159af6372ad
[ "BSD-3-Clause" ]
null
null
null
/** * @file ketCube_uart.c * @author Martin Ubl * @version 0.1 * @date 2018-03-07 * @brief This file contains definitions for the UART manager * * @attention * * <h2><center>&copy; Copyright (c) 2018 University of West Bohemia in Pilsen * All rights reserved.</center></h2> * * Developed by: * The SmartCampus Team * Department of Technologies and Measurement * www.smartcampus.cz | www.zcu.cz * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), * to deal with the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimers. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimers in the documentation * and/or other materials provided with the distribution. * * - Neither the names of The SmartCampus Team, Department of Technologies and Measurement * and Faculty of Electrical Engineering University of West Bohemia in Pilsen, * nor the names of its contributors may be used to endorse or promote products * derived from this Software without specific prior written permission. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE CONTRIBUTORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE * OR THE USE OR OTHER DEALINGS WITH THE SOFTWARE. */ /* Define to prevent recursive inclusion -------------------------------------*/ #include "stm32l0xx_hal.h" #include "stm32l0xx_hal_uart.h" #include "ketCube_uart.h" #include "ketCube_gpio.h" /** * @brief Array of registered descriptors */ static ketCube_UART_descriptor_t * ketCube_UART_descriptors[KETCUBE_UART_CHANNEL_COUNT] = { NULL, NULL, NULL, NULL, NULL }; /** * @brief Register UART channel for exclusive access * @param channel UART channel to be registered * @param descriptor descriptor with filled information * @retval KETCUBE_CFG_DRV_OK in case of success * @retval KETCUBE_CFG_DRV_ERROR in case of failure */ ketCube_cfg_DrvError_t ketCube_UART_RegisterHandle(ketCube_UART_ChannelNo_t channel, ketCube_UART_descriptor_t * descriptor) { if (ketCube_UART_descriptors[channel] != NULL) { return KETCUBE_CFG_DRV_ERROR; } // the descriptor needs to be set in order to call appropriate callbacks ketCube_UART_descriptors[channel] = descriptor; if (HAL_UART_Init(descriptor->handle) != HAL_OK) { // clear descriptor in case of failure ketCube_UART_descriptors[channel] = NULL; return KETCUBE_CFG_DRV_ERROR; } // enable IRQ and set priority HAL_NVIC_SetPriority(descriptor->irqNumber, descriptor->irqPriority, descriptor->irqSubPriority); HAL_NVIC_EnableIRQ(descriptor->irqNumber); return KETCUBE_CFG_DRV_OK; } /** * @brief Unregister UART channel * @param channel UART channel to be unregistered * @retval KETCUBE_CFGDRV_OK in case of success * @retval KETCUBE_CFG_DRV_ERROR in case of failure */ ketCube_cfg_DrvError_t ketCube_UART_UnRegisterHandle(ketCube_UART_ChannelNo_t channel) { if (ketCube_UART_descriptors[channel] == NULL) return KETCUBE_CFG_DRV_ERROR; // deinitialize IO pins ketCube_UART_IoDeInitCallback(channel); ketCube_UART_descriptors[channel] = NULL; return KETCUBE_CFG_DRV_OK; } /** * @brief Retrieve UART handle for given channel * @param channel UART channel * @retval valid handle or NULL if the channel hasn't been registered */ UART_HandleTypeDef *ketCube_UART_GetHandle(ketCube_UART_ChannelNo_t channel) { return ketCube_UART_descriptors[channel] == NULL ? NULL : ketCube_UART_descriptors[channel]->handle; } // these are just plain callbacks; their body repeats, so we could easily define macro for that #define DEFINE_CALLBACK_FNC(cbname, cbfnc) void ketCube_UART_##cbname(ketCube_UART_ChannelNo_t channel)\ {\ if (ketCube_UART_descriptors[channel] == NULL || ketCube_UART_descriptors[channel]->cbfnc == NULL){\ return;\ }\ (ketCube_UART_descriptors[channel]->cbfnc )();\ } /** * @brief IRQ callback for given channel */ DEFINE_CALLBACK_FNC(IRQCallback, fnIRQCallback); /** * @brief IRQ callback for given channel */ DEFINE_CALLBACK_FNC(ReceiveCallback, fnReceiveCallback); /** * @brief TX complete callback for given channel * @param channel UART channel */ DEFINE_CALLBACK_FNC(TransmitCallback, fnTransmitCallback); /** * @brief Error callback for given channel */ DEFINE_CALLBACK_FNC(ErrorCallback, fnErrorCallback); /** * @brief Wakeup callback for given channel */ DEFINE_CALLBACK_FNC(WakeupCallback, fnWakeupCallback); /** * @brief IO ports init callback for given channel */ DEFINE_CALLBACK_FNC(IoInitCallback, fnIoInit); /** * @brief IO ports deinit callback for given channel */ DEFINE_CALLBACK_FNC(IoDeInitCallback, fnIoDeInit); /** * @brief Initialize all registered descriptors (e.g. when going back from sleep) */ void ketCube_UART_IoInitAll(void) { int i; for (i = 0; i < KETCUBE_UART_CHANNEL_COUNT; i++) { if (ketCube_UART_descriptors[i] != NULL && ketCube_UART_descriptors[i]->fnIoInit != NULL) (ketCube_UART_descriptors[i]->fnIoInit) (); } } /** * @brief Denitialize all registered descriptors (e.g. when going to sleep) */ void ketCube_UART_IoDeInitAll(void) { int i; for (i = 0; i < KETCUBE_UART_CHANNEL_COUNT; i++) { if (ketCube_UART_descriptors[i] != NULL && ketCube_UART_descriptors[i]->fnIoDeInit != NULL) (ketCube_UART_descriptors[i]->fnIoDeInit) (); } } /** * @brief Setup UART PIN(s) * * @param pin KETCube PIN * @param port KETCube PORT * @param af alternate function for selected UART peripheral and PIN * * @retval KETCUBE_CFG_DRV_OK in case of success * @retval KETCUBE_CFG_DRV_ERROR in case of failure */ ketCube_cfg_DrvError_t ketCube_UART_SetupPin(ketCube_gpio_port_t port, ketCube_gpio_pin_t pin, uint8_t af) { static GPIO_InitTypeDef GPIO_InitStruct = { 0 }; GPIO_InitStruct.Pin = pin; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; GPIO_InitStruct.Pull = GPIO_PULLUP; GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; GPIO_InitStruct.Alternate = af; return ketCube_GPIO_Init(port, pin, &GPIO_InitStruct); }
32.660714
104
0.700109
2c424090fe65653436dee64b28bbdec9b3000527
4,437
swift
Swift
CallMeMaybe/SpeechVC.swift
EbubekirOgden/Phone-Interview-Helper-Simulator
882586a012059cb6652c7d4aa2982add61b2d978
[ "MIT" ]
null
null
null
CallMeMaybe/SpeechVC.swift
EbubekirOgden/Phone-Interview-Helper-Simulator
882586a012059cb6652c7d4aa2982add61b2d978
[ "MIT" ]
null
null
null
CallMeMaybe/SpeechVC.swift
EbubekirOgden/Phone-Interview-Helper-Simulator
882586a012059cb6652c7d4aa2982add61b2d978
[ "MIT" ]
null
null
null
// // SpeechVC.swift // CallMeMaybe // // Created by Ebubekir Ogden on 1/16/17. // Copyright © 2017 Ebubekir. All rights reserved. // import UIKit import SpeechToTextV1 import ToneAnalyzerV3 class SpeechVC: UIViewController, UITextViewDelegate { @IBOutlet weak var speechTextArea: UITextView! @IBOutlet weak var speechButton: UIButton! @IBOutlet weak var stopButton: UIButton! @IBOutlet weak var analyzeButton: UIButton! var emotionalTones = [EmotionalToneReport!]() var socialTones = [SocialToneReport!]() var fiveTones = [FiveEmotionsReport!]() let speechToText = SpeechToText(username: speechToTextUsername, password: speechToTextPassword) let toneAnalyzer = ToneAnalyzer(username: toneAnalyzerUsername, password: toneAnalyzerPassword, version: toneAnalyzerDate) override func viewDidLoad() { super.viewDidLoad() speechTextArea.delegate = self speechTextArea.returnKeyType = .done self.hideKeyboardWhenTappedAround() } @IBAction func speechButton(_ sender: UIButton) { speechButton.isEnabled = false analyzeButton.isEnabled = false stopButton.isEnabled = true startStreaming() } @IBAction func stopButton(_ sender: UIButton) { speechButton.isEnabled = true analyzeButton.isEnabled = true stopButton.isEnabled = false stopStreaming() } @IBAction func analyzeButton(_ sender: UIButton) { toneAnalyzer.getTone(ofText: speechTextArea.text!, failure : failure){ tones in let emotions = tones.documentTone[0].tones for i in 0..<emotions.count{ let emo = EmotionalToneReport(emotionId: emotions[i].id, emotionName: emotions[i].name, emotionScore: Float(emotions[i].score)) self.emotionalTones.append(emo) } let socials = tones.documentTone[1].tones for i in 0..<socials.count{ let soc = SocialToneReport(socialId: socials[i].id, socialName: socials[i].name, socialScore: Float(socials[i].score)) self.socialTones.append(soc) } let five = tones.documentTone[2].tones for i in 0..<five.count{ let fiv = FiveEmotionsReport(fiveId: five[i].id, fiveName: five[i].name, fiveScore: Float(five[i].score)) self.fiveTones.append(fiv) } let reports = [self.emotionalTones, self.socialTones, self.fiveTones] as [Any] self.performSegue(withIdentifier: "toReport", sender: reports) } } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let destination = segue.destination as? ReportVC { if let report = sender as? Array<Any>{ destination.getEmotionReportInformation = report[0] as! [EmotionalToneReport] destination.getSocialReportInformation = report[1] as! [SocialToneReport] destination.getFiveReportInformation = report[2] as! [FiveEmotionsReport] } } } func startStreaming() { var settings = RecognitionSettings(contentType: .opus) settings.continuous = true settings.interimResults = true let failure = { (error: Error) in print(error) } speechToText.recognizeMicrophone(settings: settings, failure: failure) { results in self.speechTextArea.text = results.bestTranscript /* TO-DO : AUTO SCROLL DOWN! */ // print("X is : \(self.speechTextArea.frame.origin.x)\n Y is : \(self.speechTextArea.frame.origin.y)") // // let startPosition = self.speechTextArea.beginningOfDocument // let endPosition = self.speechTextArea.endOfDocument // // let cursorPosition = self.speechTextArea.offset(from: startPosition, to: endPosition) // // if cursorPosition > 70 { // self.speechTextArea.contentOffset.y = CGFloat(cursorPosition) // } // /* */ } } func stopStreaming() { speechToText.stopRecognizeMicrophone() } }
34.395349
143
0.599279
6111fce30f15f92795d52ffe2d06da3877bb5faf
129
sql
SQL
BuilInFunctions/SQLQuery15.sql
VenelinKadankov/CS-DB-MSSQL
8ca7cc3ab0cd9676400ce34a7b6b9352750a81ae
[ "MIT" ]
null
null
null
BuilInFunctions/SQLQuery15.sql
VenelinKadankov/CS-DB-MSSQL
8ca7cc3ab0cd9676400ce34a7b6b9352750a81ae
[ "MIT" ]
1
2021-09-16T20:44:17.000Z
2021-09-16T20:45:13.000Z
BuilInFunctions/SQLQuery15.sql
VenelinKadankov/CS-DB-MSSQL
8ca7cc3ab0cd9676400ce34a7b6b9352750a81ae
[ "MIT" ]
null
null
null
SELECT Username, RIGHT(Email, LEN(Email) - CHARINDEX('@',Email)) AS EmailProvider FROM [Users] ORDER BY EmailProvider, UserName
43
81
0.75969
7f5d41ed81a57ee00cdf792ecdc769edc027cb58
638
go
Go
pkg/logging/context.go
JokeTrue/image-previewer
5af858678de0492d3a514ef14d9e0dec4326030e
[ "Apache-2.0" ]
null
null
null
pkg/logging/context.go
JokeTrue/image-previewer
5af858678de0492d3a514ef14d9e0dec4326030e
[ "Apache-2.0" ]
1
2020-07-13T18:55:25.000Z
2020-07-31T06:25:33.000Z
pkg/logging/context.go
JokeTrue/image-previewer
5af858678de0492d3a514ef14d9e0dec4326030e
[ "Apache-2.0" ]
null
null
null
package logging import ( "context" ) type fieldsKey struct{} // ContextWithFields adds logger fields to fields in context. func ContextWithFields(parent context.Context, fields Fields) context.Context { var newFields Fields val := parent.Value(fieldsKey{}) if val == nil { newFields = fields } else { oldFields, ok := val.(Fields) if !ok { panic("fields expected to be type of 'Fields'") } newFields = make(Fields, len(oldFields)+len(fields)) for k, v := range oldFields { newFields[k] = v } for k, v := range fields { newFields[k] = v } } return context.WithValue(parent, fieldsKey{}, newFields) }
19.9375
79
0.678683
67558479bc0b844a31f36faf370195697463cdf8
4,296
kt
Kotlin
src/test/kotlin/org/lexem/angmar/analyzer/nodes/functional/expressions/binary/ShiftExpressionAnalyzerTest.kt
lexem-lang/angmar
45fb563507a00c3eada89be9ab6e17cfe1701958
[ "MIT" ]
1
2019-06-25T08:14:27.000Z
2019-06-25T08:14:27.000Z
src/test/kotlin/org/lexem/angmar/analyzer/nodes/functional/expressions/binary/ShiftExpressionAnalyzerTest.kt
lexem-lang/angmar
45fb563507a00c3eada89be9ab6e17cfe1701958
[ "MIT" ]
null
null
null
src/test/kotlin/org/lexem/angmar/analyzer/nodes/functional/expressions/binary/ShiftExpressionAnalyzerTest.kt
lexem-lang/angmar
45fb563507a00c3eada89be9ab6e17cfe1701958
[ "MIT" ]
1
2019-09-16T21:42:41.000Z
2019-09-16T21:42:41.000Z
package org.lexem.angmar.analyzer.nodes.functional.expressions.binary import org.junit.jupiter.api.* import org.lexem.angmar.analyzer.data.primitives.* import org.lexem.angmar.parser.functional.expressions.binary.* import org.lexem.angmar.parser.literals.* import org.lexem.angmar.utils.* import java.util.* internal class ShiftExpressionAnalyzerTest { @Test fun `test left shift`() { val text = "${BitlistNode.binaryPrefix}${BitlistNode.startToken}0110${BitlistNode.endToken} ${ShiftExpressionNode.leftShiftOperator} 3" val analyzer = TestUtils.createAnalyzerFrom(text, parserFunction = ShiftExpressionNode.Companion::parse) TestUtils.processAndCheckEmpty(analyzer) val stackValue = analyzer.memory.getLastFromStack() as? LxmBitList ?: throw Error( "The value of the stack must be a LxmBitList") val resultValue = BitSet() Assertions.assertEquals(1, stackValue.size, "The size property of the value inserted in the stack is incorrect") Assertions.assertEquals(resultValue, stackValue.primitive, "The value inserted in the stack is incorrect") // Remove Last from the stack. analyzer.memory.removeLastFromStack() TestUtils.checkEmptyStackAndContext(analyzer) } @Test fun `test right shift`() { val text = "${BitlistNode.binaryPrefix}${BitlistNode.startToken}0110${BitlistNode.endToken} ${ShiftExpressionNode.rightShiftOperator} 3" val analyzer = TestUtils.createAnalyzerFrom(text, parserFunction = ShiftExpressionNode.Companion::parse) TestUtils.processAndCheckEmpty(analyzer) val stackValue = analyzer.memory.getLastFromStack() as? LxmBitList ?: throw Error( "The value of the stack must be a LxmBitList") val resultValue = BitSet() resultValue[4] = true resultValue[5] = true Assertions.assertEquals(7, stackValue.size, "The size property of the value inserted in the stack is incorrect") Assertions.assertEquals(resultValue, stackValue.primitive, "The value inserted in the stack is incorrect") // Remove Last from the stack. analyzer.memory.removeLastFromStack() TestUtils.checkEmptyStackAndContext(analyzer) } @Test fun `test left rotation`() { val text = "${BitlistNode.binaryPrefix}${BitlistNode.startToken}0110${BitlistNode.endToken} ${ShiftExpressionNode.leftRotationOperator} 3" val analyzer = TestUtils.createAnalyzerFrom(text, parserFunction = ShiftExpressionNode.Companion::parse) TestUtils.processAndCheckEmpty(analyzer) val stackValue = analyzer.memory.getLastFromStack() as? LxmBitList ?: throw Error( "The value of the stack must be a LxmBitList") val resultValue = BitSet() resultValue[2] = true resultValue[3] = true Assertions.assertEquals(4, stackValue.size, "The size property of the value inserted in the stack is incorrect") Assertions.assertEquals(resultValue, stackValue.primitive, "The value inserted in the stack is incorrect") // Remove Last from the stack. analyzer.memory.removeLastFromStack() TestUtils.checkEmptyStackAndContext(analyzer) } @Test fun `test right rotation`() { val text = "${BitlistNode.binaryPrefix}${BitlistNode.startToken}0110${BitlistNode.endToken} ${ShiftExpressionNode.rightRotationOperator} 3" val analyzer = TestUtils.createAnalyzerFrom(text, parserFunction = ShiftExpressionNode.Companion::parse) TestUtils.processAndCheckEmpty(analyzer) val stackValue = analyzer.memory.getLastFromStack() as? LxmBitList ?: throw Error( "The value of the stack must be a LxmBitList") val resultValue = BitSet() resultValue[0] = true resultValue[1] = true Assertions.assertEquals(4, stackValue.size, "The size property of the value inserted in the stack is incorrect") Assertions.assertEquals(resultValue, stackValue.primitive, "The value inserted in the stack is incorrect") // Remove Last from the stack. analyzer.memory.removeLastFromStack() TestUtils.checkEmptyStackAndContext(analyzer) } }
46.193548
144
0.703212
079e8606c951f41c9fe7c42a09d503b4060a7d55
555
dart
Dart
lib/src/target/target_position.dart
Simpwell/tutorial_coach_mark
e0ee22c97ddec9f1638fd2a4e2e145a978e79fb5
[ "MIT" ]
382
2019-04-30T11:25:54.000Z
2022-03-31T18:25:00.000Z
lib/src/target/target_position.dart
Simpwell/tutorial_coach_mark
e0ee22c97ddec9f1638fd2a4e2e145a978e79fb5
[ "MIT" ]
103
2019-05-01T12:49:34.000Z
2022-03-31T07:46:57.000Z
lib/src/target/target_position.dart
Simpwell/tutorial_coach_mark
e0ee22c97ddec9f1638fd2a4e2e145a978e79fb5
[ "MIT" ]
125
2019-05-21T16:27:05.000Z
2022-03-30T16:12:10.000Z
import 'dart:math'; import 'dart:ui'; class TargetPosition { final Size size; final Offset offset; TargetPosition(this.size, this.offset); Offset get center => Offset( offset.dx + size.width / 2, offset.dy + size.height / 2, ); double getBiggerSpaceBorder(Size size) { double maxDistanceX = center.dx > size.width / 2 ? center.dx : size.width - center.dx; double maxDistanceY = center.dy > size.height / 2 ? center.dy : size.height - center.dy; return max(maxDistanceX, maxDistanceY); } }
24.130435
74
0.641441
cfab2cbc9a97a95af004b1a6043c247db91c7f1a
331
asm
Assembly
programs/oeis/102/A102592.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
22
2018-02-06T19:19:31.000Z
2022-01-17T21:53:31.000Z
programs/oeis/102/A102592.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
41
2021-02-22T19:00:34.000Z
2021-08-28T10:47:47.000Z
programs/oeis/102/A102592.asm
neoneye/loda
afe9559fb53ee12e3040da54bd6aa47283e0d9ec
[ "Apache-2.0" ]
5
2021-02-24T21:14:16.000Z
2021-08-09T19:48:05.000Z
; A102592: a(n) = Sum_{k=0..n} binomial(2n+1, 2k)*5^(n-k). ; 1,8,80,832,8704,91136,954368,9994240,104660992,1096024064,11477712896,120196169728,1258710630400,13181388849152,138037296103424,1445545331654656,15137947242201088,158526641599938560 mul $0,2 add $0,3 seq $0,87205 ; a(n) = -2*a(n-1) + 4*a(n-2), a(0)=1, a(1)=2. div $0,8
41.375
183
0.712991
260538f3fd163b641383da1c8bcb1f12d7f1b31a
2,513
java
Java
iam-service/src/main/java/one/microproject/iamservice/server/config/CacheSchedulerConfig.java
jveverka/iam-service
d1eeece149350c1c0940d0da5bd5a2d4cc0407f7
[ "MIT" ]
12
2020-07-30T11:01:11.000Z
2022-03-06T17:09:08.000Z
iam-service/src/main/java/one/microproject/iamservice/server/config/CacheSchedulerConfig.java
jveverka/iam-service
d1eeece149350c1c0940d0da5bd5a2d4cc0407f7
[ "MIT" ]
59
2020-03-11T12:58:12.000Z
2021-04-27T06:09:36.000Z
iam-service/src/main/java/one/microproject/iamservice/server/config/CacheSchedulerConfig.java
jveverka/iam-service
d1eeece149350c1c0940d0da5bd5a2d4cc0407f7
[ "MIT" ]
4
2021-05-25T17:23:25.000Z
2022-03-15T00:11:13.000Z
package one.microproject.iamservice.server.config; import one.microproject.iamservice.core.services.caches.AuthorizationCodeCache; import one.microproject.iamservice.core.services.caches.CacheCleanupScheduler; import one.microproject.iamservice.core.services.impl.caches.CacheCleanupSchedulerImpl; import one.microproject.iamservice.core.services.caches.TokenCache; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.util.concurrent.TimeUnit; @Component @ConfigurationProperties(prefix="iam-service.cache-cleanup-interval") public class CacheSchedulerConfig { private static final Logger LOG = LoggerFactory.getLogger(CacheSchedulerConfig.class); private final AuthorizationCodeCache authorizationCodeCache; private final TokenCache tokenCache; private long duration = 5; private String timeunit = "MINUTES"; private CacheCleanupScheduler cacheCleanupScheduler; public CacheSchedulerConfig(@Autowired AuthorizationCodeCache authorizationCodeCache, @Autowired TokenCache tokenCache) { this.authorizationCodeCache = authorizationCodeCache; this.tokenCache = tokenCache; } @PostConstruct public void init() { LOG.info("#CONFIG iam-service.cache-cleanup-interval.duration: {}", duration); LOG.info("#CONFIG iam-service.cache-cleanup-interval.timeunit: {}", timeunit); this.cacheCleanupScheduler = new CacheCleanupSchedulerImpl(getDuration(), getTimeUnitValue(), authorizationCodeCache, tokenCache); this.cacheCleanupScheduler.start(); } @PreDestroy public void shutdown() { LOG.info("#SCHEDULER: shutdown"); try { this.cacheCleanupScheduler.close(); } catch (Exception e) { LOG.error("Error shutting down CacheCleanupScheduler", e); } } public long getDuration() { return duration; } public void setDuration(long duration) { this.duration = duration; } public String getTimeunit() { return timeunit; } public void setTimeunit(String timeunit) { this.timeunit = timeunit; } public TimeUnit getTimeUnitValue() { return TimeUnit.valueOf(timeunit); } }
33.506667
138
0.733386
11185712d7ea467fc06a0b5bcf6546584d3079a8
408
dart
Dart
lib/models/user.dart
Stefan-Radu/pebbles
db5d6d8b2174ee77cc988b09dcffdd4e7346a84b
[ "MIT" ]
null
null
null
lib/models/user.dart
Stefan-Radu/pebbles
db5d6d8b2174ee77cc988b09dcffdd4e7346a84b
[ "MIT" ]
null
null
null
lib/models/user.dart
Stefan-Radu/pebbles
db5d6d8b2174ee77cc988b09dcffdd4e7346a84b
[ "MIT" ]
null
null
null
import 'package:pebbles/services/database.dart'; class User { User({this.uid}) { DatabaseService().getUserInstance(uid:this.uid).then((document) { this.userName = document['userName']; this.email = document['email']; this.markedPebbles = Map.from(document['markedPebbles']); }); } final String uid; String userName; String email; Map < String, int > markedPebbles; }
22.666667
69
0.664216
c91ccf3866c25d6023a10fab5a7bf5648bc0d30e
688
asm
Assembly
programs/oeis/023/A023660.asm
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
1
2021-03-15T11:38:20.000Z
2021-03-15T11:38:20.000Z
programs/oeis/023/A023660.asm
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
null
null
null
programs/oeis/023/A023660.asm
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
null
null
null
; A023660: Convolution of odd numbers and A023533. ; 1,3,5,8,12,16,20,24,28,33,39,45,51,57,63,69,75,81,87,94,102,110,118,126,134,142,150,158,166,174,182,190,198,206,215,225,235,245,255,265,275,285,295,305,315,325,335,345,355,365,375,385,395,405 mov $10,$0 mov $12,$0 add $12,1 lpb $12 clr $0,10 mov $0,$10 sub $12,1 sub $0,$12 mov $7,$0 mov $9,$0 add $9,1 lpb $9 clr $0,7 mov $0,$7 sub $9,1 sub $0,$9 add $4,$0 mov $1,$4 add $1,1 mov $0,$1 cal $0,124171 ; Sequence obtained by reading the triangles shown below by rows. mov $1,$0 trn $1,2 add $1,1 mov $2,2 trn $2,$1 add $8,$2 lpe add $11,$8 lpe mov $1,$11
19.657143
193
0.574128
75fcf7a97dce53415d90113bd58ec5c6867e4066
413
java
Java
src/main/java/com/info/service/ShoppingCartService.java
Ernar2002/Online-shop-IPoint
44901d77e263f567c27997119bc00bd7f426e0c6
[ "MIT" ]
null
null
null
src/main/java/com/info/service/ShoppingCartService.java
Ernar2002/Online-shop-IPoint
44901d77e263f567c27997119bc00bd7f426e0c6
[ "MIT" ]
null
null
null
src/main/java/com/info/service/ShoppingCartService.java
Ernar2002/Online-shop-IPoint
44901d77e263f567c27997119bc00bd7f426e0c6
[ "MIT" ]
null
null
null
package com.info.service; import com.info.model.Product; import org.springframework.stereotype.Service; import java.math.BigDecimal; import java.util.Map; @Service public interface ShoppingCartService { void addProduct(Product product); void removeProduct(Product product); void clearProducts(); Map<Product, Integer> productsInCart(); // BigDecimal totalPrice(); void cartCheckout(); }
22.944444
46
0.755448
843af576915360e0cbfc364a13bfaf52cc1fb807
1,106
lua
Lua
Data/StoryBit/MissingRover_2_Shuttles.lua
dawnmist/SurvivingMars
02a3dca12d10998c5fd0a077ca8939ef6b3d4dd3
[ "BSD-Source-Code" ]
94
2018-04-04T20:43:27.000Z
2022-01-30T22:26:26.000Z
Data/StoryBit/MissingRover_2_Shuttles.lua
dawnmist/SurvivingMars
02a3dca12d10998c5fd0a077ca8939ef6b3d4dd3
[ "BSD-Source-Code" ]
4
2018-04-06T07:52:08.000Z
2018-04-27T04:27:19.000Z
Data/StoryBit/MissingRover_2_Shuttles.lua
dawnmist/SurvivingMars
02a3dca12d10998c5fd0a077ca8939ef6b3d4dd3
[ "BSD-Source-Code" ]
26
2018-04-05T01:56:10.000Z
2022-02-20T19:27:44.000Z
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ========== PlaceObj('StoryBit', { ActivationEffects = { PlaceObj('UnitAppear', { 'Location', "MapBorder", }), PlaceObj('Malfunction', nil), PlaceObj('EraseShuttles', { 'Count', "<shuttles_killed>", }), }, Effects = {}, Enables = { "MissingRover_5_Repaired", }, Prerequisites = {}, ScriptDone = true, SuppressTime = 180000, Text = T(282893267545, --[[StoryBit MissingRover_2_Shuttles Text]] "From what we can tell from the cameras, the Rover has suffered a critical malfunction. We have no idea how it ended up on its current location.\n\n<effect>You will need to send Drones to repair the malfunctioned Rover."), TextReadyForValidation = true, TextsDone = true, VoicedText = T(541991435112, --[[voice:narrator]] "The spotlight locks on to the missing Rover as a shuttle orbits the location. The search mission was successful but several Shuttles were lost in the Dust Storm."), group = "Disasters", id = "MissingRover_2_Shuttles", PlaceObj('StoryBitParamNumber', { 'Name', "shuttles_killed", 'Value', 2, }), })
34.5625
290
0.697107
2010229eb6915e84dc6a2fa635d2e1222d899b55
84
sql
SQL
src/main/resources/org/support/project/web/dao/sql/UserNotificationsDao/UserNotificationsDao_select_all.sql
kuro-channel/knowledge-1
6f74162ad54af961fb5069a27f49959b9e9a8048
[ "Apache-2.0" ]
742
2015-02-03T02:02:15.000Z
2022-03-15T16:54:25.000Z
src/main/resources/org/support/project/web/dao/sql/UserNotificationsDao/UserNotificationsDao_select_all.sql
kuro-channel/knowledge-1
6f74162ad54af961fb5069a27f49959b9e9a8048
[ "Apache-2.0" ]
760
2015-02-01T11:40:05.000Z
2022-01-21T23:22:06.000Z
src/main/resources/org/support/project/web/dao/sql/UserNotificationsDao/UserNotificationsDao_select_all.sql
kuro-channel/knowledge-1
6f74162ad54af961fb5069a27f49959b9e9a8048
[ "Apache-2.0" ]
285
2015-02-23T08:02:29.000Z
2022-03-25T02:48:31.000Z
SELECT * FROM USER_NOTIFICATIONS WHERE DELETE_FLAG = 0 ORDER BY INSERT_DATETIME %s;
21
32
0.809524
64cc61c01dc18324491ceaac9d681fce6651825b
1,625
kt
Kotlin
komapper-core/src/main/kotlin/org/komapper/core/dsl/query/EntityStoreQuery.kt
komapper/komapper
3c91b73c7e0c9d9002405577e939eee868f9054f
[ "Apache-2.0" ]
60
2021-05-12T10:20:28.000Z
2022-03-30T22:26:19.000Z
komapper-core/src/main/kotlin/org/komapper/core/dsl/query/EntityStoreQuery.kt
komapper/komapper
3c91b73c7e0c9d9002405577e939eee868f9054f
[ "Apache-2.0" ]
25
2021-03-22T15:06:15.000Z
2022-03-26T15:23:17.000Z
komapper-core/src/main/kotlin/org/komapper/core/dsl/query/EntityStoreQuery.kt
komapper/komapper
3c91b73c7e0c9d9002405577e939eee868f9054f
[ "Apache-2.0" ]
1
2022-03-27T22:02:26.000Z
2022-03-27T22:02:26.000Z
package org.komapper.core.dsl.query import org.komapper.core.dsl.context.SelectContext import org.komapper.core.dsl.metamodel.EntityMetamodel import org.komapper.core.dsl.options.SelectOptions import org.komapper.core.dsl.visitor.QueryVisitor /** * Represents a query to retrieve multiple entity sets. * This query returns the store that holds entity sets. */ interface EntityStoreQuery : Query<EntityStore> { /** * Builds a query with the options applied. * * @param configure the configure function to apply options * @return the query */ fun options(configure: (SelectOptions) -> SelectOptions): EntityStoreQuery } internal data class EntityStoreQueryImpl<ENTITY : Any, ID : Any, META : EntityMetamodel<ENTITY, ID, META>>( private val context: SelectContext<ENTITY, ID, META>, ) : EntityStoreQuery { private val support: SelectQuerySupport<ENTITY, ID, META> = SelectQuerySupport(context) fun include(vararg metamodels: EntityMetamodel<*, *, *>): EntityStoreQuery { val newContext = support.include(metamodels.toList()) return copy(context = newContext) } fun includeAll(): EntityStoreQuery { val newContext = support.includeAll() return copy(context = newContext) } override fun options(configure: (SelectOptions) -> SelectOptions): EntityStoreQuery { val newContext = support.options(configure(context.options)) return copy(context = newContext) } override fun <VISIT_RESULT> accept(visitor: QueryVisitor<VISIT_RESULT>): VISIT_RESULT { return visitor.entityStoreQuery(context) } }
34.574468
107
0.721231
f4a928f05bfcc5e4cab68b00acda7926b533a714
4,166
go
Go
Algorithms/679.24-game/24-game_1-violence.go
OctopusLian/leetcode-solutions
40920d11c584504e805d103cdc6ef3f3774172b3
[ "MIT" ]
1
2020-12-01T18:35:24.000Z
2020-12-01T18:35:24.000Z
Algorithms/679.24-game/24-game_1-violence.go
OctopusLian/leetcode-solutions
40920d11c584504e805d103cdc6ef3f3774172b3
[ "MIT" ]
18
2020-11-10T05:48:29.000Z
2020-11-26T08:39:20.000Z
Algorithms/679.24-game/24-game_1-violence.go
OctopusLian/leetcode-solutions
40920d11c584504e805d103cdc6ef3f3774172b3
[ "MIT" ]
5
2020-11-09T07:43:00.000Z
2021-12-02T14:59:37.000Z
func judgePoint24(nums []int) bool { //解法1,暴力法 return judgePoint24_3(float64(nums[0])+float64(nums[1]), float64(nums[2]), float64(nums[3])) || judgePoint24_3(float64(nums[0])-float64(nums[1]), float64(nums[2]), float64(nums[3])) || judgePoint24_3(float64(nums[0])*float64(nums[1]), float64(nums[2]), float64(nums[3])) || judgePoint24_3(float64(nums[0])/float64(nums[1]), float64(nums[2]), float64(nums[3])) || judgePoint24_3(float64(nums[1])-float64(nums[0]), float64(nums[2]), float64(nums[3])) || judgePoint24_3(float64(nums[1])/float64(nums[0]), float64(nums[2]), float64(nums[3])) || judgePoint24_3(float64(nums[0])+float64(nums[2]), float64(nums[1]), float64(nums[3])) || judgePoint24_3(float64(nums[0])-float64(nums[2]), float64(nums[1]), float64(nums[3])) || judgePoint24_3(float64(nums[0])*float64(nums[2]), float64(nums[1]), float64(nums[3])) || judgePoint24_3(float64(nums[0])/float64(nums[2]), float64(nums[1]), float64(nums[3])) || judgePoint24_3(float64(nums[2])-float64(nums[0]), float64(nums[1]), float64(nums[3])) || judgePoint24_3(float64(nums[2])/float64(nums[0]), float64(nums[1]), float64(nums[3])) || judgePoint24_3(float64(nums[0])+float64(nums[3]), float64(nums[2]), float64(nums[1])) || judgePoint24_3(float64(nums[0])-float64(nums[3]), float64(nums[2]), float64(nums[1])) || judgePoint24_3(float64(nums[0])*float64(nums[3]), float64(nums[2]), float64(nums[1])) || judgePoint24_3(float64(nums[0])/float64(nums[3]), float64(nums[2]), float64(nums[1])) || judgePoint24_3(float64(nums[3])-float64(nums[0]), float64(nums[2]), float64(nums[1])) || judgePoint24_3(float64(nums[3])/float64(nums[0]), float64(nums[2]), float64(nums[1])) || judgePoint24_3(float64(nums[2])+float64(nums[3]), float64(nums[0]), float64(nums[1])) || judgePoint24_3(float64(nums[2])-float64(nums[3]), float64(nums[0]), float64(nums[1])) || judgePoint24_3(float64(nums[2])*float64(nums[3]), float64(nums[0]), float64(nums[1])) || judgePoint24_3(float64(nums[2])/float64(nums[3]), float64(nums[0]), float64(nums[1])) || judgePoint24_3(float64(nums[3])-float64(nums[2]), float64(nums[0]), float64(nums[1])) || judgePoint24_3(float64(nums[3])/float64(nums[2]), float64(nums[0]), float64(nums[1])) || judgePoint24_3(float64(nums[1])+float64(nums[2]), float64(nums[0]), float64(nums[3])) || judgePoint24_3(float64(nums[1])-float64(nums[2]), float64(nums[0]), float64(nums[3])) || judgePoint24_3(float64(nums[1])*float64(nums[2]), float64(nums[0]), float64(nums[3])) || judgePoint24_3(float64(nums[1])/float64(nums[2]), float64(nums[0]), float64(nums[3])) || judgePoint24_3(float64(nums[2])-float64(nums[1]), float64(nums[0]), float64(nums[3])) || judgePoint24_3(float64(nums[2])/float64(nums[1]), float64(nums[0]), float64(nums[3])) || judgePoint24_3(float64(nums[1])+float64(nums[3]), float64(nums[2]), float64(nums[0])) || judgePoint24_3(float64(nums[1])-float64(nums[3]), float64(nums[2]), float64(nums[0])) || judgePoint24_3(float64(nums[1])*float64(nums[3]), float64(nums[2]), float64(nums[0])) || judgePoint24_3(float64(nums[1])/float64(nums[3]), float64(nums[2]), float64(nums[0])) || judgePoint24_3(float64(nums[3])-float64(nums[1]), float64(nums[2]), float64(nums[0])) || judgePoint24_3(float64(nums[3])/float64(nums[1]), float64(nums[2]), float64(nums[0])) } func judgePoint24_3(a, b, c float64) bool { return judgePoint24_2(a+b, c) || judgePoint24_2(a-b, c) || judgePoint24_2(a*b, c) || judgePoint24_2(a/b, c) || judgePoint24_2(b-a, c) || judgePoint24_2(b/a, c) || judgePoint24_2(a+c, b) || judgePoint24_2(a-c, b) || judgePoint24_2(a*c, b) || judgePoint24_2(a/c, b) || judgePoint24_2(c-a, b) || judgePoint24_2(c/a, b) || judgePoint24_2(c+b, a) || judgePoint24_2(c-b, a) || judgePoint24_2(c*b, a) || judgePoint24_2(c/b, a) || judgePoint24_2(b-c, a) || judgePoint24_2(b/c, a) } func judgePoint24_2(a, b float64) bool { return (a+b < 24+1e-6 && a+b > 24-1e-6) || (a*b < 24+1e-6 && a*b > 24-1e-6) || (a-b < 24+1e-6 && a-b > 24-1e-6) || (b-a < 24+1e-6 && b-a > 24-1e-6) || (a/b < 24+1e-6 && a/b > 24-1e-6) || (b/a < 24+1e-6 && b/a > 24-1e-6) }
53.410256
96
0.656745
bcd24a9b2ee4aecd4fe125ada75c65617cfb6bff
75
js
JavaScript
test/fixtures/fake-router.js
macula-projects/vue-macula-auto-routing
b718c056cea176049f7119110f31017644e2c53c
[ "MIT" ]
null
null
null
test/fixtures/fake-router.js
macula-projects/vue-macula-auto-routing
b718c056cea176049f7119110f31017644e2c53c
[ "MIT" ]
null
null
null
test/fixtures/fake-router.js
macula-projects/vue-macula-auto-routing
b718c056cea176049f7119110f31017644e2c53c
[ "MIT" ]
null
null
null
import routes from '../../' // vue-macula-auto-routing console.log(routes)
25
54
0.693333
f013b73782802e7be9ad94ff6ab1e1a0a57d6410
1,224
py
Python
saleor/app/tests/test_models.py
fairhopeweb/saleor
9ac6c22652d46ba65a5b894da5f1ba5bec48c019
[ "CC-BY-4.0" ]
15,337
2015-01-12T02:11:52.000Z
2021-10-05T19:19:29.000Z
saleor/app/tests/test_models.py
fairhopeweb/saleor
9ac6c22652d46ba65a5b894da5f1ba5bec48c019
[ "CC-BY-4.0" ]
7,486
2015-02-11T10:52:13.000Z
2021-10-06T09:37:15.000Z
saleor/app/tests/test_models.py
aminziadna/saleor
2e78fb5bcf8b83a6278af02551a104cfa555a1fb
[ "CC-BY-4.0" ]
5,864
2015-01-16T14:52:54.000Z
2021-10-05T23:01:15.000Z
from ...app.models import App from ...webhook.event_types import WebhookEventType def test_qs_for_event_type(payment_app): qs = App.objects.for_event_type(WebhookEventType.PAYMENT_AUTHORIZE) assert len(qs) == 1 assert qs[0] == payment_app def test_qs_for_event_type_no_payment_permissions(payment_app): payment_app.permissions.first().delete() qs = App.objects.for_event_type(WebhookEventType.PAYMENT_AUTHORIZE) assert len(qs) == 0 def test_qs_for_event_type_inactive_app(payment_app): payment_app.is_active = False payment_app.save() qs = App.objects.for_event_type(WebhookEventType.PAYMENT_AUTHORIZE) assert len(qs) == 0 def test_qs_for_event_type_no_webhook_event(payment_app): webhook = payment_app.webhooks.first() event = webhook.events.filter(event_type=WebhookEventType.PAYMENT_AUTHORIZE).first() event.delete() qs = App.objects.for_event_type(WebhookEventType.PAYMENT_AUTHORIZE) assert len(qs) == 0 def test_qs_for_event_type_inactive_webhook(payment_app): webhook = payment_app.webhooks.first() webhook.is_active = False webhook.save() qs = App.objects.for_event_type(WebhookEventType.PAYMENT_AUTHORIZE) assert len(qs) == 0
32.210526
88
0.768791
751d1028cec7475e82dfa06f5c2d885069f3f63f
2,458
h
C
ARC-Engine/ARC-Engine/src/ARC/Events/MouseEvent.h
Hellboy434/ARC-Engine
a3da38927ad5a7ac56c5bdae71a92b71eecdb16f
[ "Apache-2.0" ]
null
null
null
ARC-Engine/ARC-Engine/src/ARC/Events/MouseEvent.h
Hellboy434/ARC-Engine
a3da38927ad5a7ac56c5bdae71a92b71eecdb16f
[ "Apache-2.0" ]
null
null
null
ARC-Engine/ARC-Engine/src/ARC/Events/MouseEvent.h
Hellboy434/ARC-Engine
a3da38927ad5a7ac56c5bdae71a92b71eecdb16f
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Event.h" #include "..\Types\vector.h" namespace ARC { class ARC_API CMouseMovedEvent : public CEvent { public: CMouseMovedEvent(TVec2<float> p_MouseXY) : m_MouseXY(p_MouseXY) {} CMouseMovedEvent(float p_MouseX, float p_MouseY) : m_MouseXY(TVec2<float>(p_MouseX, p_MouseY)) { } inline TVec2<float> GetXY() const {return m_MouseXY;}; inline float GetX() const {return m_MouseXY[0];}; inline float GetY() const {return m_MouseXY[1];}; virtual std::string ToString() const { std::stringstream ss; ss << GetName() << "[" << GetX() << "," << GetY() << "]"; return ss.str(); } EVENT_CLASS_CATEGORY(Mouse | Input) EVENT_CLASS_TYPE(MouseMoved) private: TVec2<float> m_MouseXY; }; class ARC_API CMouseScrolledEvent : public CEvent { public: CMouseScrolledEvent(TVec2<float> p_Offset) : m_Offset(p_Offset) {} CMouseScrolledEvent(float p_OffsetX, float p_OffsetY) : m_Offset(TVec2<float>(p_OffsetY, p_OffsetY)) {} virtual std::string ToString() const override { std::stringstream ss; ss << GetName() << "[" << GetXOffset() << "," << GetYOffset() << "]"; return ss.str(); } inline TVec2<float> GetOffset() const { return m_Offset; } inline float GetXOffset() const { return m_Offset[0]; } inline float GetYOffset() const { return m_Offset[1]; } EVENT_CLASS_CATEGORY(Mouse | Input) EVENT_CLASS_TYPE(MouseScrolled) private: TVec2<float> m_Offset; }; class ARC_API CMouseButtonEvent : public CEvent { public: inline uint GetMouseButton() const { return m_MouseButton; } EVENT_CLASS_CATEGORY(Mouse | Input) protected: CMouseButtonEvent(uint p_Button) : m_MouseButton(p_Button) {} uint m_MouseButton; }; class ARC_API CMouseButtonPressedEvent : public CMouseButtonEvent { public: CMouseButtonPressedEvent(uint p_Button) : CMouseButtonEvent(p_Button) {} virtual std::string ToString() const override { std::stringstream ss; ss << GetName() << " [" << m_MouseButton << "]"; return ss.str(); } EVENT_CLASS_TYPE(MouseButtonPressed) }; class ARC_API CMouseButtonReleasedEvent : public CMouseButtonEvent { public: CMouseButtonReleasedEvent(uint p_Button) : CMouseButtonEvent(p_Button) {} virtual std::string ToString() const override { std::stringstream ss; ss << GetName() << " [" << m_MouseButton << "]"; return ss.str(); } EVENT_CLASS_TYPE(MouseButtonReleased) }; }
26.148936
76
0.685924
506a2f9c5b231ebb09c5d9d7c614c805491550ea
21,262
html
HTML
_site/blog/the-web-is-a-hypermedia-api.html
katibest/rds
05bf740209e0dda37b9846065dc2e8367950b8b9
[ "CC0-1.0" ]
null
null
null
_site/blog/the-web-is-a-hypermedia-api.html
katibest/rds
05bf740209e0dda37b9846065dc2e8367950b8b9
[ "CC0-1.0" ]
6
2020-07-16T07:33:30.000Z
2022-02-10T15:38:55.000Z
_site/blog/the-web-is-a-hypermedia-api.html
katibest/rhythmdogsports
22c422b51fbe13e4c1a47964da29e921612d034b
[ "CC0-1.0" ]
null
null
null
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Begin Jekyll SEO tag v2.6.1 --> <title>The Web Is A Hypermedia Api | Rhythm Dog Sports</title> <meta name="generator" content="Jekyll v3.8.6" /> <meta property="og:title" content="The Web Is A Hypermedia Api" /> <meta property="og:locale" content="en_US" /> <meta name="description" content="If you’re struggling to wrap your head around Hypermedia APIs, the first thing you need to understand is that you actively use one every day. Unless you were just handed a printout of this article, you are using one right now." /> <meta property="og:description" content="If you’re struggling to wrap your head around Hypermedia APIs, the first thing you need to understand is that you actively use one every day. Unless you were just handed a printout of this article, you are using one right now." /> <link rel="canonical" href="http://localhost:4000/blog/the-web-is-a-hypermedia-api" /> <meta property="og:url" content="http://localhost:4000/blog/the-web-is-a-hypermedia-api" /> <meta property="og:site_name" content="Rhythm Dog Sports" /> <meta property="og:type" content="article" /> <meta property="article:published_time" content="2019-06-27T00:00:00-04:00" /> <script type="application/ld+json"> {"url":"http://localhost:4000/blog/the-web-is-a-hypermedia-api","headline":"The Web Is A Hypermedia Api","dateModified":"2019-06-27T00:00:00-04:00","datePublished":"2019-06-27T00:00:00-04:00","mainEntityOfPage":{"@type":"WebPage","@id":"http://localhost:4000/blog/the-web-is-a-hypermedia-api"},"publisher":{"@type":"Organization","logo":{"@type":"ImageObject","url":"http://localhost:4000/assets/img/logo.png"}},"description":"If you’re struggling to wrap your head around Hypermedia APIs, the first thing you need to understand is that you actively use one every day. Unless you were just handed a printout of this article, you are using one right now.","@type":"BlogPosting","@context":"https://schema.org"}</script> <!-- End Jekyll SEO tag --> <link rel="stylesheet" href="/assets/css/style.css?v="> <link rel="stylesheet" href="https://use.typekit.net/vnr4ouz.css"> <link href="https://fonts.googleapis.com/css?family=Inconsolata&display=swap" rel="stylesheet"> <!--[if lt IE 9]> <script src="https://cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.3/html5shiv.min.js"></script> <![endif]--> <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"> <link rel="manifest" href="/site.webmanifest"> </head> <body> <nav> <a class="nav__logo" href="/"></a> <input type="checkbox" id="nav__toggle"> <label class="nav__toggle" for="nav__toggle"></label> <div class="nav__list"> <div class="nav__link "> <a href="/who-we-are">About Us</a> </div> <div class="nav__link "> <a href="/agility">Agility</a> </div> <div class="nav__link "> <a href="/events">Events</a> </div> <div class="nav__link current "> <a href="/blog">Blog</a> </div> <div class="nav__link "> <a href="/connect">Connect with Us</a> </div> <!-- <div class="nav__link nav__cta"> <a href="/start-a-project" class="btn btn--cta btn--sm">Start a Project</a> </div> --> </div> </nav> <main> <article class="post"> <section class="section--light"> <div class="post__header u-contained"> <div class="post__title"> <div class="post__date u-push-bottom--none">2 July 2012</div> <h2>The Web is a Hypermedia API</h2> <div class="post__author"> <p class="u-push-bottom--none"> by Joel Turnbull </p> </div> </div> </div> </section> <section class="post__body"> <div> <p>If you’re struggling to wrap your head around Hypermedia APIs, the first thing you need to understand is that you actively use one every day. Unless you were just handed a printout of this article, you are using one right now.</p> <h3 id="the-twilight-zone">The Twilight Zone</h3> <p>Imagine that you live in an alternate dimension. You want to do some online shopping, and you have just received the latest Amazon.com client. You fire it up and do a product search for “Three’s Company DVDs”. All of the product data comes down the wire. We have the names, brands, and prices of the twenty most relevant “Three’s Company” related products. After the client gets the data, it goes to work! It builds all of the urls and applies them onto all of the product data that came down, so that you can click on the DVD set that you like. Wait, no! The client doesn’t do that!</p> <p>To anybody with a passing amount of knowledge about how to build a website, the situation above seems ridiculous. In this dimension, we have a web browser that knows how to read a representation of data called HTML, and render and activate the links that the server provides in that document. The server defines where the resources reside, so naturally, the server provides the links to those resources.</p> <h3 id="we-didnt-know-any-better">We Didn’t Know Any Better</h3> <p>My alternate universe attempted to describe a scenario in which the web that we know and love operates like an API that I designed last year. I think a lot of people design APIs in this way, i.e. they do what they need to do right now. They provide some locations on their server that allow a third party to read or write to some resources. That doesn’t sound so bad, right? An API totally needs to do those things, but it needs to do a little bit more. APIs are by definition publicly available, they invite themselves into a realm of of other people’s stuff that you no longer have total control over. As such, some forethought needs to be given to design up front. APIs that only provide the resources, and not the locations to next resource, are taking the short view and are introducing big problems for the future evolution of your system.</p> <p>The fatal flaw will smack you soon enough. When you rolled out the API, you promised all of the people, in your meticulously crafted documentation, that the resource they want is available at location x. They, in turn, built clients around that promise, and now you badly, badly need to change that location to y. Go ahead and update that documentation and see how much it helps. Best case scenario is that you built the client, and now you have to get everybody to update it before you can get back to doing anything productive on your end. To quote <a href="https://twitter.com/steveklabnik">Steve Klabnik</a>, “People are really good at screwing themselves over in the long term”.</p> <h3 id="robots-like-to-surf-the-web-too">Robots Like to Surf The Web Too</h3> <p>So what’s the solution? Let’s bring it back to the web to understand how we can address this. Grandma has a home page with a link people can click on to see pictures of all of her perfect grandchildren. Six months later Grandma finds a cheaper site for hosting those pictures and wants to put them there instead. As Grandma’s faithful webmaster, you update the link on her homepage to point to the new photo sharing site. Does the whole world need to update their web client now? Of course not, the link to the next resource is defined and provided by the server in the HTML it sends down, and that link just changed. I think the best short description of an API I’ve found is in Ryan Tomako’s article <a href="http://tomayko.com/writings/rest-to-my-wife">“How I Explained REST to My wife”</a>. Paraphrasing, an API is an interface for machines to use the web just like people do. APIs that don’t employ hypermedia are basically jerks that are saying to clients, “I know where to go next, but I’m going to make you guess how to get there anyway.” With a Hypermedia API you force the client to know the location of exactly one resource, “Home”.</p> <p>So applying Hypermedia to APIs provides solutions, but also really transforms the very nature of the interaction into something much cooler. APIs whose resources link to other resources become “engines of application state”. Every resource exposes it’s current state, and the paths that you can take to create, interact with, and shape it. When an API describes to you how to interact with it, clients can be designed in a static way, reactively handling changes from the server.</p> <h3 id="hypermedia-apis-in-practice">Hypermedia APIs in Practice</h3> <p>So how do you go about achieving this? Unfortunately, I have little practical experience to share. I understand a few things. People who talk about REST, talk about nouns and verbs. All APIs provide the nouns, Hypermedia APIs provide the verbs too. In addition to the data the APIs traditionally provide, at every step of the way they need to describe, with links, 1) where to start 2) where you are, and 3) where you can go next.</p> <p>There are definitely some best practices around things like content negotation and media types that you can read up on, but I gather from <a href="https://twitter.com/#!/cdmwebs">Chris Moore</a> that it’s still the Wild West for Hypermedia design. Apparently making more effective use of HTTP Headers is good design, and you want to give some thought about your content format, because types like JSON and XML are not implicitly hypermedia aware, i.e. they have no baked in concept of links.</p> <h3 id="acknowledgments">Acknowledgments</h3> <p>While I’m talking about what I do know, maybe it’s a good time to mention where I learned it. The impetus for all of this was <a href="https://vimeo.com/44520801">this talk</a> given by Steve Klabnik at the most recent <a href="http://cincyrb.com/">Cincy.rb</a> meetup, just a couple weeks ago. Steve’s done a ton of writing and speaking around this subject, just google him or pick up his evolving book, <a href="http://designinghypermediaapis.com/">“Designing Hypermedia APIs”</a>. The talk is an overview of what Hypermedia APIs are, why they’re important, and their philosophical implications. Thankfully, Steve gives us permissions to stop worrying and fighting about REST and focus on cool stuff. For the Rails folks, Steve recommends two gems, <a href="https://github.com/josevalim/a ctive_model_serializers/">active_model_serializers</a> and <a href="https://github.com/spastorino/rails- api">rails-api</a></p> <p>I also highly recommend this <a href="https://vimeo.com/20781278">video presentation</a> by Jon Moore, in which he actually demos a static client. If this link between Hypermedia APIs and the web as we know it is still nebulous, this video will solidify it for you. I really like the way Jon explains things and boils down the dissertation language, translating a block of Fielding into “You do stuff by reading pages and then either following links or submitting forms.”.</p> <p>For some deep reading, I’ve heard people recommend <a href="http://www.amazon.com/Building-Hypermedia-APIs- HTML5-Node/dp/1449306578">“Building Hypermedia APIs with HTML5 and Node”</a>. Don’t worry if you’re not a node programmer. I also want to give a shout to <a href="https://twitter.com/cdmwebs/">Chris Moore</a>, who’s been our resident Hypermedia API pusher, and <a href="https://twitter.com/SeanTAllen">Sean Allen</a>, who’s been harping to me about REST since before harping about REST was cool.</p> <h3 id="conclusion">Conclusion</h3> <p>If you need inspiration in understanding hypermedia APIs, look no further than the web. The architecture and protocols for the web were designed by really smart guys who already figured this stuff out a long time ago and can be applied universally. Once I started viewing APIs through the lense of the web I know and love, it actually seems completely wrong to design one in any other way.</p> </div> <div class="post__tags"> <h5>Posted in: </h5> <a class="tag" href="/blog/categories/development/index.html">Development</a> </div> </section> <section class="post__related"> <h3>Related Posts</h3> <div class="grid grid--2"> <a href="/blog/refactoring-patterns-in-elixir-replace-conditional-with-polymorphism-via-protocols-part-2" class="card card--feature"> <div class="card__content"> <h3>Refactoring Patterns in Elixir: Replace Conditional with Polymorphism Via Protocols Part 2</h3> <h4>Zack Kayser</h4> <p class="note"></p> Read More &rarr; </div> </a> <a href="/blog/outsourcing-custom-development-for-fast-paced-companies" class="card card--feature"> <div class="card__content"> <h3>Outsourcing Custom Development for Fast-Paced Companies </h3> <h4>Peter Kananen</h4> <p class="note"></p> Read More &rarr; </div> </a> <a href="/blog/oh-to-be-a-domain-expert-if-only-we-knew-what-you-know" class="card card--feature"> <div class="card__content"> <h3>Oh, to be a Domain Expert … if we only knew what you knew.</h3> <h4>Kati Best</h4> <p class="note"></p> Read More &rarr; </div> </a> <a href="/blog/gaslight-your-partner-in-growth" class="card card--feature"> <div class="card__content"> <h3>Gaslight, Your Partner in Growth</h3> <h4>Steve Hennegan</h4> <p class="note"></p> Read More &rarr; </div> </a> </div> </section> </article> <section class="section--light flush"> <div class="cta"> <img src="/assets/img/color-shapes-one.svg" class="cta__confetti" /> <div class="cta__container"> <div> <h3> Like what you're seeing? Let's keep in touch. </h3> <a href="/newsletter" class="btn btn--cta"> Subscribe to Our Newsletter </a> </div> </div> <img src="/assets/img/color-shapes-two.svg" class="cta__confetti" /> </div> </section> </main> <footer> <div class="footer__container"> <div class="footer__menu"> <div href="/" class="footer__logo"></div> <h5 class="u-push-bottom--none"><a class="inverse" href="/agility">Agility</a></h5> <h5 class="u-push-bottom--none"><a class="inverse" href="/who-we-are">About Us</a></h5> <h5 class="u-push-bottom--none"><a class="inverse" href="/events">Events</a></h5> <h5 class="u-push-bottom--none"><a class="inverse" href="/blog">Blog</a></h5> <h5 class="u-push-bottom--none"><a class="inverse" href="/connect">Contact Us</a></h5> <div class="footer__social"> <a href="https://www.instagram.com/rhythmdogsports/" target="_blank" class="social__link instagram"> <svg viewBox="0 0 50 50"> <path d="M16 3C8.83 3 3 8.83 3 16v18c0 7.17 5.83 13 13 13h18c7.17 0 13-5.83 13-13V16c0-7.17-5.83-13-13-13H16zm21 8c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm-12 3c6.07 0 11 4.93 11 11s-4.93 11-11 11-11-4.93-11-11 4.93-11 11-11zm0 2c-4.96 0-9 4.04-9 9s4.04 9 9 9 9-4.04 9-9-4.04-9-9-9z"/> </svg> </a> <!-- <a href="http://twitter.com/teamgaslight" target="_blank" class="social__link twitter"> <svg viewBox="0 0 50 50"> <path d="M50.06 10.44c-1.85.82-3.83 1.37-5.91 1.62 2.12-1.27 3.76-3.29 4.52-5.69a20.473 20.473 0 0 1-6.53 2.49c-1.88-2-4.55-3.25-7.5-3.25-5.68 0-10.29 4.6-10.29 10.28 0 .8.09 1.59.27 2.34C16.08 17.81 8.5 13.72 3.43 7.5c-.89 1.52-1.39 3.29-1.39 5.17 0 3.57 1.81 6.71 4.57 8.56-1.69-.05-3.27-.52-4.66-1.29v.13c0 4.98 3.55 9.14 8.25 10.09-.86.23-1.77.36-2.71.36-.66 0-1.31-.06-1.94-.19 1.31 4.08 5.11 7.06 9.61 7.14-3.52 2.76-7.95 4.4-12.77 4.4-.83 0-1.65-.05-2.45-.14 4.55 2.92 9.95 4.62 15.76 4.62 18.91 0 29.26-15.67 29.26-29.25 0-.45-.01-.89-.03-1.33 2.01-1.46 3.75-3.27 5.13-5.33z"/> </svg> </a> --> <a href="http://facebook.com/rhythmdogsports" target="_blank" class="social__link facebook"> <svg viewBox="0 0 50 50"> <path d="M41 4H9C6.24 4 4 6.24 4 9v32c0 2.76 2.24 5 5 5h32c2.76 0 5-2.24 5-5V9c0-2.76-2.24-5-5-5zm-4 15h-2c-2.14 0-3 .5-3 2v3h5l-1 5h-4v15h-5V29h-4v-5h4v-3c0-4 2-7 6-7 2.9 0 4 1 4 1v4z"/> </svg> </a> <!-- <a href="http://github.com/gaslight" target="_blank" class="social__link github"> <svg viewBox="0 0 50 50"> <path d="M33 29c-1.8 0-3 1.52-3 4s.89 5.05 3 5c2.22-.05 3.02-2.22 3-5-.02-2.48-1.21-4-3-4zm11.26-11.93c.27-1.34.39-6.1-1.58-11.07 0 0-4.53.5-11.38 5.2-1.43-.4-3.87-.6-6.3-.6s-4.86.2-6.3.59C11.85 6.5 7.32 6 7.32 6c-1.98 4.96-1.88 9.61-1.59 11.07C3.42 19.59 2 22.61 2 26.74 2 44.71 16.91 45 20.67 45h8.66C33.09 45 48 44.71 48 26.74c0-4.13-1.42-7.15-3.74-9.67zM25.14 43H25c-9.43 0-16.84-1.34-16.84-10.5 0-2.2.78-4.23 2.62-5.92 3.07-2.82 8.26-1.33 14.16-1.33h.14c5.89 0 11.09-1.49 14.16 1.33 1.84 1.69 2.61 3.73 2.61 5.92-.01 9.16-7.28 10.5-16.71 10.5zM17 29c-1.79 0-3 2.02-3 4.5s1.21 4.5 3 4.5c1.8 0 3-2.02 3-4.5S18.8 29 17 29z"/> </svg> </a> --> <!-- <a href="https://www.youtube.com/channel/UCC36CM_uLqhoKEqSy2mjqFQ" target="_blank" class="social__link youtube"> <svg viewBox="0 0 50 50"> <path d="M9 4C6.24 4 4 6.24 4 9v32c0 2.76 2.24 5 5 5h32c2.76 0 5-2.24 5-5V9c0-2.76-2.24-5-5-5H9zm6 4h2.4l1.6 4 1.6-4H23l-3 7v4h-2v-4.01c-.6-1.61-2.59-5.98-3-6.99zm10 3c.89 0 1.77.27 2.33.95.43.49.67 1.28.67 2.32v1.46c0 1.04-.2 1.76-.62 2.25-.56.67-1.49 1.02-2.38 1.02s-1.8-.35-2.36-1.02c-.43-.49-.64-1.21-.64-2.25v-1.45c0-1.04.23-1.84.67-2.33.56-.68 1.32-.95 2.33-.95zm4 0h2v6c.05.27.34.39.61.39.41 0 .93-.48 1.39-1.01V11h2v8h-2v-1.38c-.81.79-1.5 1.38-2.41 1.35-.66-.02-1.12-.26-1.35-.74-.14-.28-.24-.73-.24-1.39V11zm-4 1.62c-.14 0-.27.03-.39.08a1.016 1.016 0 0 0-.53.54c-.05.13-.08.26-.08.4v2.81a1.02 1.02 0 0 0 .61.94c.12.05.25.08.39.08s.27-.03.39-.08c.36-.16.61-.52.61-.94v-2.81c0-.56-.45-1.02-1-1.02zM24.99 22h.02s6.71 0 11.19.32c.63.07 1.99.08 3.21 1.33.96.94 1.27 3.1 1.27 3.1s.32 1.53.32 4.06v2.37c0 2.53-.32 4.06-.32 4.06s-.31 2.16-1.27 3.1c-1.22 1.25-2.58 1.26-3.21 1.33-4.48.32-11.2.33-11.2.33s-8.32-.08-10.88-.32c-.71-.13-2.31-.09-3.53-1.33-.96-.95-1.27-3.11-1.27-3.11S9 35.71 9 33.18v-2.37c0-2.53.32-4.06.32-4.06s.31-2.16 1.27-3.1c1.22-1.25 2.58-1.26 3.21-1.33C18.28 22 24.99 22 24.99 22zM12 26v1.98h2V38h2V27.98h2V26h-6zm13 0v12h2v-1.25c.63.78 1.45 1.25 2.12 1.25.75 0 1.41-.4 1.66-1.18.12-.42.21-.81.21-1.7v-2.75c0-.99-.13-1.73-.26-2.15-.24-.78-.85-1.22-1.61-1.22-.98-.01-1.38.5-2.12 1.38V26h-2zm-7 3v6.69c0 .72.1 1.21.23 1.52.22.51.67.79 1.31.79.73 0 1.67-.51 2.46-1.37V38h2v-9h-2v6.27c-.44.58-1.08 1.02-1.48 1.02-.26 0-.47-.11-.52-.4V29h-2zm17.03 0c-1.01 0-1.8.32-2.37.92-.42.44-.66 1.16-.66 2.1v3.07c0 .93.27 1.58.69 2.02.57.6 1.36.9 2.39.9s1.84-.31 2.39-.95c.24-.28.39-.6.46-.95.01-.17.07-.6.07-1.11h-2v.8c0 .46-.45.84-1 .84s-1-.38-1-.84V34h4v-2.03c0-.93-.23-1.62-.64-2.06-.56-.59-1.34-.91-2.33-.91zM35 30.45c.55 0 1 .38 1 .84v1.33h-2v-1.33c0-.47.45-.84 1-.84zm-6.78.3c.55 0 .78.33.78 1.38v2.75c0 1.04-.23 1.4-.78 1.4-.31 0-.9-.21-1.22-.53v-4.38c.32-.31.91-.62 1.22-.62z"/> </svg> </a> --> <!-- <a href="https://www.linkedin.com/company/gaslight" target="_blank" class="social__link linkedin"> <svg viewBox="0 0 50 50"> <path d="M41 4H9C6.24 4 4 6.24 4 9v32c0 2.76 2.24 5 5 5h32c2.76 0 5-2.24 5-5V9c0-2.76-2.24-5-5-5zM17 20v19h-6V20h6zm-6-5.53c0-1.4 1.2-2.47 3-2.47s2.93 1.07 3 2.47c0 1.4-1.12 2.53-3 2.53-1.8 0-3-1.13-3-2.53zM39 39h-6V29c0-2-1-4-3.5-4.04h-.08C27 24.96 26 27.02 26 29v10h-6V20h6v2.56S27.93 20 31.81 20c3.97 0 7.19 2.73 7.19 8.26V39z"/> </svg> </a> --> </div> </div> </div> </footer> <script src="/assets/js/scale.fix.js"></script> <script src="/assets/js/rellax.min.js"></script> <script> var rellax = new Rellax('.float', { speed: -2, center: false, wrapper: null, round: true, vertical: true, horizontal: false }); </script> <!-- Start of HubSpot Embed Code --> <script type="text/javascript" id="hs-script-loader" async defer src="//js.hs-scripts.com/509988.js"></script> <!-- End of HubSpot Embed Code --> </body> </html>
45.724731
1,895
0.651444
c22584a95a769266a3f1b1bc9f7a0fcdbfa2af75
62
go
Go
protocol/db/db.go
koron/nvd
502f554c5c09c6f1e60f50133045b9013aadfdef
[ "MIT" ]
9
2016-07-04T01:03:38.000Z
2020-04-15T10:27:28.000Z
protocol/db/db.go
koron/nvgd
502f554c5c09c6f1e60f50133045b9013aadfdef
[ "MIT" ]
38
2016-04-16T13:53:05.000Z
2020-12-16T06:54:07.000Z
protocol/db/db.go
koron/nvd
502f554c5c09c6f1e60f50133045b9013aadfdef
[ "MIT" ]
1
2019-04-10T17:18:38.000Z
2019-04-10T17:18:38.000Z
// Package db provides database protocol for NVGD. package db
20.666667
50
0.790323
1753851152125bfa5f2ed07039221729d4998eae
391
html
HTML
src/app/components/permission-denied/permission-denied.component.html
CubingItaly/cubingitaly.org
3f3c1fa3e7b73e5e042266225c42245562af53a3
[ "MIT" ]
3
2018-04-05T14:28:58.000Z
2019-08-20T14:12:48.000Z
src/app/components/permission-denied/permission-denied.component.html
CubingItaly/cubingitaly.org
3f3c1fa3e7b73e5e042266225c42245562af53a3
[ "MIT" ]
null
null
null
src/app/components/permission-denied/permission-denied.component.html
CubingItaly/cubingitaly.org
3f3c1fa3e7b73e5e042266225c42245562af53a3
[ "MIT" ]
null
null
null
<div fxLayout="column" fxLayoutAlign="center center" fxFillLayout> <h1>Errore 403</h1> <p>Non hai i permessi per visualizzare la pagina richiesta.</p> <p>Se pensi sia un errore contatta gli <a href="mailto:cubingitaly@gmail.com">amministratori</a>.</p> <div fxLayout fxLayoutAlign="center center"> <img fxFlex="40%" fxFlex.xs="70%" src="/assets/images/error.png"> </div> </div>
48.875
103
0.710997
8056e121406dd6f41fd263fe053e63a89e823e0d
885
java
Java
jadx-core/src/main/java/jadx/core/dex/instructions/IndexInsnNode.java
wwj402/jadx
382356089f42705d8611547f37bec6e5149fd401
[ "Apache-2.0" ]
null
null
null
jadx-core/src/main/java/jadx/core/dex/instructions/IndexInsnNode.java
wwj402/jadx
382356089f42705d8611547f37bec6e5149fd401
[ "Apache-2.0" ]
null
null
null
jadx-core/src/main/java/jadx/core/dex/instructions/IndexInsnNode.java
wwj402/jadx
382356089f42705d8611547f37bec6e5149fd401
[ "Apache-2.0" ]
null
null
null
package jadx.core.dex.instructions; import jadx.core.dex.nodes.InsnNode; import jadx.core.utils.InsnUtils; public class IndexInsnNode extends InsnNode { private final Object index; public IndexInsnNode(InsnType type, Object index, int argCount) { super(type, argCount); this.index = index; } public Object getIndex() { return index; } @Override public IndexInsnNode copy() { return copyCommonParams(new IndexInsnNode(insnType, index, getArgsCount())); } @Override public boolean isSame(InsnNode obj) { if (this == obj) { return true; } if (!(obj instanceof IndexInsnNode) || !super.isSame(obj)) { return false; } IndexInsnNode other = (IndexInsnNode) obj; return index == null ? other.index == null : index.equals(other.index); } @Override public String toString() { return super.toString() + ' ' + InsnUtils.indexToString(index); } }
21.585366
78
0.708475
6e42b32272d7054b175bbc11524d2a5382b576c5
5,659
html
HTML
vendor/plugins/ruby-rtf/rdoc/classes/RTF/RTFError.html
alfcrisci/mushroom-observer
f8b901ed5acaac40356ccb24bee4e0543d3def23
[ "MIT" ]
1
2019-06-13T15:55:05.000Z
2019-06-13T15:55:05.000Z
vendor/plugins/ruby-rtf/rdoc/classes/RTF/RTFError.html
alfcrisci/mushroom-observer
f8b901ed5acaac40356ccb24bee4e0543d3def23
[ "MIT" ]
null
null
null
vendor/plugins/ruby-rtf/rdoc/classes/RTF/RTFError.html
alfcrisci/mushroom-observer
f8b901ed5acaac40356ccb24bee4e0543d3def23
[ "MIT" ]
null
null
null
<?xml version="1.0" encoding="iso-8859-1"?> <!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>Class: RTF::RTFError</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <meta http-equiv="Content-Script-Type" content="text/javascript" /> <link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" /> <script type="text/javascript"> // <![CDATA[ function popupCode( url ) { window.open(url, "Code", "resizable=yes,scrollbars=yes,toolbar=no,status=no,height=150,width=400") } function toggleCode( id ) { if ( document.getElementById ) elem = document.getElementById( id ); else if ( document.all ) elem = eval( "document.all." + id ); else return false; elemStyle = elem.style; if ( elemStyle.display != "block" ) { elemStyle.display = "block" } else { elemStyle.display = "none" } return true; } // Make codeblocks hidden by default document.writeln( "<style type=\"text/css\">div.method-source-code { display: none }</style>" ) // ]]> </script> </head> <body> <div id="classHeader"> <table class="header-table"> <tr class="top-aligned-row"> <td><strong>Class</strong></td> <td class="class-name-in-header">RTF::RTFError</td> </tr> <tr class="top-aligned-row"> <td><strong>In:</strong></td> <td> <a href="../../files/lib/rtf_rb.html"> lib/rtf.rb </a> <br /> </td> </tr> <tr class="top-aligned-row"> <td><strong>Parent:</strong></td> <td> StandardError </td> </tr> </table> </div> <!-- banner header --> <div id="bodyContent"> <div id="contextContent"> <div id="description"> <p> This is the exception class used by the <a href="../RTF.html">RTF</a> library code to indicate errors. </p> </div> </div> <div id="method-list"> <h3 class="section-bar">Methods</h3> <div class="name-list"> <a href="#M000112">fire</a>&nbsp;&nbsp; <a href="#M000111">new</a>&nbsp;&nbsp; </div> </div> </div> <!-- if includes --> <div id="section"> <!-- if method_list --> <div id="methods"> <h3 class="section-bar">Public Class methods</h3> <div id="method-M000112" class="method-detail"> <a name="M000112"></a> <div class="method-heading"> <a href="#M000112" class="method-signature"> <span class="method-name">fire</span><span class="method-args">(message=nil)</span> </a> </div> <div class="method-description"> <p> This method provides a short cut for raising RTFErrors. </p> <h4>Parameters</h4> <table> <tr><td valign="top">message:</td><td>A string containing the exception message. Defaults to nil. </td></tr> </table> <p><a class="source-toggle" href="#" onclick="toggleCode('M000112-source');return false;">[Source]</a></p> <div class="method-source-code" id="M000112-source"> <pre> <span class="ruby-comment cmt"># File lib/rtf.rb, line 30</span> 30: <span class="ruby-keyword kw">def</span> <span class="ruby-constant">RTFError</span>.<span class="ruby-identifier">fire</span>(<span class="ruby-identifier">message</span>=<span class="ruby-keyword kw">nil</span>) 31: <span class="ruby-identifier">raise</span> <span class="ruby-constant">RTFError</span>.<span class="ruby-identifier">new</span>(<span class="ruby-identifier">message</span>) 32: <span class="ruby-keyword kw">end</span> </pre> </div> </div> </div> <div id="method-M000111" class="method-detail"> <a name="M000111"></a> <div class="method-heading"> <a href="#M000111" class="method-signature"> <span class="method-name">new</span><span class="method-args">(message=nil)</span> </a> </div> <div class="method-description"> <p> This is the constructor for the <a href="RTFError.html">RTFError</a> class. </p> <h4>Parameters</h4> <table> <tr><td valign="top">message:</td><td>A reference to a string containing the error message for the exception defaults to nil. </td></tr> </table> <p><a class="source-toggle" href="#" onclick="toggleCode('M000111-source');return false;">[Source]</a></p> <div class="method-source-code" id="M000111-source"> <pre> <span class="ruby-comment cmt"># File lib/rtf.rb, line 22</span> 22: <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">initialize</span>(<span class="ruby-identifier">message</span>=<span class="ruby-keyword kw">nil</span>) 23: <span class="ruby-keyword kw">super</span>(<span class="ruby-identifier">message</span> <span class="ruby-operator">==</span> <span class="ruby-keyword kw">nil</span> <span class="ruby-operator">?</span> <span class="ruby-value str">'No error message available.'</span> <span class="ruby-operator">:</span> <span class="ruby-identifier">message</span>) 24: <span class="ruby-keyword kw">end</span> </pre> </div> </div> </div> </div> </div> <div id="validator-badges"> <p><small><a href="http://validator.w3.org/check/referer">[Validate]</a></small></p> </div> </body> </html>
28.872449
365
0.582435
ff8b94b75cb213220178a8ba4c13d896947462f1
780
lua
Lua
moonpie/tables/same_spec.lua
tredfern/moonpie
b7b6542007a4acd6ca01c7d36957b10774ba242b
[ "MIT" ]
5
2019-04-16T09:55:57.000Z
2021-01-31T21:50:47.000Z
moonpie/tables/same_spec.lua
tredfern/moonpie
b7b6542007a4acd6ca01c7d36957b10774ba242b
[ "MIT" ]
7
2021-04-26T12:14:05.000Z
2022-02-15T13:26:13.000Z
moonpie/tables/same_spec.lua
tredfern/moonpie
b7b6542007a4acd6ca01c7d36957b10774ba242b
[ "MIT" ]
null
null
null
-- Copyright (c) 2021 Trevor Redfern -- -- This software is released under the MIT License. -- https://opensource.org/licenses/MIT describe("moonpie.tables.same", function() local same = require "moonpie.tables.same" it("makes sure that the two tables have the equal values in the same index", function() local t1 = {1, 2, 3} local t2 = {1, 2, 3} local t3 = {3, 2, 1} local t4 = {4, 3, 2, 1} assert.is_true(same(t1, t2)) assert.is_false(same(t1, t3)) assert.is_false(same(t1, t4)) end) it("returns true if both are nil", function() assert.is_true(same(nil, nil)) end) it("returns false if one of them is nil", function() assert.is_false(same({}, nil)) assert.is_false(same(nil, {})) end) end)
26.896552
90
0.619231
fc589e6e5d914987377b336fbd7361d78be67cc0
2,983
kt
Kotlin
app/src/main/java/com/example/androiddevchallenge/ui/animation/AnimatedCircle.kt
mal7othify/Countdown-timer
f7ab005b5ec0426c8abd657bdf64829802dc87c8
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/androiddevchallenge/ui/animation/AnimatedCircle.kt
mal7othify/Countdown-timer
f7ab005b5ec0426c8abd657bdf64829802dc87c8
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/androiddevchallenge/ui/animation/AnimatedCircle.kt
mal7othify/Countdown-timer
f7ab005b5ec0426c8abd657bdf64829802dc87c8
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 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 * * https://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.example.androiddevchallenge.ui.animation import androidx.compose.animation.core.LinearEasing import androidx.compose.animation.core.RepeatMode import androidx.compose.animation.core.animateFloat import androidx.compose.animation.core.infiniteRepeatable import androidx.compose.animation.core.rememberInfiniteTransition import androidx.compose.animation.core.tween import androidx.compose.foundation.Canvas import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.drawscope.Stroke import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @Composable fun AnimatedCircle( modifier: Modifier = Modifier ) { val transition = rememberInfiniteTransition() val angleOffset by transition.animateFloat( initialValue = 0f, targetValue = 360f, animationSpec = infiniteRepeatable( tween( durationMillis = 25900, easing = LinearEasing ), RepeatMode.Restart ) ) val stroke = Stroke(width = 280f, cap = StrokeCap.Butt) Canvas(modifier) { val innerRadius = (size.minDimension - stroke.width) / 2 val halfSize = size / 2.0f val topLeft = Offset( halfSize.width - innerRadius, halfSize.height - innerRadius ) val size = Size(innerRadius * 2, innerRadius * 2) drawArc( color = Color.White, startAngle = angleOffset - 90f, sweepAngle = 1.5f, topLeft = topLeft, size = size, useCenter = false, style = stroke ) } } @Preview(name = "Circle Preview", showBackground = true) @Composable fun CirclePreview() { Box { AnimatedCircle( modifier = Modifier .height(300.dp) .align(Alignment.Center) .fillMaxWidth() ) } }
33.516854
75
0.695608
c6f522832a6b431f49407b04f274f843dc7b61e3
105
sql
SQL
corpus/scripts/Kill_newlines.sql
alexeyqu/zadolbali_corpus
dd12dc915106948ccce26562b3f139913123f867
[ "MIT" ]
null
null
null
corpus/scripts/Kill_newlines.sql
alexeyqu/zadolbali_corpus
dd12dc915106948ccce26562b3f139913123f867
[ "MIT" ]
null
null
null
corpus/scripts/Kill_newlines.sql
alexeyqu/zadolbali_corpus
dd12dc915106948ccce26562b3f139913123f867
[ "MIT" ]
null
null
null
Update stories set text = REPLACE( REPLACE( REPLACE( text, CHAR(13), ' '), CHAR(11), ' '), CHAR(10), ' ')
52.5
90
0.6
615ab3f36b41c3581c116d07703bab8db6a2397f
613
kt
Kotlin
src/main/java/io/github/hnosmium0001/actionale/core/MathUtil.kt
hnOsmium0001/Actionale
dc6b7ca8945c2bb3659c5b4176bfe91005cb5432
[ "MIT" ]
1
2021-02-24T00:59:44.000Z
2021-02-24T00:59:44.000Z
src/main/java/io/github/hnosmium0001/actionale/core/MathUtil.kt
hnOsmium0001/Actionale
dc6b7ca8945c2bb3659c5b4176bfe91005cb5432
[ "MIT" ]
1
2020-07-21T16:44:50.000Z
2020-07-21T18:30:51.000Z
src/main/java/io/github/hnosmium0001/actionale/core/MathUtil.kt
hnOsmium0001/Actionale
dc6b7ca8945c2bb3659c5b4176bfe91005cb5432
[ "MIT" ]
1
2021-02-24T00:59:47.000Z
2021-02-24T00:59:47.000Z
package io.github.hnosmium0001.actionale.core import net.minecraft.client.util.math.Vector3d fun Int.isEven() = this % 2 == 0 fun Int.isOdd() = this % 2 == 1 fun Vector3d.pointInTriangle(p1: Vector3d, p2: Vector3d, p3: Vector3d): Boolean { val d1 = signOf(this, p1, p2) val d2 = signOf(this, p2, p3) val d3 = signOf(this, p3, p1) val hasNeg = d1 < 0 || d2 < 0 || d3 < 0 val hasPos = d1 > 0 || d2 > 0 || d3 > 0 return !(hasNeg && hasPos) } private fun signOf(p1: Vector3d, p2: Vector3d, p3: Vector3d): Double { return (p1.x - p3.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p3.y); }
32.263158
81
0.60522
70c05bd4f2a52a6a95b64bc4bf83ceeaf39430de
4,521
go
Go
pkg/osquery/tables/gsettings/gsettings.go
zwass/launcher
554bd92531311b42e6dfb476b5515c93f68970dd
[ "MIT" ]
null
null
null
pkg/osquery/tables/gsettings/gsettings.go
zwass/launcher
554bd92531311b42e6dfb476b5515c93f68970dd
[ "MIT" ]
null
null
null
pkg/osquery/tables/gsettings/gsettings.go
zwass/launcher
554bd92531311b42e6dfb476b5515c93f68970dd
[ "MIT" ]
null
null
null
// +build !windows package gsettings import ( "bufio" "bytes" "context" "fmt" "io" "io/ioutil" "os" "os/exec" "os/user" "strconv" "strings" "syscall" "time" "github.com/go-kit/kit/log" "github.com/go-kit/kit/log/level" "github.com/kolide/launcher/pkg/osquery/tables/tablehelpers" osquery "github.com/kolide/osquery-go" "github.com/kolide/osquery-go/plugin/table" "github.com/pkg/errors" ) const gsettingsPath = "/usr/bin/gsettings" const allowedCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-." type gsettingsExecer func(ctx context.Context, username string, buf *bytes.Buffer) error type GsettingsValues struct { client *osquery.ExtensionManagerClient logger log.Logger getBytes gsettingsExecer } // Settings returns a table plugin for querying setting values from the // gsettings command. func Settings(client *osquery.ExtensionManagerClient, logger log.Logger) *table.Plugin { columns := []table.ColumnDefinition{ table.TextColumn("schema"), table.TextColumn("key"), table.TextColumn("value"), table.TextColumn("username"), } t := &GsettingsValues{ client: client, logger: logger, getBytes: execGsettings, } return table.NewPlugin("kolide_gsettings", columns, t.generate) } func (t *GsettingsValues) generate(ctx context.Context, queryContext table.QueryContext) ([]map[string]string, error) { var results []map[string]string users := tablehelpers.GetConstraints(queryContext, "username", tablehelpers.WithAllowedCharacters(allowedCharacters)) if len(users) < 1 { return results, errors.New("kolide_gsettings requires at least one username to be specified") } for _, username := range users { var output bytes.Buffer err := t.getBytes(ctx, username, &output) if err != nil { level.Info(t.logger).Log( "msg", "error getting bytes for user", "username", username, "err", err, ) continue } user_results := t.parse(username, &output) results = append(results, user_results...) } return results, nil } // execGsettings writes the output of running 'gsettings' command into the // supplied bytes buffer func execGsettings(ctx context.Context, username string, buf *bytes.Buffer) error { ctx, cancel := context.WithTimeout(ctx, 2*time.Second) defer cancel() u, err := user.Lookup(username) if err != nil { return errors.Wrapf(err, "finding user by username '%s'", username) } cmd := exec.CommandContext(ctx, gsettingsPath, "list-recursively") // set the HOME for the the cmd so that gsettings is exec'd properly as the // new user. cmd.Env = append(cmd.Env, fmt.Sprintf("HOME=%s", u.HomeDir)) // Check if the supplied UID is that of the current user currentUser, err := user.Current() if err != nil { return errors.Wrap(err, "checking current user uid") } if u.Uid != currentUser.Uid { uid, err := strconv.ParseInt(u.Uid, 10, 32) if err != nil { return errors.Wrap(err, "converting uid from string to int") } gid, err := strconv.ParseInt(u.Gid, 10, 32) if err != nil { return errors.Wrap(err, "converting gid from string to int") } cmd.SysProcAttr = &syscall.SysProcAttr{} cmd.SysProcAttr.Credential = &syscall.Credential{ Uid: uint32(uid), Gid: uint32(gid), } } dir, err := ioutil.TempDir("", "osq-gsettings") if err != nil { return errors.Wrap(err, "mktemp") } defer os.RemoveAll(dir) // if we don't chmod the dir, we get errors like: // 'fork/exec /usr/bin/gsettings: permission denied' if err := os.Chmod(dir, 0755); err != nil { return errors.Wrap(err, "chmod") } cmd.Dir = dir stderr := new(bytes.Buffer) cmd.Stderr = stderr cmd.Stdout = buf if err := cmd.Run(); err != nil { return errors.Wrapf(err, "running gsettings, err is: %s", stderr.String()) } return nil } func (t *GsettingsValues) parse(username string, input io.Reader) []map[string]string { var results []map[string]string scanner := bufio.NewScanner(input) for scanner.Scan() { line := scanner.Text() if line == "" { continue } parts := strings.SplitN(line, " ", 3) if len(parts) < 3 { level.Error(t.logger).Log( "msg", "unable to process line, not enough segments", "line", line, ) continue } row := make(map[string]string) row["schema"] = parts[0] row["key"] = parts[1] row["value"] = parts[2] row["username"] = username results = append(results, row) } if err := scanner.Err(); err != nil { level.Debug(t.logger).Log("msg", "scanner error", "err", err) } return results }
24.570652
119
0.688786
4e5978b20dae51f14b391f2ecac95d56c80f9c3e
118
ps1
PowerShell
Modules/PowerTab/TabExpansion.ps1
trailynx/myPs
b29aaa0e855a78cd5d985d20366fc03526e010c2
[ "MIT" ]
2
2020-10-23T18:47:48.000Z
2021-07-12T22:49:08.000Z
code/ps/profile/WindowsPowerShell/Modules/PowerTab/TabExpansion.ps1
BoolNordicAB/project-blinkenlights
c8d6b5eb06dd1ef7c674ceac1ac061586f8683cc
[ "MIT" ]
null
null
null
code/ps/profile/WindowsPowerShell/Modules/PowerTab/TabExpansion.ps1
BoolNordicAB/project-blinkenlights
c8d6b5eb06dd1ef7c674ceac1ac061586f8683cc
[ "MIT" ]
1
2021-07-12T22:49:11.000Z
2021-07-12T22:49:11.000Z
Function global:TabExpansion { param($Line, $LastWord) Invoke-TabExpansion -Line $Line -LastWord $LastWord }
19.666667
55
0.720339
9f48f9da07df97287bb797636161f4b4b0f113dc
1,454
asm
Assembly
assets/assembly/IA32/linux_nasm_progs/nasm_linux_ORG_CH10/procex2.asm
edassis/SB-Tradutor
9e5a5836e6cf978face35023620257fce684c257
[ "MIT" ]
1
2021-02-09T22:24:34.000Z
2021-02-09T22:24:34.000Z
assets/assembly/IA32/linux_nasm_progs/nasm_linux_ORG_CH10/procex2.asm
edassis/SB-Tradutor
9e5a5836e6cf978face35023620257fce684c257
[ "MIT" ]
null
null
null
assets/assembly/IA32/linux_nasm_progs/nasm_linux_ORG_CH10/procex2.asm
edassis/SB-Tradutor
9e5a5836e6cf978face35023620257fce684c257
[ "MIT" ]
null
null
null
;Parameter passing via registers PROCEX2.ASM ; ; Objective: To show parameter passing via registers ; Input: Requests a character string from the user. ; Output: Outputs the length of the input string. %include "io.mac" BUF_LEN EQU 41 ; string buffer length .DATA prompt_msg db "Please input a string: ",0 length_msg db "The string length is ",0 .UDATA string resb BUF_LEN ;input string < BUF_LEN chars. .CODE .STARTUP PutStr prompt_msg ; request string input GetStr string,BUF_LEN ; read string from keyboard mov EBX,string ; EBX := string address call str_len ; returns string length in AX PutStr length_msg ; display string length PutInt AX nwln done: .EXIT ;----------------------------------------------------------- ;Procedure str_len receives a pointer to a string in BX. ; String length is returned in AX. ;----------------------------------------------------------- ;section .text .CODE str_len: push EBX sub AX,AX ; string length := 0 repeat: cmp byte [EBX],0 ; compare with NULL char. je str_len_done ; if NULL we are done inc AX ; else, increment string length inc EBX ; point BX to the next char. jmp repeat ; and repeat the process str_len_done: pop EBX ret
30.291667
62
0.552957
2cfee0d3defdea7e7fb6ae7f228b21b43e875d06
9,488
asm
Assembly
Appl/Startup/RStartup/rstartupApp.asm
steakknife/pcgeos
95edd7fad36df400aba9bab1d56e154fc126044a
[ "Apache-2.0" ]
504
2018-11-18T03:35:53.000Z
2022-03-29T01:02:51.000Z
Appl/Startup/RStartup/rstartupApp.asm
steakknife/pcgeos
95edd7fad36df400aba9bab1d56e154fc126044a
[ "Apache-2.0" ]
96
2018-11-19T21:06:50.000Z
2022-03-06T10:26:48.000Z
Appl/Startup/RStartup/rstartupApp.asm
steakknife/pcgeos
95edd7fad36df400aba9bab1d56e154fc126044a
[ "Apache-2.0" ]
73
2018-11-19T20:46:53.000Z
2022-03-29T00:59:26.000Z
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% (c) Copyright Geoworks 1995 -- All Rights Reserved GEOWORKS CONFIDENTIAL PROJECT: PC GEOS MODULE: Start up FILE: rstartupApp.asm AUTHOR: Jason Ho, Aug 28, 1995 METHODS: Name Description ---- ----------- ROUTINES: Name Description ---- ----------- REVISION HISTORY: Name Date Description ---- ---- ----------- kho 8/28/95 Initial revision DESCRIPTION: Code for RStartupApplicationClass. $Id: rstartupApp.asm,v 1.1 97/04/04 16:52:36 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ CommonCode segment resource COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% RSAMetaNotify %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: All purpose MetaClass expansion message. Frequently used in conjunction with GCN mechanism CALLED BY: MSG_META_NOTIFY PASS: *ds:si = RStartupApplicationClass object ds:di = RStartupApplicationClass instance data es = segment of RStartupApplicationClass ax = message # cx:dx - NotificationType cx - NT_manuf dx - NT_type bp - change specific data RETURN: nothing DESTROYED: ax, cx, dx, bp SIDE EFFECTS: PSEUDO CODE/STRATEGY: In this application, we should ignore the application keys (so that nothing else runs) -- ie. when dx = GWNT_STARTUP_INDEXED_APP. REVISION HISTORY: Name Date Description ---- ---- ----------- kho 5/ 1/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ RSAMetaNotify method dynamic RStartupApplicationClass, MSG_META_NOTIFY .enter ; ; if dx != GWNT_STARTUP_INDEXED_APP, call super ; if 0 PrintMessage<Take me away! No Hard icons!> else cmp dx, GWNT_STARTUP_INDEXED_APP jne callSuper ; ; see if we are ignoring application keys right now - this is ; necessary because we will launch phone app (or contact ; manager) when we quit. If we keep ignoring the key, the app ; will not start ; test ds:[di].RSAI_miscFlags, mask RSAF_ACCEPT_HARD_ICON jz quit callSuper: ; ; Call super ; endif mov di, offset RStartupApplicationClass GOTO ObjCallSuperNoLock quit:: .leave ret RSAMetaNotify endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% RSAMetaQuit %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Close IACP connection before quiting the app This should not be done in CLOSE_APPLICATION: you will never reach that far if there is IACP connection. CALLED BY: MSG_META_QUIT PASS: *ds:si = RStartupApplicationClass object ds:di = RStartupApplicationClass instance data es = segment of RStartupApplicationClass ax = message # ^lcx:dx = object to send MSG_META_QUIT_ACK to RETURN: nothing DESTROYED: ax, cx, dx, bp SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- kho 6/23/95 Initial version (copied from FAMetaQuit, kertes) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if DO_ECI_SIM_CARD_CHECK ;-------------------------------------------- RSAMetaQuit method dynamic RStartupApplicationClass, MSG_META_QUIT uses ax, bx, cx, dx, bp .enter CheckHack <size VpCloseIacpParams eq \ size VpDeinstallClientParams> ; ; Deinstall the client from VP library, and ; close that pesky IACP connection that they have to us or we ; will never be able to quit ; sub sp, size VpCloseIacpParams mov bp, sp CheckHack < size TokenChars eq 4 > mov {word} ss:[bp].VCIAP_geodeToken.GT_chars, 'ST' mov {word} ss:[bp].VCIAP_geodeToken.GT_chars+2, 'AU' mov {word} ss:[bp].GT_manufID, MANUFACTURER_ID_GEOWORKS call VpDeinstallClient ; ax, bx, cx, ; dx destroyed call VpCloseIacp ; ax, bx, cx, ; dx destroyed add sp, size VpCloseIacpParams .leave ; ; Call superclas to do normal stuff ; mov di, offset RStartupApplicationClass GOTO ObjCallSuperNoLock RSAMetaQuit endm endif ;----------------------------------------------------------- if 0 COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% RSARstartupAppAcceptAppKey %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Mark that we will accept application keys CALLED BY: MSG_RSTARTUP_APP_ACCEPT_APP_KEY PASS: *ds:si = RStartupApplicationClass object ds:di = RStartupApplicationClass instance data es = segment of RStartupApplicationClass ax = message # RETURN: nothing DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: We need this because we ignore app key when user is doing startup, but then we have to launch PHONE app (or CONTACT MGR) ourselves before we quit. If we do not mark that we accept keys, the launch from FoamLaunchApplication will also be ignored. REVISION HISTORY: Name Date Description ---- ---- ----------- kho 5/ 3/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ RSARstartupAppAcceptAppKey -- OBSOLETE -- method dynamic RStartupApplicationClass, MSG_RSTARTUP_APP_ACCEPT_APP_KEY .enter BitSet ds:[di].RSAI_miscFlags, RSAF_ACCEPT_HARD_ICON .leave ret RSARstartupAppAcceptAppKey endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% RSARstartupAppKbdTypeChanged %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Mark that the kbd type is changed, so we should reboot later. CALLED BY: MSG_RSTARTUP_APP_KBD_TYPE_CHANGED PASS: *ds:si = RStartupApplicationClass object ds:di = RStartupApplicationClass instance data es = segment of RStartupApplicationClass ax = message # RETURN: nothing DESTROYED: nothing SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- kho 8/28/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ RSARstartupAppKbdTypeChanged -- OBSOLETE -- method dynamic RStartupApplicationClass, MSG_RSTARTUP_APP_KBD_TYPE_CHANGED .enter BitSet ds:[di].RSAI_miscFlags, RSAF_KBD_TYPE_CHANGED .leave ret RSARstartupAppKbdTypeChanged endm endif COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% RSARstartupAppIsKbdTypeChanged %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Return whether the kbd type is changed. CALLED BY: MSG_RSTARTUP_APP_IS_KBD_TYPE_CHANGED PASS: *ds:si = RStartupApplicationClass object ds:di = RStartupApplicationClass instance data es = segment of RStartupApplicationClass ax = message # RETURN: cx = TRUE or FALSE DESTROYED: ax SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- kho 8/28/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ if 0 RSARstartupAppIsKbdTypeChanged method dynamic RStartupApplicationClass, MSG_RSTARTUP_APP_IS_KBD_TYPE_CHANGED .enter mov cx, TRUE test ds:[di].RSAI_miscFlags, mask RSAF_KBD_TYPE_CHANGED jnz quit clr cx quit: .leave ret RSARstartupAppIsKbdTypeChanged endm endif ; 0 COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% RSARstartupAppSetAppFlags %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Set the app flags. CALLED BY: MSG_RSTARTUP_APP_SET_APP_FLAGS PASS: *ds:si = RStartupApplicationClass object ds:di = RStartupApplicationClass instance data es = segment of RStartupApplicationClass ax = message # cl = RStartupApplicationFlags record RETURN: nothing DESTROYED: ax SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- kho 9/13/95 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ RSARstartupAppSetAppFlags method dynamic RStartupApplicationClass, MSG_RSTARTUP_APP_SET_APP_FLAGS .enter EC < Assert record, cl, RStartupApplicationFlags > ornf ds:[di].RSAI_miscFlags, cl .leave ret RSARstartupAppSetAppFlags endm COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% RStartupAppMetaBringUpHelp %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SYNOPSIS: Ignore all help request CALLED BY: MSG_META_BRING_UP_HELP PASS: *ds:si = RStartupApplicationClass object ds:di = RStartupApplicationClass instance data ds:bx = RStartupApplicationClass object (same as *ds:si) es = segment of RStartupApplicationClass ax = message # RETURN: nothing DESTROYED: ax SIDE EFFECTS: PSEUDO CODE/STRATEGY: REVISION HISTORY: Name Date Description ---- ---- ----------- kho 4/ 5/96 Initial version %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ RStartupAppMetaBringUpHelp method dynamic RStartupApplicationClass, MSG_META_BRING_UP_HELP Destroy ax ret RStartupAppMetaBringUpHelp endm CommonCode ends
27.905882
86
0.573461
404214dba145417485f24ccdc2c7d9eb12ad54ac
1,402
py
Python
Course_Management/portal/migrations/0003_project_takesproject.py
RohanShrothrium/CourseManagement
fa7529cca2f02b937bad2ef4886582614d8bff3f
[ "Apache-2.0" ]
1
2019-10-29T16:56:06.000Z
2019-10-29T16:56:06.000Z
Course_Management/portal/migrations/0003_project_takesproject.py
RohanShrothrium/CourseManagement
fa7529cca2f02b937bad2ef4886582614d8bff3f
[ "Apache-2.0" ]
null
null
null
Course_Management/portal/migrations/0003_project_takesproject.py
RohanShrothrium/CourseManagement
fa7529cca2f02b937bad2ef4886582614d8bff3f
[ "Apache-2.0" ]
null
null
null
# Generated by Django 2.1.5 on 2019-11-10 17:09 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('portal', '0002_classroom_instructor'), ] operations = [ migrations.CreateModel( name='Project', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('ProjectID', models.CharField(default='', max_length=5)), ('InstID', models.CharField(default='', max_length=5)), ('Title', models.TextField()), ('Description', models.TextField()), ], ), migrations.CreateModel( name='TakesProject', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('Performance', models.TextField()), ('Feedback', models.TextField()), ('Project', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='portal.Project')), ('Student', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
37.891892
121
0.594864
80a75baf6bc5188ef1d2648b65d3ed5832ab3d69
2,955
java
Java
src/main/java/com/example/chessgame/Pieces/Bishop.java
JuniorZani/ChessGame
8065106ed6ed9644a875fb52913c58f1470825bf
[ "MIT" ]
null
null
null
src/main/java/com/example/chessgame/Pieces/Bishop.java
JuniorZani/ChessGame
8065106ed6ed9644a875fb52913c58f1470825bf
[ "MIT" ]
null
null
null
src/main/java/com/example/chessgame/Pieces/Bishop.java
JuniorZani/ChessGame
8065106ed6ed9644a875fb52913c58f1470825bf
[ "MIT" ]
1
2021-12-09T20:53:37.000Z
2021-12-09T20:53:37.000Z
package com.example.chessgame.Pieces; import com.example.chessgame.Enums.ColorType; import com.example.chessgame.Enums.PieceType; import static com.example.chessgame.Controllers.ChessBoardController.tiles; public class Bishop extends Piece { public Bishop(ColorType color, int row, int column) { super(color, PieceType.BISHOP, row, column); } @Override public boolean canMove(int targetRow, int targetColumn) { int currentRow = getCoordinate().getRow(); int currentColumn = getCoordinate().getColumn(); int j; //Diagonal movement verification if (!(Math.abs(targetRow - currentRow) == Math.abs(targetColumn - currentColumn)) || (this.getCoordinate().getRow() == targetRow && this.getCoordinate().getColumn() == targetColumn)) { return false; } //top diagonals if (currentRow > targetRow) { j = currentColumn; //i-- and j-- if (currentColumn > targetColumn) { j = j - 1; for (int i = currentRow - 1; i > targetRow; i--) { if(j < targetColumn) break; else if (!tiles[i][j].isTileEmpty()) return false; j--; } } else { //i-- and j++ if (currentColumn < targetColumn) { j = j + 1; for (int i = currentRow - 1; i > targetRow; i--) { if(j > targetColumn) break; else if (!tiles[i][j].isTileEmpty()) return false; j++; } } } } else { //bottom diagonals if (currentRow < targetRow) { j = currentColumn; //i++ and j-- if (currentColumn > targetColumn) { j = j - 1; for (int i = currentRow + 1; i < targetRow; i++) { if(j < targetColumn) break; else if (!tiles[i][j].isTileEmpty()) return false; j--; } } else { //i++ and j++ j = j + 1; for (int i = currentRow + 1; i < targetRow; i++) { if (j > targetColumn) break; else { if (!tiles[i][j].isTileEmpty()) return false; j++; } } } } } return true; } }
34.360465
192
0.389509
db22c1bbf147bed467b3d64b69e9b3d877ad7a2c
867
ps1
PowerShell
example-tests/RunTests.ps1
JonnyWideFoot/tyrannosaurus-trx
54a2cf2ce694e9dfd9dd7e4afe037dd388a1b7ad
[ "Apache-2.0" ]
null
null
null
example-tests/RunTests.ps1
JonnyWideFoot/tyrannosaurus-trx
54a2cf2ce694e9dfd9dd7e4afe037dd388a1b7ad
[ "Apache-2.0" ]
2
2021-02-26T10:31:30.000Z
2021-04-30T08:04:06.000Z
example-tests/RunTests.ps1
JonnyWideFoot/tyrannosaurus-trx
54a2cf2ce694e9dfd9dd7e4afe037dd388a1b7ad
[ "Apache-2.0" ]
3
2021-02-26T00:10:25.000Z
2022-01-11T04:06:15.000Z
$dir = $PsScriptRoot $tests = gci "$dir/**/*.Tests.csproj" if($env:TRX_TESTSDIR -ne $null){ $testsDir = $env:TRX_TESTSDIR } else { $testsDir = "$dir/out" } if($env:TRX_TESTSFAILED -ne $null){ $testsFailed = $env:TRX_TESTSFAILED } else { $testsFailed = "$testsDir/failed" } function RunTestProj($absPath) { $name = $absPath.Replace('\ '.Replace(' ', ''), '').Replace('.', '_').Replace('/', '_') write-host ('Running dotnet test for {0} -> {1}' -f $absPath, $name) $fileName = "$name.trx" $filePath = "$testsDir/$fileName" dotnet test $absPath --logger ('trx;LogFileName={0}' -f $filePath) # $dest = ('{0}/{1}' -f $testsDir, $fileName) # cp $fileName $dest if($LASTEXITCODE -ne 0) { out-file -filepath $testsFailed } } gci -Recurse *.csproj |% { RunTestProj (resolve-path -relative $_.FullName) }
26.272727
91
0.595156
861692498413f1695f02cd96d53ddcb78f679a21
1,745
java
Java
core/src/stonering/test_chamber/model/DiggingModel.java
Arael1895/Tearfall
a63d751fb8aaf492cad8a373ca6cbf4bf457b85c
[ "MIT" ]
null
null
null
core/src/stonering/test_chamber/model/DiggingModel.java
Arael1895/Tearfall
a63d751fb8aaf492cad8a373ca6cbf4bf457b85c
[ "MIT" ]
null
null
null
core/src/stonering/test_chamber/model/DiggingModel.java
Arael1895/Tearfall
a63d751fb8aaf492cad8a373ca6cbf4bf457b85c
[ "MIT" ]
null
null
null
package stonering.test_chamber.model; import stonering.entity.item.Item; import stonering.entity.unit.Unit; import stonering.enums.blocks.BlockTypesEnum; import stonering.enums.items.type.ItemTypeMap; import stonering.enums.materials.MaterialMap; import stonering.game.model.EntitySelector; import stonering.game.model.system.items.ItemContainer; import stonering.game.model.system.units.UnitContainer; import stonering.game.model.local_map.LocalMap; import stonering.generators.creatures.CreatureGenerator; import stonering.util.geometry.Position; /** * Model for testing farms. * * @author Alexander_Kuzyakov on 04.07.2019. */ public class DiggingModel extends TestModel { @Override public void init() { super.init(); get(EntitySelector.class).setPosition(MAP_SIZE / 2, MAP_SIZE / 2, 10); get(UnitContainer.class).addUnit(createUnit()); get(ItemContainer.class).addAndPut(createHoe()); } @Override protected void updateLocalMap() { LocalMap localMap = get(LocalMap.class); for (int x = 0; x < localMap.xSize; x++) { for (int y = 0; y < localMap.ySize; y++) { for (int z = 0; z < 10; z++) { localMap.setBlock(x, y, z, BlockTypesEnum.WALL, MaterialMap.instance().getId("soil")); } localMap.setBlock(x, y, 10, BlockTypesEnum.FLOOR, MaterialMap.instance().getId("soil")); } } } private Unit createUnit() { return new CreatureGenerator().generateUnit(new Position(3, 3, 10), "human"); } private Item createHoe() { Item item = new Item(new Position(0, 0, 10), ItemTypeMap.getInstance().getItemType("pickaxe")); return item; } }
34.215686
106
0.665903
e8f011132e8ba4c80c24305ed5651fd0b38079a6
3,411
cpp
C++
src/test/tests/samples/binsearch.cpp
jeroendebaat/lc3tools
b1ceb8bc28a82227ccbd17c90f6b6cfcdf324d41
[ "Apache-2.0" ]
58
2018-07-13T03:41:38.000Z
2022-03-08T19:06:20.000Z
src/test/tests/samples/binsearch.cpp
jeroendebaat/lc3tools
b1ceb8bc28a82227ccbd17c90f6b6cfcdf324d41
[ "Apache-2.0" ]
26
2019-12-02T05:33:00.000Z
2022-03-12T15:54:26.000Z
src/test/tests/samples/binsearch.cpp
jeroendebaat/lc3tools
b1ceb8bc28a82227ccbd17c90f6b6cfcdf324d41
[ "Apache-2.0" ]
24
2019-08-30T15:00:13.000Z
2022-01-26T05:11:36.000Z
/* * Copyright 2020 McGraw-Hill Education. All rights reserved. No reproduction or distribution without the prior written consent of McGraw-Hill Education. */ #define API_VER 2 #include "framework.h" static constexpr uint64_t InstLimit = 5000; struct Node { uint16_t node_addr, str_addr; Node * left, * right; std::string name; uint16_t income; Node(uint16_t node_addr, uint16_t str_addr, Node * left, Node * right, std::string const & name, uint16_t income) : node_addr(node_addr), str_addr(str_addr), left(left), right(right), name(name), income(income) {} }; void fillMem(lc3::sim & sim, Node * root) { sim.writeMem(root->node_addr + 2, root->str_addr); sim.writeStringMem(root->str_addr, root->name); sim.writeMem(root->node_addr + 3, root->income); if(root->left != nullptr) { sim.writeMem(root->node_addr, root->left->node_addr); fillMem(sim, root->left); } else { sim.writeMem(root->node_addr, 0); } if(root->right != nullptr) { sim.writeMem(root->node_addr + 1, root->right->node_addr); fillMem(sim, root->right); } else { sim.writeMem(root->node_addr + 1, 0); } } std::ostream & operator<<(std::ostream & out, std::vector<char> const & data) { for(char c : data) { out << c; } return out; } void OneTest(lc3::sim & sim, Tester & tester, double total_points) { Node ali{0x4009, 0x5000, nullptr, nullptr, "Ali", 18000}; Node dan{0x400d, 0x5004, nullptr, nullptr, "Dan", 16000}; Node daniel{0x4005, 0x5008, nullptr, &ali, "Daniel", 24000}; Node joe{0x4001, 0x500f, &daniel, &dan, "Joe", 20000}; fillMem(sim, &joe); sim.writeMem(0x4000, joe.node_addr); bool success = true; success &= sim.runUntilInputRequested(); bool correct = tester.checkMatch(tester.getOutput(), "Type a professor's name and then press enter:"); tester.verify("Correct", success && correct, total_points / 5); tester.clearOutput(); tester.setInputString("Dan\n"); success &= sim.runUntilInputRequested(); correct = tester.checkContain(tester.getOutput(), "16000"); tester.verify("Dan", success && correct, total_points / 5); tester.clearOutput(); tester.setInputString("Dani\n"); success &= sim.runUntilInputRequested(); correct = tester.checkContain(tester.getOutput(), "No Entry"); tester.verify("Dani", success && correct, total_points / 5); tester.clearOutput(); tester.setInputString("Daniel\n"); success &= sim.runUntilInputRequested(); correct = tester.checkContain(tester.getOutput(), "24000"); tester.verify("Daniel", success && correct, total_points / 5); tester.clearOutput(); tester.setInputString("dan\n"); success &= sim.runUntilInputRequested(); correct = tester.checkContain(tester.getOutput(), "No Entry"); tester.verify("dan", success && correct, total_points / 5); tester.clearOutput(); tester.setInputString("d\n"); success &= sim.runUntilHalt(); tester.verify("Exit", success && ! sim.didExceedInstLimit(), 0); } void testBringup(lc3::sim & sim) { sim.writePC(0x3000); sim.setRunInstLimit(InstLimit); } void testTeardown(lc3::sim & sim) { (void) sim; } void setup(Tester & tester) { tester.registerTest("One", OneTest, 60, false); tester.registerTest("One", OneTest, 40, true); } void shutdown(void) {}
31.009091
153
0.657872
4e173b48aae3eac0e1d8fe9b5dd4098f7d3e6792
503
ps1
PowerShell
profile/restart-powershell-ses.ps1
insyri/powershell-scripts
5785a2196ec2b73aacea1c94ccc474a7dac4ce5f
[ "MIT" ]
1
2021-08-25T13:24:26.000Z
2021-08-25T13:24:26.000Z
profile/restart-powershell-ses.ps1
insyri/powershell-scripts
5785a2196ec2b73aacea1c94ccc474a7dac4ce5f
[ "MIT" ]
null
null
null
profile/restart-powershell-ses.ps1
insyri/powershell-scripts
5785a2196ec2b73aacea1c94ccc474a7dac4ce5f
[ "MIT" ]
null
null
null
# This script is a custom function to "restart" a powershell session by creating a new session and exiting the old session. # https://stackoverflow.com/a/42040185 function Restart-PowerShell{ Start-Process PowerShell # Launch PowerShell host in new window exit # Exit existing PowerShell host window } # Add any alias if you want, for ex. rps (rp already occupied by "Remove-ItemProperty”) Set-Alias -Name "rps" -Value "Restart-PowerShell" Set-Alias -Name "restart" -Value "Restart-PowerShell"
45.727273
123
0.765408
80350c1f0fc55eefd5c8beff31f672b0738e6fb7
8,217
java
Java
src/main/java/com/rymcu/forest/lucene/api/LuceneSearchController.java
acaterpillar/forest
d6904d84d123421884e628e8231e63492b733e6b
[ "MIT" ]
5
2021-01-25T09:02:31.000Z
2022-03-04T09:11:24.000Z
src/main/java/com/rymcu/forest/lucene/api/LuceneSearchController.java
acaterpillar/forest
d6904d84d123421884e628e8231e63492b733e6b
[ "MIT" ]
16
2021-01-25T09:13:47.000Z
2022-01-08T13:27:43.000Z
src/main/java/com/rymcu/forest/lucene/api/LuceneSearchController.java
acaterpillar/forest
d6904d84d123421884e628e8231e63492b733e6b
[ "MIT" ]
7
2021-01-26T00:32:14.000Z
2022-01-27T06:02:55.000Z
package com.rymcu.forest.lucene.api; import com.github.pagehelper.Page; import com.github.pagehelper.PageInfo; import com.rymcu.forest.core.result.GlobalResult; import com.rymcu.forest.core.result.GlobalResultGenerator; import com.rymcu.forest.dto.ArticleDTO; import com.rymcu.forest.dto.PortfolioDTO; import com.rymcu.forest.dto.UserDTO; import com.rymcu.forest.lucene.model.ArticleLucene; import com.rymcu.forest.lucene.model.PortfolioLucene; import com.rymcu.forest.lucene.model.UserLucene; import com.rymcu.forest.lucene.service.LuceneService; import com.rymcu.forest.lucene.service.PortfolioLuceneService; import com.rymcu.forest.lucene.service.UserDicService; import com.rymcu.forest.lucene.service.UserLuceneService; import com.rymcu.forest.lucene.util.ArticleIndexUtil; import com.rymcu.forest.lucene.util.PortfolioIndexUtil; import com.rymcu.forest.lucene.util.UserIndexUtil; import com.rymcu.forest.util.Utils; import org.springframework.web.bind.annotation.*; import javax.annotation.PostConstruct; import javax.annotation.Resource; import java.io.FileNotFoundException; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * LuceneSearchController * * @author suwen * @date 2021/2/3 10:41 */ @RestController @RequestMapping("/api/v1/lucene") public class LuceneSearchController { @Resource private LuceneService luceneService; @Resource private UserLuceneService userLuceneService; @Resource private PortfolioLuceneService portfolioLuceneService; @Resource private UserDicService dicService; @PostConstruct public void createIndex() { // 删除系统运行时保存的索引,重新创建索引 ArticleIndexUtil.deleteAllIndex(); UserIndexUtil.deleteAllIndex(); PortfolioIndexUtil.deleteAllIndex(); ExecutorService executor = Executors.newSingleThreadExecutor(); CompletableFuture<String> future = CompletableFuture.supplyAsync( () -> { System.out.println(">>>>>>>>> 开始创建索引 <<<<<<<<<<<"); luceneService.writeArticle(luceneService.getAllArticleLucene()); userLuceneService.writeUser(userLuceneService.getAllUserLucene()); portfolioLuceneService.writePortfolio(portfolioLuceneService.getAllPortfolioLucene()); System.out.println(">>>>>>>>> 索引创建完毕 <<<<<<<<<<<"); System.out.println("加载用户配置的自定义扩展词典到主词库表"); try { System.out.println(">>>>>>>>> 开始加载用户词典 <<<<<<<<<<<"); dicService.writeUserDic(); } catch (FileNotFoundException e) { System.out.println("加载用户词典失败,未成功创建用户词典"); } return ">>>>>>>>> 加载用户词典完毕 <<<<<<<<<<<"; }, executor); future.thenAccept(System.out::println); } /** * 文章搜索,实现高亮 * * @param q * @return */ @GetMapping("/search-article") public GlobalResult<?> searchArticle( @RequestParam String q, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer rows) { // 找出相关文章,相关度倒序 List<ArticleLucene> resList = luceneService.searchArticle(q); // 分页组装文章详情 int total = resList.size(); if (total == 0) { return GlobalResultGenerator.genSuccessResult("未找到相关文章"); } Page<ArticleDTO> articles = new Page<>(page, rows); articles.setTotal(total); int startIndex = (page - 1) * rows; int endIndex = Math.min(startIndex + rows, total); // 分割子列表 List<ArticleLucene> subList = resList.subList(startIndex, endIndex); String[] ids = subList.stream().map(ArticleLucene::getIdArticle).toArray(String[]::new); List<ArticleDTO> articleDTOList = luceneService.getArticlesByIds(ids); ArticleDTO temp; // 写入文章关键词信息 for (int i = 0; i < articleDTOList.size(); i++) { temp = articleDTOList.get(i); temp.setArticleTitle(subList.get(i).getArticleTitle()); if (subList.get(i).getArticleContent().length() > 10) { // 内容中命中太少则不替换 temp.setArticlePreviewContent(subList.get(i).getArticleContent()); } articleDTOList.set(i, temp); } articles.addAll(articleDTOList); PageInfo<ArticleDTO> pageInfo = new PageInfo<>(articles); return GlobalResultGenerator.genSuccessResult(Utils.getArticlesGlobalResult(pageInfo)); } /** * 用户搜索,实现高亮 * * @param q * @return */ @GetMapping("/search-user") public GlobalResult<?> searchUser( @RequestParam String q, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer rows) { // 找出相关文章,相关度倒序 List<UserLucene> resList = userLuceneService.searchUser(q); // 分页组装文章详情 int total = resList.size(); if (total == 0) { return GlobalResultGenerator.genSuccessResult("未找到相关用户"); } Page<UserDTO> users = new Page<>(page, rows); users.setTotal(total); int startIndex = (page - 1) * rows; int endIndex = Math.min(startIndex + rows, total); // 分割子列表 List<UserLucene> subList = resList.subList(startIndex, endIndex); Integer[] ids = subList.stream().map(UserLucene::getIdUser).toArray(Integer[]::new); List<UserDTO> userDTOList = userLuceneService.getUsersByIds(ids); UserDTO temp; // 写入文章关键词信息 for (int i = 0; i < userDTOList.size(); i++) { temp = userDTOList.get(i); temp.setNickname(subList.get(i).getNickname()); if (subList.get(i).getSignature().length() > 10) { // 内容中命中太少则不替换 temp.setSignature(subList.get(i).getSignature()); } userDTOList.set(i, temp); } users.addAll(userDTOList); PageInfo<UserDTO> pageInfo = new PageInfo<>(users); return GlobalResultGenerator.genSuccessResult(Utils.getUserGlobalResult(pageInfo)); } /** * 作品集搜索,实现高亮 * * @param q * @return */ @GetMapping("/search-portfolio") public GlobalResult<?> searchPortfolio( @RequestParam String q, @RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer rows) { // 找出相关文章,相关度倒序 List<PortfolioLucene> resList = portfolioLuceneService.searchPortfolio(q); // 分页组装文章详情 int total = resList.size(); if (total == 0) { return GlobalResultGenerator.genSuccessResult("未找到相关作品集"); } Page<PortfolioDTO> portfolios = new Page<>(page, rows); portfolios.setTotal(total); int startIndex = (page - 1) * rows; int endIndex = Math.min(startIndex + rows, total); // 分割子列表 List<PortfolioLucene> subList = resList.subList(startIndex, endIndex); String[] ids = subList.stream().map(PortfolioLucene::getIdPortfolio).toArray(String[]::new); List<PortfolioDTO> portfolioDTOList = portfolioLuceneService.getPortfoliosByIds(ids); PortfolioDTO temp; // 写入文章关键词信息 for (int i = 0; i < portfolioDTOList.size(); i++) { temp = portfolioDTOList.get(i); temp.setPortfolioTitle(subList.get(i).getPortfolioTitle()); if (subList.get(i).getPortfolioDescription().length() > 10) { // 内容中命中太少则不替换 temp.setPortfolioDescription(subList.get(i).getPortfolioDescription()); } portfolioDTOList.set(i, temp); } portfolios.addAll(portfolioDTOList); PageInfo<PortfolioDTO> pageInfo = new PageInfo<>(portfolios); return GlobalResultGenerator.genSuccessResult(Utils.getPortfolioGlobalResult(pageInfo)); } }
40.279412
114
0.617744
c5fa159f255880c14e8604c192064c77e57b2e79
2,511
hpp
C++
deps/boost/include/boost/contract/detail/type_traits/member_function_types.hpp
kindlychung/mediasoup-sfu-cpp
f69d2f48f7edbf4f0c57244280a47bea985f39cf
[ "Apache-2.0" ]
995
2018-06-22T10:39:18.000Z
2022-03-25T01:22:14.000Z
deps/boost/include/boost/contract/detail/type_traits/member_function_types.hpp
kindlychung/mediasoup-sfu-cpp
f69d2f48f7edbf4f0c57244280a47bea985f39cf
[ "Apache-2.0" ]
32
2018-06-23T14:19:37.000Z
2022-03-29T10:20:37.000Z
deps/boost/include/boost/contract/detail/type_traits/member_function_types.hpp
kindlychung/mediasoup-sfu-cpp
f69d2f48f7edbf4f0c57244280a47bea985f39cf
[ "Apache-2.0" ]
172
2018-06-22T11:12:00.000Z
2022-03-29T07:44:33.000Z
#ifndef BOOST_CONTRACT_DETAIL_MEMBER_FUNCTION_TYPES_HPP_ #define BOOST_CONTRACT_DETAIL_MEMBER_FUNCTION_TYPES_HPP_ // Copyright (C) 2008-2018 Lorenzo Caminiti // Distributed under the Boost Software License, Version 1.0 (see accompanying // file LICENSE_1_0.txt or a copy at http://www.boost.org/LICENSE_1_0.txt). // See: http://www.boost.org/doc/libs/release/libs/contract/doc/html/index.html #include <boost/contract/detail/none.hpp> #include <boost/function_types/parameter_types.hpp> #include <boost/function_types/result_type.hpp> #include <boost/function_types/property_tags.hpp> #include <boost/type_traits/is_const.hpp> #include <boost/type_traits/is_volatile.hpp> #include <boost/type_traits/is_same.hpp> #include <boost/mpl/pop_front.hpp> #include <boost/mpl/push_back.hpp> #include <boost/mpl/back.hpp> #include <boost/mpl/and.hpp> #include <boost/mpl/if.hpp> #include <boost/mpl/identity.hpp> namespace boost { namespace contract { class virtual_; } } namespace boost { namespace contract { namespace detail { template<class C, typename F> struct member_function_types { typedef typename boost::function_types::result_type<F>::type result_type; // Never include leading class type. typedef typename boost::mpl::pop_front<typename boost::function_types:: parameter_types<F>::type>::type argument_types; // Always include trailing virtual_* type. typedef typename boost::mpl::if_<boost::is_same<typename boost:: mpl::back<argument_types>::type, boost::contract::virtual_*>, boost::mpl::identity<argument_types> , boost::mpl::push_back<argument_types, boost::contract::virtual_*> >::type::type virtual_argument_types; typedef typename boost::mpl::if_<boost::mpl::and_<boost::is_const<C>, boost::is_volatile<C> >, boost::function_types::cv_qualified , typename boost::mpl::if_<boost::is_const<C>, boost::function_types::const_non_volatile , typename boost::mpl::if_<boost::is_volatile<C>, boost::function_types::volatile_non_const , boost::function_types::null_tag >::type>::type>::type property_tag; }; // Also handles none type. template<class C> struct member_function_types<C, none> { typedef none result_type; typedef none argument_types; typedef none virtual_argument_types; typedef none property_tag; }; } } } // namespace #endif // #include guard
34.39726
80
0.709677
b0816e56366cf2b2e24d3d3fab0451504117c960
2,958
html
HTML
index.html
lukespeers/lukespeers.github.io_0
1c642c3c4e29e1e08b1cc59404dd4c7b66a41a4c
[ "CC-BY-3.0" ]
null
null
null
index.html
lukespeers/lukespeers.github.io_0
1c642c3c4e29e1e08b1cc59404dd4c7b66a41a4c
[ "CC-BY-3.0" ]
null
null
null
index.html
lukespeers/lukespeers.github.io_0
1c642c3c4e29e1e08b1cc59404dd4c7b66a41a4c
[ "CC-BY-3.0" ]
null
null
null
<!DOCTYPE HTML> <!-- Identity by HTML5 UP html5up.net | @ajlkn Free for personal and commercial use under the CCA 3.0 license (html5up.net/license) --> <html> <head> <title>Luke Speers</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" /> <link rel="stylesheet" href="assets/css/main.css" /> <noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript> </head> <body class="is-preload"> <!-- Wrapper --> <div id="wrapper"> <!-- Main --> <section id="main"> <header> <span class="avatar"><img src="images/lisa_luke_bw_small.jpg" alt="" /></span> <h1>Luke Speers</h1> <p>Musician, Developer, Entrepreneur</p> <p>Welcome to my personal page.</p> </header> <ul id="myUL"> <li><span class="caret">Uxbridge Ontario Bands</span> <ul class="nested"> <li><a onclick=" window.open('https://www.benhudsonmusic.com/', '_blank'); return false;">Ben Hudson</a></li> <li><a onclick=" window.open('https://www.leahdaniels.com/', '_blank'); return false;">Leah Daniels</a></li> <li><a onclick=" window.open('https://www.robynottolini.com/', '_blank'); return false;">Robyn Ottolini</a></li> <li><a onclick=" window.open('https://orangabang.com/', '_blank'); return false;">Orangabang</a></li> <li><a onclick=" window.open('https://www.facebook.com/eightfivetwoband/', '_blank'); return false;">852</a></li> <li><a onclick=" window.open('https://soundcloud.com/1985rules/', '_blank'); return false;">1985</a></li> </ul> </li> <li><span class="caret">Uxbridge Musical Events</span> <ul class="nested"> <li><a onclick=" window.open('https://springtidemusicfestival.com/', '_blank'); return false;">Spring Tide</a></li> <li><a onclick=" window.open('https://www.hitsfest.com/', '_blank'); return false;">Hits Fest</a></li> </ul> </li> </ul> </li> </ul> </ul> </section> <!-- Footer --> <footer id="footer"> <ul class="copyright"> <li>&copy; Luke Speers</li><li>Design: <a href="http://html5up.net">HTML5 UP</a></li> </ul> </footer> </div> <!-- Scripts --> <script> if ('addEventListener' in window) { window.addEventListener('load', function() { document.body.className = document.body.className.replace(/\bis-preload\b/, ''); }); document.body.className += (navigator.userAgent.match(/(MSIE|rv:11\.0)/) ? ' is-ie' : ''); } var toggler = document.getElementsByClassName("caret"); var i; for (i = 0; i < toggler.length; i++) { toggler[i].addEventListener("click", function() { this.parentElement.querySelector(".nested").classList.toggle("active"); this.classList.toggle("caret-down"); }); } </script> </body> </html>
34.395349
134
0.585869
a96a761ab37a0b4bf0933c862701b04fe459d1e2
5,816
dart
Dart
lib/Row/description.dart
grevity/Flutter-Gallery-Ultimate
2fa341a25a986df9834af4651b3dcfca27ec3734
[ "MIT" ]
2
2020-09-23T21:21:54.000Z
2021-05-25T13:38:35.000Z
lib/Row/description.dart
flutter-bharat/Flutter-Gallery-Ultimate
2fa341a25a986df9834af4651b3dcfca27ec3734
[ "MIT" ]
9
2020-08-07T09:07:36.000Z
2021-05-26T01:44:38.000Z
lib/Row/description.dart
grevity/Flutter-Gallery-Ultimate
2fa341a25a986df9834af4651b3dcfca27ec3734
[ "MIT" ]
5
2020-06-10T07:43:34.000Z
2020-08-07T06:14:46.000Z
import 'package:flutter/material.dart'; import 'package:flutter_gallery_ultimate/utils/DataFile.dart'; import 'package:flutter_highlight/flutter_highlight.dart'; import 'package:flutter_highlight/themes/googlecode.dart'; class RowDescription extends StatelessWidget { @override Widget build(BuildContext context) { var code; Column( children: [ HighlightView( code = '''Row( children: <Widget>[ Expanded( child: Text('Deliver features faster', textAlign: TextAlign.center), ), Expanded( child: Text('Craft beautiful UIs', textAlign: TextAlign.center), ), Expanded( child: FittedBox( fit: BoxFit.contain, // otherwise the logo will be tiny child: const FlutterLogo(), ), ), ], ) ''' ), ], ); return Scaffold( appBar: customizedAppBar("Description"), body: ListView( children: [ Padding( padding: const EdgeInsets.all( 15.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( // padding: EdgeInsets.symmetric(horizontal: 50.0), child: Text("Row",style: TextStyle(fontSize: 20.0,fontWeight: FontWeight.bold))), SizedBox(height: 30.0), Container( // padding: EdgeInsets.symmetric(horizontal: 16.0), child: Column( children: [ Text(" A widget that displays its children in a horizontal array.To cause a child to " "expand to fill the available horizontal space, wrap the child in an Expanded " "widget",style: TextStyle(fontSize: 15,),), SizedBox(height: 10.0,), Text(" The Row widget does not scroll (and in general it is considered an error to have more children in a Row than will fit in the available room). " "If you have a line of widgets and want them to be able to scroll if there is insufficient room, consider using " "a ListView.",style: TextStyle(fontSize: 15),), ], ), ), SizedBox(height: 30.0), Text("Demo Code",style: TextStyle(fontSize: 20.0,fontWeight: FontWeight.bold)), SizedBox(height: 20.0), Container( height: 400, width: 370, child: Card( shadowColor: Colors.grey, elevation: 15, child: ListView( children: [ HighlightView( // The original code to be highlighted code, // Specify language // It is recommended to give it a value for performance language: 'dart', // Specify highlight theme // All available themes are listed in `themes` folder theme: googlecodeTheme , // Specify padding padding: EdgeInsets.all(12), // Specify text style textStyle: TextStyle( fontFamily: 'My awesome monospace font', fontSize: 16, ), ), ], ), ), ), SizedBox(height: 40.0), Text("Related Widgets",style: TextStyle(fontSize: 20.0,fontWeight: FontWeight.bold),), SizedBox(height: 20.0), Container( // padding: EdgeInsets.symmetric(horizontal: 15.0,vertical: 20.0), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text("Column",style: TextStyle(color: Colors.blue,fontSize: 17),), SizedBox(height: 5.0), Text("For a vertical equivalent.",style: TextStyle(fontSize: 15),), SizedBox(height: 20.0), Text("Flex",style: TextStyle(color: Colors.blue,fontSize: 17),), SizedBox(height: 5.0), Text("If you don't know in advance if you want a horizontal or vertical arrangement.",style: TextStyle(fontSize: 15),), SizedBox(height: 20.0), Text("Expanded",style: TextStyle(color: Colors.blue,fontSize: 17),), SizedBox(height: 5.0), Text("To indicate children that should take all the remaining room.",style: TextStyle(fontSize: 15),), SizedBox(height: 20.0), Text("Flexibal",style: TextStyle(color: Colors.blue,fontSize: 17),), SizedBox(height: 5.0), Text("To indicate children that should share the remaining room but that may by sized smaller (leaving some remaining room unused).",style: TextStyle(fontSize: 15),), SizedBox(height: 20.0), Text("Spacer",style: TextStyle(color: Colors.blue,fontSize: 17),), SizedBox(height: 5.0), Text("A widget that takes up space proportional to it's flex value..",style: TextStyle(fontSize: 15),), ], ), ), ], ), ), ], ), ); } }
43.081481
188
0.486761
aa84abcc681b9fe2d65ad8f95a916322ce3debe5
1,244
dart
Dart
lib/api/speech_api.dart
ElouadiAbdelati/walk-alone-app-mobile
c2d39e4d5539c7f9c66662416a4127ef2ca2924d
[ "MIT" ]
null
null
null
lib/api/speech_api.dart
ElouadiAbdelati/walk-alone-app-mobile
c2d39e4d5539c7f9c66662416a4127ef2ca2924d
[ "MIT" ]
null
null
null
lib/api/speech_api.dart
ElouadiAbdelati/walk-alone-app-mobile
c2d39e4d5539c7f9c66662416a4127ef2ca2924d
[ "MIT" ]
null
null
null
import 'dart:developer'; import 'package:flutter/cupertino.dart'; import 'package:speech_to_text/speech_to_text.dart'; import 'package:flutter_tts/flutter_tts.dart'; class SpeechApi { static final _speech = SpeechToText(); static final _flutterTts = FlutterTts(); static Future<bool> toggleRecording({ @required Function(String text) onResult, @required ValueChanged<bool> onListening, }) async { if (_speech.isListening) { _speech.stop(); return true; } final isAvailable = await _speech.initialize( onStatus: (status) => onListening(_speech.isListening), onError: (e) => print('Error: $e'), ); if (isAvailable) { _speech.listen(onResult: (value) => onResult(value.recognizedWords)); } return isAvailable; } static void textTospeech({ @required String text, @required ValueChanged<bool> onResult, }) async { if (text != null && text.isNotEmpty) { await _flutterTts.setLanguage('fr-FR'); await _flutterTts.setSpeechRate(1.0); await _flutterTts.setPitch(1.0); _flutterTts.setCompletionHandler(() { bool isFinishing = true; onResult(isFinishing); }); await _flutterTts.speak(text); } } }
25.387755
75
0.663183
72ba0e77e8229e1f50ab1596fe955ed12ea9c82c
3,428
dart
Dart
lib/app/config/injectable.config.dart
jorgesarabia/flutter_quotes
74c8841ac2b4c0cbd3bbb48fdb30a87f8cdc7a12
[ "MIT" ]
null
null
null
lib/app/config/injectable.config.dart
jorgesarabia/flutter_quotes
74c8841ac2b4c0cbd3bbb48fdb30a87f8cdc7a12
[ "MIT" ]
null
null
null
lib/app/config/injectable.config.dart
jorgesarabia/flutter_quotes
74c8841ac2b4c0cbd3bbb48fdb30a87f8cdc7a12
[ "MIT" ]
null
null
null
// GENERATED CODE - DO NOT MODIFY BY HAND // ************************************************************************** // InjectableConfigGenerator // ************************************************************************** import 'package:get_it/get_it.dart' as _i1; import 'package:injectable/injectable.dart' as _i2; import 'package:local_auth/local_auth.dart' as _i8; import 'package:shared_preferences/shared_preferences.dart' as _i9; import 'package:stokkur_api_client/stokkur_api_client.dart' as _i3; import '../../auth/application/auth/auth_bloc.dart' as _i24; import '../../auth/application/login/login_bloc.dart' as _i23; import '../../auth/domain/i_auth_api.dart' as _i4; import '../../auth/domain/i_auth_facade.dart' as _i21; import '../../auth/domain/i_biometrics.dart' as _i10; import '../../auth/infrastructure/auth_api.dart' as _i5; import '../../auth/infrastructure/auth_repository.dart' as _i22; import '../../auth/infrastructure/biometrics_repository.dart' as _i11; import '../../quotes/application/quotes_bloc.dart' as _i20; import '../../quotes/domain/i_local_quotes.dart' as _i12; import '../../quotes/domain/i_quotes_api.dart' as _i16; import '../../quotes/domain/i_quotes_endpoints.dart' as _i6; import '../../quotes/domain/i_quotes_facade.dart' as _i18; import '../../quotes/infrastructure/local_quotes.dart' as _i13; import '../../quotes/infrastructure/quotes_api.dart' as _i17; import '../../quotes/infrastructure/quotes_endpoints.dart' as _i7; import '../../quotes/infrastructure/quotes_repository.dart' as _i19; import '../domain/i_local_storage_facade.dart' as _i14; import '../infrastructure/local_storage.dart' as _i15; import 'modules.dart' as _i25; // ignore_for_file: unnecessary_lambdas // ignore_for_file: lines_longer_than_80_chars /// initializes the registration of provided dependencies inside of [GetIt] Future<_i1.GetIt> $initGetIt(_i1.GetIt get, {String? environment, _i2.EnvironmentFilter? environmentFilter}) async { final gh = _i2.GetItHelper(get, environment, environmentFilter); final registerModule = _$RegisterModule(); gh.factory<_i3.ApiClient>(() => registerModule.client); gh.factory<_i4.IAuthApi>(() => _i5.AuthApi()); gh.factory<_i6.IQuotesEndpoints>(() => _i7.QuotesEndpoints()); gh.factory<_i8.LocalAuthentication>(() => registerModule.localAuthentication); await gh.factoryAsync<_i9.SharedPreferences>(() => registerModule.prefs, preResolve: true); gh.factory<_i10.IBiometrics>( () => _i11.BiometricsRepository(get<_i8.LocalAuthentication>())); gh.factory<_i12.ILocalQuotes>( () => _i13.LocalQuotes(get<_i9.SharedPreferences>())); gh.factory<_i14.ILocalStorageFacade>( () => _i15.LocalStorage(get<_i9.SharedPreferences>())); gh.factory<_i16.IQuotesApi>( () => _i17.QuoteApi(get<_i3.ApiClient>(), get<_i6.IQuotesEndpoints>())); gh.factory<_i18.IQuotesFacade>(() => _i19.QuoteRepository(get<_i12.ILocalQuotes>(), get<_i16.IQuotesApi>())); gh.factory<_i20.QuotesBloc>(() => _i20.QuotesBloc(get<_i18.IQuotesFacade>())); gh.factory<_i21.IAuthFacade>(() => _i22.AuthRepository( get<_i14.ILocalStorageFacade>(), get<_i4.IAuthApi>(), get<_i10.IBiometrics>())); gh.factory<_i23.LoginBloc>(() => _i23.LoginBloc(get<_i21.IAuthFacade>())); gh.factory<_i24.AuthBloc>(() => _i24.AuthBloc(get<_i21.IAuthFacade>())); return get; } class _$RegisterModule extends _i25.RegisterModule {}
51.164179
80
0.700408
c58681ae562c3e8d44b51780b0372872c21ab189
4,704
cpp
C++
src/struct/SxStickyFilter.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
1
2020-02-29T03:26:32.000Z
2020-02-29T03:26:32.000Z
src/struct/SxStickyFilter.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
src/struct/SxStickyFilter.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
// --------------------------------------------------------------------------- // // The ab-initio based multiscale library // // S / P H I / n X // // Copyright: Max-Planck-Institute for Iron Research // 40237 Duesseldorf, Germany // // Contact: https://sxlib.mpie.de // Authors: see sphinx/AUTHORS // License: see sphinx/LICENSE // // --------------------------------------------------------------------------- #include <SxStickyFilter.h> #include <SxList.h> SxStickyFilter::SxStickyFilter () { // empty } SxStickyFilter::SxStickyFilter (const SxSymbolTable *structGroup) { SxList<SxVector3<Int> > stickyList; bool movableX, movableY, movableZ; SxSymbolTable *speciesGroup, *atomGroup; bool anyMovable = false; try { for (speciesGroup = structGroup->getGroup("species"); speciesGroup != NULL; speciesGroup = speciesGroup->nextSibling ("species")) { for (atomGroup = speciesGroup->getGroup("atom"); atomGroup != NULL; atomGroup = atomGroup->nextSibling("atom")) { movableX = movableY = movableZ = false; if (atomGroup->contains ("movable")) { movableX = atomGroup->get("movable")->toAttribute(); movableY = movableZ = movableX; anyMovable = true; } if ( atomGroup->contains ("movableX")) { movableX = atomGroup->get("movableX")->toAttribute(); anyMovable = true; } if ( atomGroup->contains ("movableY")) { movableY = atomGroup->get("movableY")->toAttribute(); anyMovable = true; } if ( atomGroup->contains ("movableZ")) { movableZ = atomGroup->get("movableZ")->toAttribute(); anyMovable = true; } stickyList << SxVector3<Int> (movableX, movableY, movableZ); } } } catch (SxException e) { e.print (); SX_EXIT; } sticky = stickyList; if (!anyMovable) { // if no movable specified, make all atoms movable sticky.set (SxVector3<Int> (true, true, true)); } } SxStickyFilter::~SxStickyFilter () { // empty } SxVector<TPrecTauR> SxStickyFilter::operator* (const SxVector<TPrecTauR> &in) const { SX_CHECK (in.getSize() == 3*sticky.getSize(), in.getSize(), sticky.getSize()); ssize_t nAtoms = sticky.getSize(); SxVector<TPrecTauR> res(3 * nAtoms); ssize_t i, d, iDoF; for (i=0,iDoF=0; i < nAtoms; i++) { for (d=0; d < 3; d++, iDoF++) { // sticky == 0 => coordinate is fixed res(iDoF) = sticky(i)(d) ? in(iDoF) : 0.; } } return res; } SxAtomicStructure SxStickyFilter::operator* (const SxAtomicStructure &str) const { SxAtomicStructure res; res.cell = str.cell; res.atomInfo = str.atomInfo; res.set ((*this * str.coords).reshape (3, str.getNAtoms ())); return res; } void SxStickyFilter::validate (const SymMat &S, const SxVector<Int> &equivalentIdx) { ssize_t n = sticky.getSize (); SX_CHECK (n == equivalentIdx.getSize(), n, equivalentIdx.getSize() ); for (ssize_t i = 0; i < 3; ++i) { for (ssize_t j = 0; j < 3; ++j) { // don't check coordinates that are not intermixed if (fabs(S(j,i)) < 1e-7) continue; for (ssize_t ia = 0; ia < n; ia++) { if ((bool)sticky(ia)(i) != (bool)sticky(equivalentIdx(ia))(j)) { cout << "Stickyness validation error" << endl; SxString xyz("xyz"); int ja = equivalentIdx(ia); if ( sticky(ia)(0) != sticky(ia)(1) || sticky(ia)(0) != sticky(ia)(2)) { cout << xyz(i) << "-coordinate of "; } cout << "atom " << (ia + 1) << " is " << (sticky(ia)(i) ? "fixed" : "movable") << ", but" << endl; if ( sticky(ja)(0) != sticky(ja)(1) || sticky(ja)(0) != sticky(ja)(2)) { cout << xyz(j) << "-coordinate of "; } cout << "atom " << (ja + 1) << " is " << (sticky(ja)(j) ? "fixed" : "movable") << ".\n"; cout << "Symmetry equivalent " << ((ia != ja) ? "atoms" : "directions") << " should have the same stickyness." << endl; cout << "Please adjust the \"movable\" flags in the structure " "group.\n"; SX_QUIT; } } } } }
31.152318
80
0.487457
d4d4f7810feaac86f329a5f766c30384525b656c
13,265
rs
Rust
cruncher_api/src/parser.rs
Tristansmiller/Cruncher
f3a669187dcef65bed02db6cd4f2fc4d8e5ef439
[ "MIT" ]
1
2021-09-03T01:38:02.000Z
2021-09-03T01:38:02.000Z
cruncher_api/src/parser.rs
Tristansmiller/Cruncher
f3a669187dcef65bed02db6cd4f2fc4d8e5ef439
[ "MIT" ]
null
null
null
cruncher_api/src/parser.rs
Tristansmiller/Cruncher
f3a669187dcef65bed02db6cd4f2fc4d8e5ef439
[ "MIT" ]
null
null
null
use serde::{Deserialize, Serialize}; use serde_json::Result; use std::collections::HashMap; use std::fs; use std::sync::Arc; use std::thread; //TODO: Integrate this into the API by making a Manual trigger via web request w/ secret key #[derive(Deserialize)] struct StockInfo { stocks: Vec<Stock>, } #[derive(Deserialize)] struct Stock { ticker: Option<String>, short_description: Option<String>, long_description: Option<String>, name: Option<String>, sic: Option<String>, legal_name: Option<String>, stock_exchange: Option<String>, } #[derive(Serialize)] struct TokenCountedStockInfo { stocks: Vec<TokenCountedStock>, } #[derive(Serialize)] struct TokenCountedStock { ticker: String, name: String, legal_name: String, sic: String, stock_exchange: String, token_count: HashMap<String, u32>, } pub fn generate_token_counted_stock_file(filename: String) -> Result<()> { println!("Deserializing json for preprocessing"); let stock_info: StockInfo = parse_stocks_from_json(filename); println!("Generating token count dictionary"); let token_counted_stock_info: TokenCountedStockInfo = count_tokens(stock_info); println!("Writing preprocessed json to file"); write_token_counted_stocks_to_file(token_counted_stock_info); Ok(()) } fn write_token_counted_stocks_to_file(token_counted_stock_info: TokenCountedStockInfo) { let string_stocks = serde_json::to_string(&token_counted_stock_info) .expect("Failed to serialize token counted stocks"); let new_filename = String::from("TokenCountedStocks.json"); fs::write(new_filename, string_stocks).expect("Failed to write to new token counted file"); } fn parse_stocks_from_json(filename: String) -> StockInfo { let raw_json_string: String = fs::read_to_string(filename).expect("Something went wrong reading the file"); let stock_vector: Vec<Stock> = serde_json::from_str(&raw_json_string).expect("Could not parse file"); StockInfo { stocks: stock_vector, } } fn count_tokens(stock_info: StockInfo) -> TokenCountedStockInfo { let mut token_counted_stocks: Vec<TokenCountedStock> = Vec::new(); let thread_count = 16; //TODO: Pull this in dynamically - just use number of cores let mut thread_pool: Vec<thread::JoinHandle<Vec<TokenCountedStock>>> = Vec::new(); let sharable_stock_info: Arc<StockInfo> = Arc::new(stock_info); for index in 0..thread_count { let skip_index = (sharable_stock_info.stocks.len() / thread_count) * index; let sharable_stock_info: Arc<StockInfo> = Arc::clone(&sharable_stock_info); let join_handle = thread::spawn(move || { let stock_info_thread_chunk = sharable_stock_info .stocks .iter() .skip(skip_index) .take(sharable_stock_info.stocks.len() / thread_count); let mut token_counted_batch: Vec<TokenCountedStock> = Vec::new(); for stock in stock_info_thread_chunk { let token_map: HashMap<String, u32> = HashMap::new(); if let Some(description) = &stock.long_description { if description.to_ascii_lowercase().trim() != "n/a" { token_counted_batch.push(generate_token_counted_stock( &description.to_ascii_lowercase(), token_map, stock, )); } } else if let Some(description) = &stock.short_description { if description.to_ascii_lowercase().trim() != "n/a" { token_counted_batch.push(generate_token_counted_stock( &description.to_ascii_lowercase(), token_map, stock, )); } } } token_counted_batch }); thread_pool.push(join_handle); } for handle in thread_pool { token_counted_stocks.append(&mut handle.join().unwrap()); } TokenCountedStockInfo { stocks: token_counted_stocks, } } fn generate_token_counted_stock( description: &String, mut token_map: HashMap<String, u32>, stock: &Stock, ) -> TokenCountedStock { for token in description.split(' ') { if !STOP_WORDS.contains(&token) { let alpha_numeric_token: String = token .chars() .filter(|character| character.is_ascii_alphanumeric()) .collect(); if token_map.contains_key(&alpha_numeric_token) { let current_count = &token_map .get(&alpha_numeric_token) .expect("Retrieval triggered on empty map entry"); let new_count = *current_count + 1; &token_map.insert(alpha_numeric_token, new_count); } else { token_map.insert(String::from(alpha_numeric_token), 1); } } } let token_counted_stock = TokenCountedStock { ticker: match &stock.ticker { Some(ticker) => ticker.clone(), None => String::from(""), }, name: match &stock.name { Some(name) => name.clone(), None => String::from(""), }, legal_name: match &stock.legal_name { Some(legal_name) => legal_name.clone(), None => String::from(""), }, sic: match &stock.sic { Some(sic) => sic.clone(), None => String::from(""), }, stock_exchange: match &stock.stock_exchange { Some(stock_exchange) => stock_exchange.clone(), None => String::from(""), }, token_count: token_map, }; token_counted_stock } static STOP_WORDS: [&str; 543] = [ "a's", "able", "about", "above", "according", "accordingly", "across", "actually", "after", "afterwards", "again", "against", "ain't", "all", "allow", "allows", "almost", "alone", "along", "already", "also", "although", "always", "am", "among", "amongst", "an", "and", "another", "any", "anybody", "anyhow", "anyone", "anything", "anyway", "anyways", "anywhere", "apart", "appear", "appreciate", "appropriate", "are", "aren't", "around", "as", "aside", "ask", "asking", "associated", "at", "available", "away", "awfully", "be", "became", "because", "become", "becomes", "becoming", "been", "before", "beforehand", "behind", "being", "believe", "below", "beside", "besides", "best", "better", "between", "beyond", "both", "brief", "but", "by", "c'mon", "c's", "came", "can", "can't", "cannot", "cant", "cause", "causes", "certain", "certainly", "changes", "clearly", "co", "com", "come", "comes", "concerning", "consequently", "consider", "considering", "contain", "containing", "contains", "corresponding", "could", "couldn't", "course", "currently", "definitely", "described", "despite", "did", "didn't", "different", "do", "does", "doesn't", "doing", "don't", "done", "down", "downwards", "during", "each", "edu", "eg", "eight", "either", "else", "elsewhere", "enough", "entirely", "especially", "et", "etc", "even", "ever", "every", "everybody", "everyone", "everything", "everywhere", "ex", "exactly", "example", "except", "far", "few", "fifth", "first", "five", "followed", "following", "follows", "for", "former", "formerly", "forth", "four", "from", "further", "furthermore", "get", "gets", "getting", "given", "gives", "go", "goes", "going", "gone", "got", "gotten", "greetings", "had", "hadn't", "happens", "hardly", "has", "hasn't", "have", "haven't", "having", "he", "he's", "hello", "help", "hence", "her", "here", "here's", "hereafter", "hereby", "herein", "hereupon", "hers", "herself", "hi", "him", "himself", "his", "hither", "hopefully", "how", "howbeit", "however", "i'd", "i'll", "i'm", "i've", "ie", "if", "ignored", "immediate", "in", "inasmuch", "inc", "indeed", "indicate", "indicated", "indicates", "inner", "insofar", "instead", "into", "inward", "is", "isn't", "it", "it'd", "it'll", "it's", "its", "itself", "just", "keep", "keeps", "kept", "know", "known", "knows", "last", "lately", "later", "latter", "latterly", "least", "less", "lest", "let", "let's", "like", "liked", "likely", "little", "look", "looking", "looks", "ltd", "mainly", "many", "may", "maybe", "me", "mean", "meanwhile", "merely", "might", "more", "moreover", "most", "mostly", "much", "must", "my", "myself", "name", "namely", "nd", "near", "nearly", "necessary", "need", "needs", "neither", "never", "nevertheless", "new", "next", "nine", "no", "nobody", "non", "none", "noone", "nor", "normally", "not", "nothing", "novel", "now", "nowhere", "obviously", "of", "off", "often", "oh", "ok", "okay", "old", "on", "once", "one", "ones", "only", "onto", "or", "other", "others", "otherwise", "ought", "our", "ours", "ourselves", "out", "outside", "over", "overall", "own", "particular", "particularly", "per", "perhaps", "placed", "please", "plus", "possible", "presumably", "probably", "provides", "que", "quite", "qv", "rather", "rd", "re", "really", "reasonably", "regarding", "regardless", "regards", "relatively", "respectively", "right", "said", "same", "saw", "say", "saying", "says", "second", "secondly", "see", "seeing", "seem", "seemed", "seeming", "seems", "seen", "self", "selves", "sensible", "sent", "serious", "seriously", "seven", "several", "shall", "she", "should", "shouldn't", "since", "six", "so", "some", "somebody", "somehow", "someone", "something", "sometime", "sometimes", "somewhat", "somewhere", "soon", "sorry", "specified", "specify", "specifying", "still", "sub", "such", "sup", "sure", "t's", "take", "taken", "tell", "tends", "th", "than", "thank", "thanks", "thanx", "that", "that's", "thats", "the", "their", "theirs", "them", "themselves", "then", "thence", "there", "there's", "thereafter", "thereby", "therefore", "therein", "theres", "thereupon", "these", "they", "they'd", "they'll", "they're", "they've", "think", "third", "this", "thorough", "thoroughly", "those", "though", "three", "through", "throughout", "thru", "thus", "to", "together", "too", "took", "toward", "towards", "tried", "tries", "truly", "try", "trying", "twice", "two", "un", "under", "unfortunately", "unless", "unlikely", "until", "unto", "up", "upon", "us", "use", "used", "useful", "uses", "using", "usually", "value", "various", "very", "via", "viz", "vs", "want", "wants", "was", "wasn't", "way", "we", "we'd", "we'll", "we're", "we've", "welcome", "well", "went", "were", "weren't", "what", "what's", "whatever", "when", "whence", "whenever", "where", "where's", "whereafter", "whereas", "whereby", "wherein", "whereupon", "wherever", "whether", "which", "while", "whither", "who", "who's", "whoever", "whole", "whom", "whose", "why", "will", "willing", "wish", "with", "within", "without", "won't", "wonder", "would", "wouldn't", "yes", "yet", "you", "you'd", "you'll", "you're", "you've", "your", "yours", "yourself", "yourselves", "zero", ];
18.70945
95
0.492122
825f4008287f31a0bc3eb138936daaa9e91dcd18
6,035
sql
SQL
Triggers/triggers.sql
com6056/starrs
0caa585532af6eedcc7e916cde1a71fe302f3ca0
[ "MIT" ]
5
2017-05-31T22:01:56.000Z
2020-11-08T03:42:01.000Z
Triggers/triggers.sql
com6056/starrs
0caa585532af6eedcc7e916cde1a71fe302f3ca0
[ "MIT" ]
3
2016-08-29T01:03:42.000Z
2021-04-30T02:56:21.000Z
Triggers/triggers.sql
com6056/starrs
0caa585532af6eedcc7e916cde1a71fe302f3ca0
[ "MIT" ]
5
2015-10-20T22:36:12.000Z
2018-10-12T04:29:42.000Z
/* dns.a */ CREATE TRIGGER "dns_a_insert" BEFORE INSERT ON "dns"."a" FOR EACH ROW EXECUTE PROCEDURE "dns"."a_insert"(); CREATE TRIGGER "dns_a_update" BEFORE UPDATE ON "dns"."a" FOR EACH ROW EXECUTE PROCEDURE "dns"."a_update"(); /* dns.mx */ CREATE TRIGGER "dns_mx_insert" BEFORE INSERT ON "dns"."mx" FOR EACH ROW EXECUTE PROCEDURE "dns"."mx_insert"(); CREATE TRIGGER "dns_mx_update" BEFORE UPDATE ON "dns"."mx" FOR EACH ROW EXECUTE PROCEDURE "dns"."mx_update"(); /* dns.srv */ CREATE TRIGGER "dns_srv_insert" BEFORE INSERT ON "dns"."srv" FOR EACH ROW EXECUTE PROCEDURE "dns"."srv_insert"(); CREATE TRIGGER "dns_srv_update" BEFORE UPDATE ON "dns"."srv" FOR EACH ROW EXECUTE PROCEDURE "dns"."srv_update"(); /* dns.cname */ CREATE TRIGGER "dns_cname_insert" BEFORE INSERT ON "dns"."cname" FOR EACH ROW EXECUTE PROCEDURE "dns"."cname_insert"(); CREATE TRIGGER "dns_cname_update" BEFORE UPDATE ON "dns"."cname" FOR EACH ROW EXECUTE PROCEDURE "dns"."cname_update"(); /* dns.txt */ CREATE TRIGGER "dns_txt_insert" BEFORE INSERT ON "dns"."txt" FOR EACH ROW EXECUTE PROCEDURE "dns"."txt_insert"(); CREATE TRIGGER "dns_txt_update" BEFORE UPDATE ON "dns"."txt" FOR EACH ROW EXECUTE PROCEDURE "dns"."txt_update"(); /* dns.txt */ CREATE TRIGGER "dns_zone_txt_insert" BEFORE INSERT ON "dns"."zone_txt" FOR EACH ROW EXECUTE PROCEDURE "dns"."zone_txt_insert"(); CREATE TRIGGER "dns_zone_txt_update" BEFORE UPDATE ON "dns"."zone_txt" FOR EACH ROW EXECUTE PROCEDURE "dns"."zone_txt_update"(); /* ip.addresses */ CREATE TRIGGER "ip_addresses_insert" BEFORE INSERT ON "ip"."addresses" FOR EACH ROW EXECUTE PROCEDURE "ip"."addresses_insert"(); /* ip.ranges */ CREATE TRIGGER "ip_ranges_insert" BEFORE INSERT ON "ip"."ranges" FOR EACH ROW EXECUTE PROCEDURE "ip"."ranges_insert"(); CREATE TRIGGER "ip_ranges_update" BEFORE UPDATE ON "ip"."ranges" FOR EACH ROW EXECUTE PROCEDURE "ip"."ranges_update"(); /* ip.subnets */ CREATE TRIGGER "ip_subnets_insert" BEFORE INSERT ON "ip"."subnets" FOR EACH ROW EXECUTE PROCEDURE "ip"."subnets_insert"(); CREATE TRIGGER "ip_subnets_update" BEFORE UPDATE ON "ip"."subnets" FOR EACH ROW EXECUTE PROCEDURE "ip"."subnets_update"(); CREATE TRIGGER "ip_subnets_delete" BEFORE DELETE ON "ip"."subnets" FOR EACH ROW EXECUTE PROCEDURE "ip"."subnets_delete"(); /* systems.interface_addresses */ CREATE TRIGGER "systems_interface_addresses_insert" BEFORE INSERT ON "systems"."interface_addresses" FOR EACH ROW EXECUTE PROCEDURE "systems"."interface_addresses_insert"(); CREATE TRIGGER "systems_interface_addresses_update" BEFORE UPDATE ON "systems"."interface_addresses" FOR EACH ROW EXECUTE PROCEDURE "systems"."interface_addresses_update"(); CREATE TRIGGER "dns_a_insert_queue" AFTER INSERT ON "dns"."a" FOR EACH ROW EXECUTE PROCEDURE "dns"."queue_insert"(); CREATE TRIGGER "dns_a_update_queue" AFTER UPDATE ON "dns"."a" FOR EACH ROW EXECUTE PROCEDURE "dns"."queue_update"(); CREATE TRIGGER "dns_a_delete_queue" AFTER DELETE ON "dns"."a" FOR EACH ROW EXECUTE PROCEDURE "dns"."queue_delete"(); CREATE TRIGGER "dns_srv_insert_queue" AFTER INSERT ON "dns"."srv" FOR EACH ROW EXECUTE PROCEDURE "dns"."queue_insert"(); CREATE TRIGGER "dns_srv_update_queue" AFTER UPDATE ON "dns"."srv" FOR EACH ROW EXECUTE PROCEDURE "dns"."queue_update"(); CREATE TRIGGER "dns_srv_delete_queue" AFTER DELETE ON "dns"."srv" FOR EACH ROW EXECUTE PROCEDURE "dns"."queue_delete"(); CREATE TRIGGER "dns_cname_insert_queue" AFTER INSERT ON "dns"."cname" FOR EACH ROW EXECUTE PROCEDURE "dns"."queue_insert"(); CREATE TRIGGER "dns_cname_update_queue" AFTER UPDATE ON "dns"."cname" FOR EACH ROW EXECUTE PROCEDURE "dns"."queue_update"(); CREATE TRIGGER "dns_cname_delete_queue" AFTER DELETE ON "dns"."cname" FOR EACH ROW EXECUTE PROCEDURE "dns"."queue_delete"(); CREATE TRIGGER "dns_ns_insert_queue" AFTER INSERT ON "dns"."ns" FOR EACH ROW EXECUTE PROCEDURE "dns"."ns_query_insert"(); CREATE TRIGGER "dns_ns_update_queue" AFTER UPDATE ON "dns"."ns" FOR EACH ROW EXECUTE PROCEDURE "dns"."ns_query_update"(); CREATE TRIGGER "dns_ns_delete_queue" AFTER DELETE ON "dns"."ns" FOR EACH ROW EXECUTE PROCEDURE "dns"."ns_query_delete"(); CREATE TRIGGER "dns_mx_insert_queue" AFTER INSERT ON "dns"."mx" FOR EACH ROW EXECUTE PROCEDURE "dns"."queue_insert"(); CREATE TRIGGER "dns_mx_update_queue" AFTER UPDATE ON "dns"."mx" FOR EACH ROW EXECUTE PROCEDURE "dns"."queue_update"(); CREATE TRIGGER "dns_mx_delete_queue" AFTER DELETE ON "dns"."mx" FOR EACH ROW EXECUTE PROCEDURE "dns"."queue_delete"(); CREATE TRIGGER "dns_txt_insert_queue" AFTER INSERT ON "dns"."txt" FOR EACH ROW EXECUTE PROCEDURE "dns"."txt_query_insert"(); CREATE TRIGGER "dns_txt_update_queue" AFTER UPDATE ON "dns"."txt" FOR EACH ROW EXECUTE PROCEDURE "dns"."txt_query_update"(); CREATE TRIGGER "dns_txt_delete_queue" AFTER DELETE ON "dns"."txt" FOR EACH ROW EXECUTE PROCEDURE "dns"."txt_query_delete"(); CREATE TRIGGER "dns_zone_txt_insert_queue" AFTER INSERT ON "dns"."zone_txt" FOR EACH ROW EXECUTE PROCEDURE "dns"."txt_query_insert"(); CREATE TRIGGER "dns_zone_txt_update_queue" AFTER UPDATE ON "dns"."zone_txt" FOR EACH ROW EXECUTE PROCEDURE "dns"."txt_query_update"(); CREATE TRIGGER "dns_zone_txt_delete_queue" AFTER DELETE ON "dns"."zone_txt" FOR EACH ROW EXECUTE PROCEDURE "dns"."txt_query_delete"(); CREATE TRIGGER "dns_zone_a_insert" BEFORE INSERT ON "dns"."zone_a" FOR EACH ROW EXECUTE PROCEDURE "dns"."zone_a_insert"(); CREATE TRIGGER "dns_zone_a_update" BEFORE UPDATE ON "dns"."zone_a" FOR EACH ROW EXECUTE PROCEDURE "dns"."zone_a_update"(); CREATE TRIGGER "dns_zone_a_delete" BEFORE DELETE ON "dns"."zone_a" FOR EACH ROW EXECUTE PROCEDURE "dns"."zone_a_delete"(); CREATE TRIGGER "dns_zone_a_insert_queue" AFTER INSERT ON "dns"."zone_a" FOR EACH ROW EXECUTE PROCEDURE "dns"."queue_insert"(); CREATE TRIGGER "dns_zone_a_update_queue" AFTER UPDATE ON "dns"."zone_a" FOR EACH ROW EXECUTE PROCEDURE "dns"."queue_update"(); CREATE TRIGGER "dns_zone_a_delete_queue" AFTER DELETE ON "dns"."zone_a" FOR EACH ROW EXECUTE PROCEDURE "dns"."queue_delete"();
30.479798
72
0.76106
82804f8a7fe9b0d93302fd905ba837734fe34100
660
sql
SQL
sql/zalihe_OLD/za_proveru_zaliha.sql
ivancekic/sql-data-analysis
8be412c18eab7791b45a34d04b0632992263669b
[ "MIT" ]
null
null
null
sql/zalihe_OLD/za_proveru_zaliha.sql
ivancekic/sql-data-analysis
8be412c18eab7791b45a34d04b0632992263669b
[ "MIT" ]
null
null
null
sql/zalihe_OLD/za_proveru_zaliha.sql
ivancekic/sql-data-analysis
8be412c18eab7791b45a34d04b0632992263669b
[ "MIT" ]
null
null
null
select d.org_deo , sum(sd.kolicina * sd.faktor * sd.K_robe), sum(sd.realizovano * sd.faktor * sd.K_robe) /* distinct proizvod , d.broj_dok , P.TARIFNI_BROJ, stavka */ from stavka_dok sd, dokument d where d.status not in (0) and d.godina = 2006 and d.datum_dok >= to_date( '01.01.2006' , 'dd.mm.yyyy' ) and sd.proizvod in ( 14654 ) and sd.godina = d.godina and sd.vrsta_dok = d.vrsta_dok and sd.broj_dok = d.broj_dok -- sd.valuta != 'YUD' group by d.org_deo , sd.lokacija --order by to_number(proizvod)
28.695652
65
0.539394
21723548056e6625a54bfe97c90e64ad8f6c4529
258
sql
SQL
data/schema.sql
C-T-R-L-Z/GITHUB-STATS-PAGE
06195a01ec3aa67b2a54722a67a0986d69ccbe1c
[ "MIT" ]
2
2019-11-02T00:13:28.000Z
2019-11-09T00:07:30.000Z
data/schema.sql
masonrybits/GITHUB-STATS-PAGE
06195a01ec3aa67b2a54722a67a0986d69ccbe1c
[ "MIT" ]
9
2019-11-04T17:19:08.000Z
2019-11-07T19:43:55.000Z
data/schema.sql
masonrybits/GITHUB-STATS-PAGE
06195a01ec3aa67b2a54722a67a0986d69ccbe1c
[ "MIT" ]
1
2019-11-09T00:07:42.000Z
2019-11-09T00:07:42.000Z
DROP TABLE IF EXISTS orgs; CREATE TABLE orgs ( id SERIAL PRIMARY KEY, orgName VARCHAR(255), time BIGINT ); DROP TABLE IF EXISTS siteStats; CREATE TABLE siteStats ( id SERIAL PRIMARY KEY, username VARCHAR(255), apiCalls INTEGER, time BIGINT );
17.2
31
0.728682
63ecda6cd7756c68a4fdef2f9e5e1677fd2dfee2
1,169
dart
Dart
lib/utils/constants.dart
trancker/castScrean
b64ae966da9b5d67573035cec3952c31c99e49a0
[ "MIT" ]
6
2020-08-19T08:05:03.000Z
2022-02-15T07:11:22.000Z
lib/utils/constants.dart
trancker/castScrean
b64ae966da9b5d67573035cec3952c31c99e49a0
[ "MIT" ]
null
null
null
lib/utils/constants.dart
trancker/castScrean
b64ae966da9b5d67573035cec3952c31c99e49a0
[ "MIT" ]
3
2020-08-19T08:05:05.000Z
2022-01-24T08:15:28.000Z
import 'package:flutter/material.dart'; enum PageState { HOME_SCREEN, FOLDER_VIDEO_SCREEN, FOLDER_IMAGE_SCREEN, VIDEO_LIST_SCREEN, IMAGE_LIST_SCREEN, } enum FolderMode { VIDEO, IMAGE, } const kPrimaryTextColor = Color(0xFF1A242E); const kSubTextColor = Color(0x881A242E); const kBorderColor = Color(0xFFF3F3F3); class Utils { static String convertTimeVideos(int secs) { int minutes = ((secs / 60) % 60).toInt(); int hours = (secs ~/ (60 * 60)); int seconds = (secs % 60); if (hours > 0) return "${_convertNumberToString(hours)}:${_convertNumberToString(minutes)}:${_convertNumberToString(seconds)}"; else return "${_convertNumberToString(minutes)}:${_convertNumberToString(seconds)}"; } static String _convertNumberToString(int number) { if (number == 0) { return "00"; } else if (number <= 9) { return "0$number"; } else return "$number"; } static String shortenTitle(String title) { String result = title; if (title.length > 49) { result = title.substring(0, 40) + "~" + title.substring(title.lastIndexOf(".")); } return result; } }
24.354167
118
0.646707
884eb03f11a288d42408d571c1089cd733393b70
15,142
cpp
C++
src/images/SkPngEncoder.cpp
Shachlan/skia
633db4db7672fd55b48ba1073256853e00f18d8c
[ "BSD-3-Clause" ]
96
2017-05-11T13:10:35.000Z
2021-11-21T03:11:43.000Z
src/images/SkPngEncoder.cpp
Shachlan/skia
633db4db7672fd55b48ba1073256853e00f18d8c
[ "BSD-3-Clause" ]
4
2017-05-20T23:10:49.000Z
2018-02-04T04:39:05.000Z
src/images/SkPngEncoder.cpp
Shachlan/skia
633db4db7672fd55b48ba1073256853e00f18d8c
[ "BSD-3-Clause" ]
43
2017-05-24T13:43:37.000Z
2022-02-14T07:55:58.000Z
/* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/images/SkImageEncoderPriv.h" #ifdef SK_HAS_PNG_LIBRARY #include "include/core/SkStream.h" #include "include/core/SkString.h" #include "include/encode/SkPngEncoder.h" #include "include/private/SkImageInfoPriv.h" #include "src/codec/SkColorTable.h" #include "src/codec/SkPngPriv.h" #include "src/images/SkImageEncoderFns.h" #include <vector> #include "png.h" static_assert(PNG_FILTER_NONE == (int)SkPngEncoder::FilterFlag::kNone, "Skia libpng filter err."); static_assert(PNG_FILTER_SUB == (int)SkPngEncoder::FilterFlag::kSub, "Skia libpng filter err."); static_assert(PNG_FILTER_UP == (int)SkPngEncoder::FilterFlag::kUp, "Skia libpng filter err."); static_assert(PNG_FILTER_AVG == (int)SkPngEncoder::FilterFlag::kAvg, "Skia libpng filter err."); static_assert(PNG_FILTER_PAETH == (int)SkPngEncoder::FilterFlag::kPaeth, "Skia libpng filter err."); static_assert(PNG_ALL_FILTERS == (int)SkPngEncoder::FilterFlag::kAll, "Skia libpng filter err."); static constexpr bool kSuppressPngEncodeWarnings = true; static void sk_error_fn(png_structp png_ptr, png_const_charp msg) { if (!kSuppressPngEncodeWarnings) { SkDebugf("libpng encode error: %s\n", msg); } longjmp(png_jmpbuf(png_ptr), 1); } static void sk_write_fn(png_structp png_ptr, png_bytep data, png_size_t len) { SkWStream* stream = (SkWStream*)png_get_io_ptr(png_ptr); if (!stream->write(data, len)) { png_error(png_ptr, "sk_write_fn cannot write to stream"); } } class SkPngEncoderMgr final : SkNoncopyable { public: /* * Create the decode manager * Does not take ownership of stream */ static std::unique_ptr<SkPngEncoderMgr> Make(SkWStream* stream); bool setHeader(const SkImageInfo& srcInfo, const SkPngEncoder::Options& options); bool setColorSpace(const SkImageInfo& info); bool writeInfo(const SkImageInfo& srcInfo); void chooseProc(const SkImageInfo& srcInfo); png_structp pngPtr() { return fPngPtr; } png_infop infoPtr() { return fInfoPtr; } int pngBytesPerPixel() const { return fPngBytesPerPixel; } transform_scanline_proc proc() const { return fProc; } ~SkPngEncoderMgr() { png_destroy_write_struct(&fPngPtr, &fInfoPtr); } private: SkPngEncoderMgr(png_structp pngPtr, png_infop infoPtr) : fPngPtr(pngPtr) , fInfoPtr(infoPtr) {} png_structp fPngPtr; png_infop fInfoPtr; int fPngBytesPerPixel; transform_scanline_proc fProc; }; std::unique_ptr<SkPngEncoderMgr> SkPngEncoderMgr::Make(SkWStream* stream) { png_structp pngPtr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, sk_error_fn, nullptr); if (!pngPtr) { return nullptr; } png_infop infoPtr = png_create_info_struct(pngPtr); if (!infoPtr) { png_destroy_write_struct(&pngPtr, nullptr); return nullptr; } png_set_write_fn(pngPtr, (void*)stream, sk_write_fn, nullptr); return std::unique_ptr<SkPngEncoderMgr>(new SkPngEncoderMgr(pngPtr, infoPtr)); } bool SkPngEncoderMgr::setHeader(const SkImageInfo& srcInfo, const SkPngEncoder::Options& options) { if (setjmp(png_jmpbuf(fPngPtr))) { return false; } int pngColorType; png_color_8 sigBit; int bitDepth = 8; switch (srcInfo.colorType()) { case kRGBA_F16Norm_SkColorType: case kRGBA_F16_SkColorType: case kRGBA_F32_SkColorType: sigBit.red = 16; sigBit.green = 16; sigBit.blue = 16; sigBit.alpha = 16; bitDepth = 16; pngColorType = srcInfo.isOpaque() ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_RGB_ALPHA; fPngBytesPerPixel = 8; break; case kGray_8_SkColorType: sigBit.gray = 8; pngColorType = PNG_COLOR_TYPE_GRAY; fPngBytesPerPixel = 1; SkASSERT(srcInfo.isOpaque()); break; case kRGBA_8888_SkColorType: case kBGRA_8888_SkColorType: sigBit.red = 8; sigBit.green = 8; sigBit.blue = 8; sigBit.alpha = 8; pngColorType = srcInfo.isOpaque() ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_RGB_ALPHA; fPngBytesPerPixel = srcInfo.isOpaque() ? 3 : 4; break; case kRGB_888x_SkColorType: sigBit.red = 8; sigBit.green = 8; sigBit.blue = 8; pngColorType = PNG_COLOR_TYPE_RGB; fPngBytesPerPixel = 3; SkASSERT(srcInfo.isOpaque()); break; case kARGB_4444_SkColorType: if (kUnpremul_SkAlphaType == srcInfo.alphaType()) { return false; } sigBit.red = 4; sigBit.green = 4; sigBit.blue = 4; sigBit.alpha = 4; pngColorType = srcInfo.isOpaque() ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_RGB_ALPHA; fPngBytesPerPixel = srcInfo.isOpaque() ? 3 : 4; break; case kRGB_565_SkColorType: sigBit.red = 5; sigBit.green = 6; sigBit.blue = 5; pngColorType = PNG_COLOR_TYPE_RGB; fPngBytesPerPixel = 3; SkASSERT(srcInfo.isOpaque()); break; case kAlpha_8_SkColorType: // store as gray+alpha, but ignore gray sigBit.gray = kGraySigBit_GrayAlphaIsJustAlpha; sigBit.alpha = 8; pngColorType = PNG_COLOR_TYPE_GRAY_ALPHA; fPngBytesPerPixel = 2; break; case kRGBA_1010102_SkColorType: bitDepth = 16; sigBit.red = 10; sigBit.green = 10; sigBit.blue = 10; sigBit.alpha = 2; pngColorType = srcInfo.isOpaque() ? PNG_COLOR_TYPE_RGB : PNG_COLOR_TYPE_RGB_ALPHA; fPngBytesPerPixel = 8; break; case kRGB_101010x_SkColorType: bitDepth = 16; sigBit.red = 10; sigBit.green = 10; sigBit.blue = 10; pngColorType = PNG_COLOR_TYPE_RGB; fPngBytesPerPixel = 6; break; default: return false; } png_set_IHDR(fPngPtr, fInfoPtr, srcInfo.width(), srcInfo.height(), bitDepth, pngColorType, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); png_set_sBIT(fPngPtr, fInfoPtr, &sigBit); int filters = (int)options.fFilterFlags & (int)SkPngEncoder::FilterFlag::kAll; SkASSERT(filters == (int)options.fFilterFlags); png_set_filter(fPngPtr, PNG_FILTER_TYPE_BASE, filters); int zlibLevel = SkTMin(SkTMax(0, options.fZLibLevel), 9); SkASSERT(zlibLevel == options.fZLibLevel); png_set_compression_level(fPngPtr, zlibLevel); // Set comments in tEXt chunk const sk_sp<SkDataTable>& comments = options.fComments; if (comments != nullptr) { std::vector<png_text> png_texts(comments->count()); std::vector<SkString> clippedKeys; for (int i = 0; i < comments->count() / 2; ++i) { const char* keyword; const char* originalKeyword = comments->atStr(2 * i); const char* text = comments->atStr(2 * i + 1); if (strlen(originalKeyword) <= PNG_KEYWORD_MAX_LENGTH) { keyword = originalKeyword; } else { SkDEBUGFAILF("PNG tEXt keyword should be no longer than %d.", PNG_KEYWORD_MAX_LENGTH); clippedKeys.emplace_back(originalKeyword, PNG_KEYWORD_MAX_LENGTH); keyword = clippedKeys.back().c_str(); } // It seems safe to convert png_const_charp to png_charp for key/text, // and we don't have to provide text_length and other fields as we're providing // 0-terminated c_str with PNG_TEXT_COMPRESSION_NONE (no compression, no itxt). png_texts[i].compression = PNG_TEXT_COMPRESSION_NONE; png_texts[i].key = (png_charp)keyword; png_texts[i].text = (png_charp)text; } png_set_text(fPngPtr, fInfoPtr, png_texts.data(), png_texts.size()); } return true; } static transform_scanline_proc choose_proc(const SkImageInfo& info) { switch (info.colorType()) { case kUnknown_SkColorType: break; case kRGBA_8888_SkColorType: switch (info.alphaType()) { case kOpaque_SkAlphaType: return transform_scanline_RGBX; case kUnpremul_SkAlphaType: return transform_scanline_memcpy; case kPremul_SkAlphaType: return transform_scanline_rgbA; default: SkASSERT(false); return nullptr; } case kBGRA_8888_SkColorType: switch (info.alphaType()) { case kOpaque_SkAlphaType: return transform_scanline_BGRX; case kUnpremul_SkAlphaType: return transform_scanline_BGRA; case kPremul_SkAlphaType: return transform_scanline_bgrA; default: SkASSERT(false); return nullptr; } case kRGB_565_SkColorType: return transform_scanline_565; case kRGB_888x_SkColorType: return transform_scanline_RGBX; case kARGB_4444_SkColorType: switch (info.alphaType()) { case kOpaque_SkAlphaType: return transform_scanline_444; case kPremul_SkAlphaType: return transform_scanline_4444; default: SkASSERT(false); return nullptr; } case kGray_8_SkColorType: return transform_scanline_memcpy; case kRGBA_F16Norm_SkColorType: case kRGBA_F16_SkColorType: switch (info.alphaType()) { case kOpaque_SkAlphaType: case kUnpremul_SkAlphaType: return transform_scanline_F16; case kPremul_SkAlphaType: return transform_scanline_F16_premul; default: SkASSERT(false); return nullptr; } case kRGBA_F32_SkColorType: switch (info.alphaType()) { case kOpaque_SkAlphaType: case kUnpremul_SkAlphaType: return transform_scanline_F32; case kPremul_SkAlphaType: return transform_scanline_F32_premul; default: SkASSERT(false); return nullptr; } case kRGBA_1010102_SkColorType: switch (info.alphaType()) { case kOpaque_SkAlphaType: case kUnpremul_SkAlphaType: return transform_scanline_1010102; case kPremul_SkAlphaType: return transform_scanline_1010102_premul; default: SkASSERT(false); return nullptr; } case kRGB_101010x_SkColorType: return transform_scanline_101010x; case kAlpha_8_SkColorType: return transform_scanline_A8_to_GrayAlpha; } SkASSERT(false); return nullptr; } static void set_icc(png_structp png_ptr, png_infop info_ptr, const SkImageInfo& info) { sk_sp<SkData> icc = icc_from_color_space(info); if (!icc) { return; } #if PNG_LIBPNG_VER_MAJOR > 1 || (PNG_LIBPNG_VER_MAJOR == 1 && PNG_LIBPNG_VER_MINOR >= 5) const char* name = "Skia"; png_const_bytep iccPtr = icc->bytes(); #else SkString str("Skia"); char* name = str.writable_str(); png_charp iccPtr = (png_charp) icc->writable_data(); #endif png_set_iCCP(png_ptr, info_ptr, name, 0, iccPtr, icc->size()); } bool SkPngEncoderMgr::setColorSpace(const SkImageInfo& info) { if (setjmp(png_jmpbuf(fPngPtr))) { return false; } if (info.colorSpace() && info.colorSpace()->isSRGB()) { png_set_sRGB(fPngPtr, fInfoPtr, PNG_sRGB_INTENT_PERCEPTUAL); } else { set_icc(fPngPtr, fInfoPtr, info); } return true; } bool SkPngEncoderMgr::writeInfo(const SkImageInfo& srcInfo) { if (setjmp(png_jmpbuf(fPngPtr))) { return false; } png_write_info(fPngPtr, fInfoPtr); if (kRGBA_F16_SkColorType == srcInfo.colorType() && kOpaque_SkAlphaType == srcInfo.alphaType()) { // For kOpaque, kRGBA_F16, we will keep the row as RGBA and tell libpng // to skip the alpha channel. png_set_filler(fPngPtr, 0, PNG_FILLER_AFTER); } return true; } void SkPngEncoderMgr::chooseProc(const SkImageInfo& srcInfo) { fProc = choose_proc(srcInfo); } std::unique_ptr<SkEncoder> SkPngEncoder::Make(SkWStream* dst, const SkPixmap& src, const Options& options) { if (!SkPixmapIsValid(src)) { return nullptr; } std::unique_ptr<SkPngEncoderMgr> encoderMgr = SkPngEncoderMgr::Make(dst); if (!encoderMgr) { return nullptr; } if (!encoderMgr->setHeader(src.info(), options)) { return nullptr; } if (!encoderMgr->setColorSpace(src.info())) { return nullptr; } if (!encoderMgr->writeInfo(src.info())) { return nullptr; } encoderMgr->chooseProc(src.info()); return std::unique_ptr<SkPngEncoder>(new SkPngEncoder(std::move(encoderMgr), src)); } SkPngEncoder::SkPngEncoder(std::unique_ptr<SkPngEncoderMgr> encoderMgr, const SkPixmap& src) : INHERITED(src, encoderMgr->pngBytesPerPixel() * src.width()) , fEncoderMgr(std::move(encoderMgr)) {} SkPngEncoder::~SkPngEncoder() {} bool SkPngEncoder::onEncodeRows(int numRows) { if (setjmp(png_jmpbuf(fEncoderMgr->pngPtr()))) { return false; } const void* srcRow = fSrc.addr(0, fCurrRow); for (int y = 0; y < numRows; y++) { fEncoderMgr->proc()((char*)fStorage.get(), (const char*)srcRow, fSrc.width(), SkColorTypeBytesPerPixel(fSrc.colorType())); png_bytep rowPtr = (png_bytep) fStorage.get(); png_write_rows(fEncoderMgr->pngPtr(), &rowPtr, 1); srcRow = SkTAddOffset<const void>(srcRow, fSrc.rowBytes()); } fCurrRow += numRows; if (fCurrRow == fSrc.height()) { png_write_end(fEncoderMgr->pngPtr(), fEncoderMgr->infoPtr()); } return true; } bool SkPngEncoder::Encode(SkWStream* dst, const SkPixmap& src, const Options& options) { auto encoder = SkPngEncoder::Make(dst, src, options); return encoder.get() && encoder->encodeRows(src.height()); } #endif
34.335601
100
0.607978
dc302609aad490c6ede35a8c28a4385fcaacdb1c
3,986
dart
Dart
lib/screens/vocabulary_screen.dart
mauriciotogneri/languages
7339c48c5c49dea5ce125f2a82d7042817a746ea
[ "MIT" ]
null
null
null
lib/screens/vocabulary_screen.dart
mauriciotogneri/languages
7339c48c5c49dea5ce125f2a82d7042817a746ea
[ "MIT" ]
null
null
null
lib/screens/vocabulary_screen.dart
mauriciotogneri/languages
7339c48c5c49dea5ce125f2a82d7042817a746ea
[ "MIT" ]
null
null
null
import 'package:languages/json/json_expression.dart'; import 'package:languages/storage/known_words_storage.dart'; import 'package:languages/models/vocabulary.dart'; import 'package:languages/models/player.dart'; import 'package:languages/widgets/expression_text.dart'; import 'package:languages/widgets/option_button.dart'; import 'package:flutter/material.dart'; // TODO(momo): Don't repeat words in the same session // TODO(momo): Remove all duplicated class VocabularyScreen extends StatefulWidget { final Vocabulary vocabulary; const VocabularyScreen(this.vocabulary); @override _VocabularyScreenState createState() => _VocabularyScreenState(); } class _VocabularyScreenState extends State<VocabularyScreen> { JsonExpression expression; @override Widget build(BuildContext context) { if (expression == null) { return Empty(_nextExpression); } else { return Content(widget.vocabulary, expression, _nextExpression); } } void _nextExpression() { setState(() { expression = widget.vocabulary.randomExpression; }); } } class Empty extends StatelessWidget { final Function nextExpression; const Empty(this.nextExpression); @override Widget build(BuildContext context) { return Center( child: OptionButton( icon: Icons.play_arrow, color: Colors.blue, onPressed: _onStart, ), ); } void _onStart() => nextExpression(); } class Content extends StatefulWidget { final Vocabulary vocabulary; final JsonExpression expression; final Function nextExpression; const Content(this.vocabulary, this.expression, this.nextExpression); @override _ContentState createState() => _ContentState(); } class _ContentState extends State<Content> { bool hide = true; @override void initState() { super.initState(); Player.playSingle(widget.vocabulary.originLocale, widget.expression.origin); } @override void didUpdateWidget(covariant Content oldWidget) { super.didUpdateWidget(oldWidget); Player.playSingle(widget.vocabulary.originLocale, widget.expression.origin); } @override Widget build(BuildContext context) { return Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ ExpressionText( widget.vocabulary.originLocale, widget.expression.origin, ), const SizedBox(height: 20), if (hide) Column( mainAxisSize: MainAxisSize.min, children: [ const SizedBox(height: 20), OptionButton( text: '?', color: Colors.blue, onPressed: _onReveal, ), const SizedBox(height: 21), ], ) else ExpressionText( widget.vocabulary.targetLocale, widget.expression.target, ), const SizedBox(height: 50), if (!hide) Row( mainAxisAlignment: MainAxisAlignment.center, children: [ OptionButton( icon: Icons.close, color: Colors.red, onPressed: _onIncorrect, ), const SizedBox(width: 20), OptionButton( icon: Icons.check, color: Colors.green, onPressed: _onCorrect, ), ], ), ], ), ); } void _onReveal() { Player.playSingle(widget.vocabulary.targetLocale, widget.expression.target); setState(() { hide = false; }); } void _onIncorrect() { setState(() { hide = true; }); widget.nextExpression(); } Future _onCorrect() async { await KnownWordsStorage.add(widget.expression.origin); setState(() { hide = true; }); widget.nextExpression(); } }
24.757764
80
0.608128
6b388dffe01a7400a109573df68a5c2cf155ef04
1,916
swift
Swift
algorithms/swift/0018_ 4sum.swift
yimtcode/LeetCode
470b4a34c57e7efe1967bcad9134733c712bf51c
[ "MIT" ]
null
null
null
algorithms/swift/0018_ 4sum.swift
yimtcode/LeetCode
470b4a34c57e7efe1967bcad9134733c712bf51c
[ "MIT" ]
null
null
null
algorithms/swift/0018_ 4sum.swift
yimtcode/LeetCode
470b4a34c57e7efe1967bcad9134733c712bf51c
[ "MIT" ]
null
null
null
class Solution { func fourSum(_ nums: [Int], _ target: Int) -> [[Int]] { if nums.count < 4 { return [] } var result: [[Int]] = [] let soredNums = nums.sorted() for n1Index in 0..<soredNums.count - 3 { let n1 = soredNums[n1Index] // 过滤重复 if n1Index != 0 && n1 == soredNums[n1Index - 1] { continue } for n2Index in n1Index + 1..<soredNums.count - 2 { let n2 = soredNums[n2Index] // 过滤重复 if n2Index != n1Index + 1 && n2 == soredNums[n2Index - 1] { continue } var (n3Index, n4Index) = (n2Index + 1, soredNums.count - 1) while n3Index < n4Index { let (n3, n4) = (soredNums[n3Index], soredNums[n4Index]) let sum = n1 + n2 + n3 + n4 if sum == target { result.append([n1, n2, n3, n4]) n3Index += 1 // 过滤重复n3 while n3Index < n4Index && n3 == soredNums[n3Index] { n3Index += 1 } n4Index -= 1 // 过滤重复n4 while n3Index < n4Index && n4 == soredNums[n4Index] { n4Index -= 1 } } else if sum < target { n3Index += 1 } else { n4Index -= 1 } } } } return result } } // example 1 //let nums: [Int] = [1, 0, -1, 0, -2, 2] //let target: Int = 0 // example 2 let nums: [Int] = [2, 2, 2, 2, 2] let target: Int = 8 let solution = Solution() let result = solution.fourSum(nums, target) print(result)
30.903226
77
0.384134
6228f77cfd9b43bdbd93c511c19043175e9d19af
7,248
swift
Swift
Sources/swift_lm.swift
klgraham/swift-lm
1967d6c5506418f33693664905007b948ea8b93d
[ "MIT" ]
2
2017-10-10T14:34:32.000Z
2018-03-12T01:33:19.000Z
Sources/swift_lm.swift
klgraham/swift-lm
1967d6c5506418f33693664905007b948ea8b93d
[ "MIT" ]
null
null
null
Sources/swift_lm.swift
klgraham/swift-lm
1967d6c5506418f33693664905007b948ea8b93d
[ "MIT" ]
null
null
null
import Foundation struct Constants { static let alphanumericChars = Set("abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLKMNOPQRSTUVWXYZ1234567890".characters) static let letters = Set("abcdefghijklmnopqrstuvwxyz".characters) } func removeNonAlphanumericCharacters(from text: String) -> String { return String(text.characters.filter { Constants.alphanumericChars.contains($0) }) } // split a string on \s, \n, \r, and \t and lowercase the text func tokenize(_ text: String) -> [String] { let words = text.components(separatedBy: .whitespacesAndNewlines) return words.flatMap { $0.components(separatedBy: "\t") }.map { removeNonAlphanumericCharacters(from: $0.lowercased()) } } func loadCorpus(from path: String) -> [String] { var words = [String]() if let streamReader = StreamReader(path: path) { defer { streamReader.close() } for line in streamReader { words.append(contentsOf: tokenize(line)) } } return words } func getStringIndex(at index: Int, of text: String) -> String.Index { return text.index(text.startIndex, offsetBy: index) } func getChar(at i: Int, from text: String) -> Character? { if i < text.characters.count { return text[getStringIndex(at: i, of: text)] } else { return Optional.none } } func getSubstring(of text: String, from: Int, to: Int) -> String { var substring = "" for i in from..<to { if let c = getChar(at: i, from: text) { substring += String(c) } } return substring } // split string into two parts // (1) substring from i to the end // (2) substring from the start to i func split(word: String, at index: Int) -> (String, String ) { let prefix = getSubstring(of: word, from: 0, to: index) let suffix = getSubstring(of: word, from: index, to: word.characters.count) return (prefix, suffix) } // returns a new string, absent the character at specified index func deleteChar(at i: Int, from text: String) -> String { var output = text output.remove(at: getStringIndex(at: i, of: text)) return output } func swapChars(at i: Int, and j: Int, of text: String) -> String { assert(i < j, "Error: \(i) is not less than \(j)") let a = getChar(at: i, from: text) let b = getChar(at: j, from: text) return getSubstring(of: text, from: 0, to: i) + String(b!) + getSubstring(of: text, from: (i + 1), to: j) + String(a!) + getSubstring(of: text, from: (j + 1), to: text.characters.count) } func replaceChar(at i: Int, from text: String, with a: Character) -> String { return getSubstring(of: text, from: 0, to: i) + String(a) + getSubstring(of: text, from: (i+1), to: text.characters.count) } func insert(_ c: Character, into text: String, at index: Int) -> String { var output = text output.insert(c, at: getStringIndex(at: index, of: text)) return output } func countWordsIn(_ words: [String]) -> [String: Int] { var wordCounts = [String: Int]() for word in words { if let count = wordCounts[word] { wordCounts[word] = count + 1 } else { wordCounts[word] = 1 } } return wordCounts } struct UnigramModel { private var maxCorrections = 3 private let wordCounts: [String: Int] init(corpus path: String) { let words = loadCorpus(from: path) wordCounts = countWordsIn(words) } func getFrequencyOf(_ word: String) -> Int { if let frequency = wordCounts[word] { return frequency } else { return 0 } } func getWordCounts() -> [String: Int] { return wordCounts } mutating func setMaxCorrections(to n: Int) { maxCorrections = n } func vocabContains(_ word: String) -> Bool { if let _ = wordCounts[word] { return true } else { return false } } func getWordsOffByOneCharacter(from word: String) -> Set<String> { var edits = [String]() var splits = [(String, String)]() for i in 0...(word.characters.count) { splits.append(split(word: word, at: i)) } for (left, right) in splits { if !right.isEmpty { // deletions edits.append(left + deleteChar(at: 0, from: right)) // swap adjacent letters if right.characters.count > 1 { edits.append(left + swapChars(at: 0, and: 1, of: right)) } for letter in Constants.letters { // insertions edits.append(left + String(letter) + right) // replacements edits.append(left + replaceChar(at: 0, from: right, with: letter)) } } } return Set(edits) } func getWordsOffByTwoCharacters(from word: String) -> Set<String> { var edits = [String]() for e1 in getWordsOffByOneCharacter(from: word) { for e2 in getWordsOffByOneCharacter(from: e1) { edits.append(e2) } } return Set(edits) } func generateCorrectionCandidates(of word: String) -> [String] { var candidates = [String]() let knownEdits1 = getWordsOffByOneCharacter(from: word).filter { vocabContains($0) } let knownEdits2 = getWordsOffByTwoCharacters(from: word).filter { vocabContains($0) } candidates.append(contentsOf: knownEdits1) candidates.append(contentsOf: knownEdits2) if vocabContains(word) { candidates.append(word) } return candidates } func getCorrectionsFor(_ word: String) -> [String] { let candidates = generateCorrectionCandidates(of: word) var wordProbabilities = [String: Float]() candidates.forEach { wordProbabilities[$0] = probabilityOf($0) } let topWords = wordProbabilities.sorted(by: >).map { $0.key } let n = min(maxCorrections, topWords.count) return Array(topWords.prefix(upTo: n)) } var totalNumWords: Int { var sum = 0 for count in wordCounts.values { sum += count } return sum } func probabilityOf(_ word: String) -> Float { if let count = wordCounts[word] { return Float(count) / Float(totalNumWords) } else { return 0 } } } class SpellChecker { private var model: UnigramModel init(corpus: String, maxCorrections: Int) { model = UnigramModel(corpus: corpus) model.setMaxCorrections(to: maxCorrections) } convenience init(corpus: String) { self.init(corpus: corpus, maxCorrections: 3) } convenience init() { self.init(corpus: "data/big.txt") } func getCorrectionsFor(_ word: String) -> [String] { return model.getCorrectionsFor(word) } }
28.423529
124
0.573951
6ba4c62a51265614d906600e54d23cba7a59342f
3,583
swift
Swift
Empresas iOS/Empresas iOS/Views/ListTableViewController.swift
mariaelenasilveira/list-empresas
b124543b391e1bb842985c60e7f8fe77585d2f63
[ "MIT" ]
null
null
null
Empresas iOS/Empresas iOS/Views/ListTableViewController.swift
mariaelenasilveira/list-empresas
b124543b391e1bb842985c60e7f8fe77585d2f63
[ "MIT" ]
null
null
null
Empresas iOS/Empresas iOS/Views/ListTableViewController.swift
mariaelenasilveira/list-empresas
b124543b391e1bb842985c60e7f8fe77585d2f63
[ "MIT" ]
null
null
null
// // ListTableViewController.swift // Empresas iOS // // Created by Mariaelena Silveira on 28/08/19. // Copyright © 2019 Mariaelena Nascimento Silveira. All rights reserved. // import UIKit class ListTableViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var searchBar: UISearchBar! @IBOutlet weak var mensagemLabel: UILabel! var arrayEnterprise: [Enterprise] = [] var tableViewArrayEnterprise: [Enterprise] = [] let listViewModel = ListViewModel() override func viewDidLoad() { super.viewDidLoad() listViewModel.delegate = self searchBar.delegate = self configureUI() touchScreenHideKeyboard() } private func configureUI() { tableView.isHidden = true let colorPink = UIColor(red: 222/255, green: 71/255, blue: 114/225, alpha: 1) searchBar.layer.borderWidth = 1 searchBar.layer.borderColor = colorPink.cgColor searchBar.isHidden = true searchBar.changeClearButtonColor(color: colorPink) let cancelButtonAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] UIBarButtonItem.appearance().setTitleTextAttributes(cancelButtonAttributes , for: .normal) } @IBAction func searchButtonAction(_ sender: Any) { listViewModel.loadEnterprises() searchBar.becomeFirstResponder() searchBar.isHidden = false } } extension ListTableViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tableViewArrayEnterprise.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = Bundle.main.loadNibNamed("EnterpriseTableViewCell", owner: self, options: nil)?.first as? EnterpriseTableViewCell else { return UITableViewCell()} cell.enterprise = tableViewArrayEnterprise[indexPath.row] return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let detailsViewController = self.storyboard?.instantiateViewController(withIdentifier: "DetailsViewController") as! DetailsViewController detailsViewController.enterprise = tableViewArrayEnterprise[indexPath.row] self.navigationController?.pushViewController(detailsViewController, animated: true) } } extension ListTableViewController: UISearchBarDelegate { func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { searchBar.isHidden = true mensagemLabel.isHidden = false tableView.isHidden = true view.endEditing(true) } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { view.endEditing(true) } func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { let enterprises = listViewModel.arrayEnterprise guard !searchText.isEmpty else { tableViewArrayEnterprise = enterprises tableView.reloadData() return } tableViewArrayEnterprise = enterprises.filter({ enterprise -> Bool in let enterpriseName = enterprise.enterpriseName return enterpriseName.contains(searchText) }) tableView.reloadData() mensagemLabel.isHidden = true tableView.isHidden = false } }
34.12381
171
0.684343
fe0f2057154c407f076e539542a9c8ca3fe18fb7
115
cpp
C++
C++/behavioral_patterns/iterator/Iterator.cpp
ploukareas/Design-Patterns
8effde38d73ae9058c3028c97ef395644a90d55b
[ "BSD-3-Clause", "MIT" ]
10
2018-10-26T20:02:43.000Z
2022-03-21T02:00:46.000Z
C++/behavioral_patterns/iterator/Iterator.cpp
ploukareas/Design-Patterns
8effde38d73ae9058c3028c97ef395644a90d55b
[ "BSD-3-Clause", "MIT" ]
null
null
null
C++/behavioral_patterns/iterator/Iterator.cpp
ploukareas/Design-Patterns
8effde38d73ae9058c3028c97ef395644a90d55b
[ "BSD-3-Clause", "MIT" ]
2
2021-09-27T09:09:39.000Z
2021-11-19T18:52:40.000Z
// ˅ #include "behavioral_patterns/iterator/Iterator.h" // ˄ Iterator::~Iterator() { // ˅ // ˄ } // ˅ // ˄
7.1875
50
0.513043
fbb8299ab083d7552b12f205fdfdd6958a4df378
2,578
java
Java
Semestrul3/MAP/L1/All in one app/Application.java
Andrei15193/Laboratoare-Facultate
ef9f0f64c055e85ddc84bc05eddd417b330539ae
[ "MIT" ]
2
2019-04-06T09:42:26.000Z
2021-12-14T22:11:27.000Z
Semestrul3/MAP/L1/All in one app/Application.java
Andrei15193/Laboratoare-Facultate
ef9f0f64c055e85ddc84bc05eddd417b330539ae
[ "MIT" ]
null
null
null
Semestrul3/MAP/L1/All in one app/Application.java
Andrei15193/Laboratoare-Facultate
ef9f0f64c055e85ddc84bc05eddd417b330539ae
[ "MIT" ]
null
null
null
// Genereaza primul numar prim mai mare decat un numarul natural n dat. // Dandu-se numarul natural n, determina numerele prime p1 si p2 astfel ca // n = p1 + p2 (verificarea ipotezei lui Goldbach). // Determina varsta (in numar de zile) pentru o persoana. // Determina numerele prime p1 si p2 gemene imediat superioare numarului natural // nenul n dat. Doua numere prime p si q sunt gemene daca q-p = 2. // Fie n un numar natural dat. Calculati produsul p al tuturor factorilor proprii // ai lui n. // Palindromul unui numar este numarul obtinut prin scrierea cifrelor in ordine // inversa (Ex. palindrom(237) = 732). Pentru un n dat calculati palindromul sau. // Genereaza cel mai mic numar perfect mai mare decat un numar n dat. In cazul in // care nu exista, se afiseaza mesaj. Un numar este perfect daca este egal cu suma // divizorilor sai, exeptandu-l pe el insusi. (6=1+2+3). // Genereaza cel mai mare numar prim mai mic decat un numar n dat. In cazul in care // nu exista, se afiseaza mesaj. // Genereaza cel mai mare numar perfect mai mic decat un numar n dat. In cazul in // care nu exista, se afiseaza mesaj. Un numar este perfect daca este egal cu suma // divizorilor sai, exeptandu-l pe el insusi. (6=1+2+3). // Gaseste cel mai mic numar m din sirul lui Fibonacci definit de // f[0]=f[1]=1, f[n]=f[n-1]+f[n-2], pentru n>2, // mai mare decat numarul natural n dat, deci exista k astfel ca f[k]=m si m>n. // Se da un vector X cu n componente numare naturale. Sa se determine produsul // numerelor prime din sir. // Se da un vector X cu n componente numere naturale. Sa se determine suma // numerelor prime din sir. // Se da un vector X cu n componente numare naturale. Sa se cel mai mare numar prim // din sir. In cazul in care nu exista, se afiseaza mesaj. // Se da un vector X cu n componente numare naturale. Sa se cel mai mic numar prim // din sir. In cazul in care nu exista, se afiseaza mesaj. // Se da un vector X cu n componente numare naturale. Sa se determine suma numerelor // compuse (neprime) din sir. // Represents the application public class Application { // Point of entry. The program starts here. // Preconditions: // args: refers an array of Strings that represent the command line // arguments. // Postconditions: // Solves the given problem by requesting data (the n number) and prints // the solution to the standard output. public static void main(String[] args){ UserInterface ui = new UserInterface(new Controller()); ui.run(); } }
42.966667
84
0.707913
7150dfc13f5ef2bc62a05ead41f59e103d3bbe57
9,742
lua
Lua
src_rebuild/premake_modules/emscripten/emscripten_vstudio.lua
nahimr/REDRIVER2
dbe4e8999338da07dc69aa58691cd66e0532c191
[ "MIT" ]
681
2020-11-04T17:18:10.000Z
2022-03-30T05:14:25.000Z
src_rebuild/premake_modules/emscripten/emscripten_vstudio.lua
nahimr/REDRIVER2
dbe4e8999338da07dc69aa58691cd66e0532c191
[ "MIT" ]
147
2020-11-03T08:35:42.000Z
2022-03-28T23:10:18.000Z
src_rebuild/premake_modules/emscripten/emscripten_vstudio.lua
nahimr/REDRIVER2
dbe4e8999338da07dc69aa58691cd66e0532c191
[ "MIT" ]
63
2020-11-08T20:21:00.000Z
2022-03-29T21:25:15.000Z
-- -- emscripten_vstudio.lua -- Emscripten integration for vstudio. -- Copyright (c) 2012-2015 Manu Evans and the Premake project -- local p = premake local emscripten = p.modules.emscripten require "vstudio" local sln2005 = p.vstudio.sln2005 local vc2010 = p.vstudio.vc2010 local vstudio = p.vstudio local project = p.project local config = p.config -- -- Add Emscripten tools to vstudio actions. -- if vstudio.vs2010_architectures ~= nil then vstudio.vs2010_architectures.emscripten = "Emscripten" end local function alreadyHas(t, key) for _, k in ipairs(t) do if string.find(k, key) then return true end end return false end -- -- Extend configurationProperties. -- premake.override(vc2010, "platformToolset", function(orig, cfg) if cfg.system == p.EMSCRIPTEN then -- is there a reason to write this? default is fine. -- _p(2,'<PlatformToolset>emcc</PlatformToolset>') else orig(cfg) end end) premake.override(vc2010, "configurationType", function(oldfn, cfg) if cfg.system == p.EMSCRIPTEN then if cfg.kind then local types = { StaticLib = "StaticLibrary", ConsoleApp = "JSApplication", WindowedApp = "Application", HTMLPage = "Application" } if not types[cfg.kind] then error("Invalid 'kind' for Emscripten: " .. cfg.kind, 2) else _p(2,'<ConfigurationType>%s</ConfigurationType>', types[cfg.kind]) end end else oldfn(cfg) end end) -- -- Extend outputProperties. -- premake.override(vc2010.elements, "outputProperties", function(oldfn, cfg) local elements = oldfn(cfg) if cfg.system == p.EMSCRIPTEN then elements = table.join(elements, { emscripten.clangPath, emscripten.emccPath }) end return elements end) function emscripten.clangPath(cfg) if cfg.clangpath ~= nil then -- local dirs = project.getrelative(cfg.project, includedirs) -- dirs = path.translate(table.concat(fatalwarnings, ";")) _p(2,'<ClangPath>%s</ClangPath>', cfg.clangpath) end end function emscripten.emccPath(cfg) if cfg.emccpath ~= nil then -- local dirs = project.getrelative(cfg.project, includedirs) -- dirs = path.translate(table.concat(fatalwarnings, ";")) _p(2,'<EmccPath>%s</EmccPath>', cfg.emccpath) end end -- -- Extend clCompile. -- premake.override(vc2010.elements, "clCompile", function(oldfn, cfg) local elements = oldfn(cfg) if cfg.system == p.EMSCRIPTEN then elements = table.join(elements, { emscripten.debugInformation, emscripten.enableWarnings, emscripten.languageStandard, }) end return elements end) function emscripten.debugInformation(cfg) -- TODO: support these -- NoDebugInfo -- LimitedDebugInfo -- FullDebugInfo if cfg.flags.Symbols then _p(3,'<GenerateDebugInformation>FullDebugInfo</GenerateDebugInformation>') end end function emscripten.enableWarnings(cfg) if #cfg.enablewarnings > 0 then _x(3,'<EnableWarnings>%s</EnableWarnings>', table.concat(cfg.enablewarnings, ";")) end end function emscripten.languageStandard(cfg) local map = { c90 = "LanguageStandardC89", gnu90 = "LanguageStandardGnu89", c94 = "LanguageStandardC94", c99 = "LanguageStandardC99", gnu99 = "LanguageStandardGnu99", ["c++98"] = "LanguageStandardCxx03", ["gnu++98"] = "LanguageStandardGnu++98", ["c++11"] = "LanguageStandardC++11", ["gnu++11"] = "LanguageStandardGnu++11" } if cfg.languagestandard and map[cfg.languagestandard] then _p(3,'<LanguageStandardMode>%s</LanguageStandardMode>', map[cfg.languagestandard]) end end premake.override(vc2010, "disableSpecificWarnings", function(oldfn, cfg) if cfg.system == p.EMSCRIPTEN then if #cfg.disablewarnings > 0 then local warnings = table.concat(cfg.disablewarnings, ";") warnings = premake.esc(warnings) .. ";%%(DisableWarnings)" vc2010.element('DisableWarnings', condition, warnings) end else oldfn(cfg) end end) premake.override(vc2010, "treatSpecificWarningsAsErrors", function(oldfn, cfg) if cfg.system == p.EMSCRIPTEN then if #cfg.fatalwarnings > 0 then local fatal = table.concat(cfg.fatalwarnings, ";") fatal = premake.esc(fatal) .. ";%%(SpecificWarningsAsErrors)" vc2010.element('SpecificWarningsAsErrors', condition, fatal) end else oldfn(cfg) end end) premake.override(vc2010, "undefinePreprocessorDefinitions", function(oldfn, cfg, undefines, escapeQuotes, condition) if cfg.system == p.EMSCRIPTEN then if #undefines > 0 then undefines = table.concat(undefines, ";") if escapeQuotes then undefines = undefines:gsub('"', '\\"') end undefines = premake.esc(undefines) .. ";%%(PreprocessorUndefinitions)" vc2010.element('PreprocessorUndefinitions', condition, undefines) end else oldfn(cfg, undefines, escapeQuotes, condition) end end) premake.override(vc2010, "exceptionHandling", function(oldfn, cfg) -- ignored for Emscripten if cfg.system ~= p.EMSCRIPTEN then oldfn(cfg) end end) premake.override(vc2010, "additionalCompileOptions", function(oldfn, cfg, condition) if cfg.system == p.EMSCRIPTEN then emscripten.additionalCompileOptions(cfg, condition) end return oldfn(cfg, condition) end) function emscripten.additionalCompileOptions(cfg, condition) if cfg.flags["C++11"] then table.insert(cfg.buildoptions, "-std=c++11") end end -- these should be silenced for Emscripten premake.override(vc2010, "precompiledHeader", function(oldfn, cfg, filecfg, condition) if cfg.system ~= p.EMSCRIPTEN then oldfn(cfg, filecfg, condition) end end) premake.override(vc2010, "floatingPointModel", function(oldfn, cfg) if cfg.system ~= p.EMSCRIPTEN then oldfn(cfg) end end) -- -- Extend Link. -- premake.override(vc2010.elements, "link", function(oldfn, cfg, explicit) local elements = oldfn(cfg, explicit) if cfg.kind ~= p.STATICLIB and cfg.system == p.EMSCRIPTEN then elements = table.join(elements, { emscripten.linkerOptimizationLevel, emscripten.typedArrays, emscripten.closureCompiler, emscripten.minify, emscripten.ignoreDynamicLinking, emscripten.preJsFile, emscripten.postJsFile, emscripten.embedFile, emscripten.preloadFile, emscripten.htmlShellFile, emscripten.jsLibrary, }) end return elements end) function emscripten.linkerOptimizationLevel(cfg) local map = { ["Off"] = "O0", ["Simple"] = "O1", ["On"] = "O2", ["Unsafe"] = "O3", } if cfg.linkeroptimize and map[cfg.linkeroptimize] then _p(3, '<LinkerOptimizationLevel>%s</LinkerOptimizationLevel>', map[cfg.linkeroptimize]) end end function emscripten.typedArrays(cfg) local map = { ["None"] = "NoTypedArrays", ["Parallel"] = "ParallelTypedArrays", ["Shared"] = "SharedTypedArrays", } if cfg.typedarrays and map[cfg.typedarrays] then _p(3, '<TypedArrays>%s</TypedArrays>', map[cfg.typedarrays]) end end function emscripten.closureCompiler(cfg) if cfg.flags.NoClosureCompiler then _p(3, '<RunClosureCompiler>false</RunClosureCompiler>') end end function emscripten.minify(cfg) if cfg.flags.NoMinifyJavaScript then _p(3, '<RunMinify>false</RunMinify>') end end function emscripten.ignoreDynamicLinking(cfg) if cfg.flags.IgnoreDynamicLinking then _p(3, '<IgnoreDynamicLinking>true</IgnoreDynamicLinking>') end end function emscripten.preJsFile(cfg) if #cfg.jsprepend > 0 then local files = project.getrelative(cfg.project, cfg.jsprepend) _x(3, '<PreJsFile>%s;%%(PreJsFile)</PreJsFile>', table.concat(files, ";")) end end function emscripten.postJsFile(cfg) if #cfg.jsappend > 0 then local files = project.getrelative(cfg.project, cfg.jsappend) _x(3, '<PostJsFile>%s;%%(PostJsFile)</PostJsFile>', table.concat(files, ";")) end end function emscripten.embedFile(cfg) -- _x(3, '<EmbedFile>embedRes;embed2;%(EmbedFile)</EmbedFile>', ) end function emscripten.preloadFile(cfg) -- _x(3, '<PreloadFile>preloadRes;preload2;%(PreloadFile)</PreloadFile>', ) end function emscripten.htmlShellFile(cfg) -- _x(3, '<HtmlShellFile>htmlShell;html2;%(HtmlShellFile)</HtmlShellFile>', ) end function emscripten.jsLibrary(cfg) -- _x(3, '<JsLibrary>jsLib;jsLib2;%(JsLibrary)</JsLibrary>', ) end premake.override(vc2010, "additionalLinkOptions", function(oldfn, cfg) if cfg.system == p.EMSCRIPTEN then emscripten.additionalLinkOptions(cfg) -- TODO: should this be moved to bake or something? end return oldfn(cfg) end) -- these should be silenced for Emscripten premake.override(vc2010, "generateDebugInformation", function(oldfn, cfg) -- Note: Emscripten specifies the debug info in the clCompile section if cfg.system ~= p.EMSCRIPTEN then oldfn(cfg) end end) premake.override(vc2010, "subSystem", function(oldfn, cfg) if cfg.system ~= p.EMSCRIPTEN then oldfn(cfg) end end) premake.override(vc2010, "optimizeReferences", function(oldfn, cfg) if cfg.system ~= p.EMSCRIPTEN then oldfn(cfg) end end) premake.override(vc2010, "entryPointSymbol", function(oldfn, cfg) if cfg.system ~= p.EMSCRIPTEN then oldfn(cfg) end end) -- -- Add options unsupported by Emscripten vs-tool UI to <AdvancedOptions>. -- function emscripten.additionalLinkOptions(cfg) if #cfg.exportedfunctions > 0 then local functions = table.implode(cfg.exportedfunctions, "'", "'", ", ") table.insert(cfg.linkoptions, "-s EXPORTED_FUNCTIONS=\"[" .. functions .. "]\"") end if cfg.flags.NoExitRuntime then table.insert(cfg.linkoptions, "-s NO_EXIT_RUNTIME=1") end if cfg.flags.NoMemoryInitFile then table.insert(cfg.linkoptions, "--memory-init-file 0") end end
26.472826
117
0.705297
cc60df1bd65b81da8bbb82bfd3b5be192d9bec1a
6,191
swift
Swift
Hummingbird/PreferencesController.swift
glowinthedark/Hummingbird
fdc79a14c94099c3cebd68e26a9da37685ed1e3a
[ "MIT" ]
122
2019-03-03T14:26:12.000Z
2022-03-28T07:05:24.000Z
Hummingbird/PreferencesController.swift
glowinthedark/Hummingbird
fdc79a14c94099c3cebd68e26a9da37685ed1e3a
[ "MIT" ]
30
2019-02-17T09:48:09.000Z
2022-03-02T15:41:40.000Z
Hummingbird/PreferencesController.swift
glowinthedark/Hummingbird
fdc79a14c94099c3cebd68e26a9da37685ed1e3a
[ "MIT" ]
17
2019-06-13T19:02:52.000Z
2022-02-19T17:49:37.000Z
// // PreferencesController.swift // Hummingbird // // Created by Sven A. Schmidt on 02/05/2019. // Copyright © 2019 finestructure. All rights reserved. // import Cocoa protocol PreferencesControllerDelegate: class { func didRequestRegistrationController() func didRequestTipJarController() } class PreferencesController: NSWindowController { @IBOutlet weak var moveAlt: NSButton! @IBOutlet weak var moveCommand: NSButton! @IBOutlet weak var moveControl: NSButton! @IBOutlet weak var moveFn: NSButton! @IBOutlet weak var moveShift: NSButton! @IBOutlet weak var resizeAlt: NSButton! @IBOutlet weak var resizeCommand: NSButton! @IBOutlet weak var resizeControl: NSButton! @IBOutlet weak var resizeFn: NSButton! @IBOutlet weak var resizeShift: NSButton! @IBOutlet weak var resizeFromNearestCorner: NSButton! @IBOutlet weak var resizeInfoLabel: NSTextField! @IBOutlet weak var showMenuIcon: NSButton! @IBOutlet weak var registrationStatusLabel: NSTextField! @IBOutlet weak var versionLabel: NSTextField! weak var delegate: (ShowTipJarControllerDelegate & ShowRegistrationControllerDelegate)? var isRegistered: Bool { return License(forKey: .license, defaults: Current.defaults()) != nil } override func showWindow(_ sender: Any?) { super.showWindow(sender) updateCopy() } @IBAction func modifierClicked(_ sender: NSButton) { let moveButtons = [moveAlt, moveCommand, moveControl, moveFn, moveShift] let moveModifiers: [Modifiers<Move>] = [.alt, .command, .control, .fn, .shift] let resizeButtons = [resizeAlt, resizeCommand, resizeControl, resizeFn, resizeShift] let resizeModifiers: [Modifiers<Resize>] = [.alt, .command, .control, .fn, .shift] let modifierForButton = Dictionary( uniqueKeysWithValues: zip(moveButtons + resizeButtons, moveModifiers.map { $0.rawValue } + resizeModifiers.map { $0.rawValue } ) ) if let modifier = modifierForButton[sender] { if moveButtons.contains(sender) { let modifiers = Modifiers<Move>(forKey: .moveModifiers, defaults: Current.defaults()) let m = Modifiers<Move>(rawValue: modifier) try? modifiers.toggle(m).save(forKey: .moveModifiers, defaults: Current.defaults()) } else if resizeButtons.contains(sender) { let modifiers = Modifiers<Resize>(forKey: .resizeModifiers, defaults: Current.defaults()) let m = Modifiers<Resize>(rawValue: modifier) try? modifiers.toggle(m).save(forKey: .resizeModifiers, defaults: Current.defaults()) } // FIXME: this isn't great - maybe use a notification instead? Tracker.shared?.readModifiers() } } @IBAction func registrationLabelClicked(_ sender: Any) { if Current.featureFlags.commercial { if !isRegistered { close() delegate?.showRegistrationController() } } else { delegate?.showTipJarController() } } @IBAction func resizeFromNearestCornerClicked(_ sender: Any) { let value: NSNumber = { var v = Current.defaults().bool(forKey: DefaultsKeys.resizeFromNearestCorner.rawValue) v.toggle() return NSNumber(booleanLiteral: v) }() Current.defaults().set(value, forKey: DefaultsKeys.resizeFromNearestCorner.rawValue) updateCopy() } @IBAction func hideMenuIconClicked(_ sender: Any) { let value: NSNumber = { var v = Current.defaults().bool(forKey: DefaultsKeys.showMenuIcon.rawValue) v.toggle() return NSNumber(booleanLiteral: v) }() Current.defaults().set(value, forKey: DefaultsKeys.showMenuIcon.rawValue) updateCopy() (NSApp.delegate as? AppDelegate)?.updateStatusItemVisibility() } } extension PreferencesController: NSWindowDelegate { func windowDidChangeOcclusionState(_ notification: Notification) { do { let prefs = Modifiers<Move>(forKey: .moveModifiers, defaults: Current.defaults()) let buttons = [moveAlt, moveCommand, moveControl, moveFn, moveShift] let allModifiers: [Modifiers<Move>] = [.alt, .command, .control, .fn, .shift] let buttonForModifier = Dictionary(uniqueKeysWithValues: zip(allModifiers, buttons)) for (modifier, button) in buttonForModifier { button?.state = prefs.contains(modifier) ? .on : .off } } do { let prefs = Modifiers<Resize>(forKey: .resizeModifiers, defaults: Current.defaults()) let buttons = [resizeAlt, resizeCommand, resizeControl, resizeFn, resizeShift] let allModifiers: [Modifiers<Resize>] = [.alt, .command, .control, .fn, .shift] let buttonForModifier = Dictionary(uniqueKeysWithValues: zip(allModifiers, buttons)) for (modifier, button) in buttonForModifier { button?.state = prefs.contains(modifier) ? .on : .off } } resizeFromNearestCorner.state = Current.defaults().bool(forKey: DefaultsKeys.resizeFromNearestCorner.rawValue) ? .on : .off showMenuIcon.state = Current.defaults().bool(forKey: DefaultsKeys.showMenuIcon.rawValue) ? .on : .off updateCopy() } func updateCopy() { registrationStatusLabel.stringValue = Current.featureFlags.commercial ? ( isRegistered ? "🎫 Registered copy" : "⚠️ Unregistered – click to register" ) : "Fancy sending a coffee? ☕️ Please click here to support Hummingbird." resizeInfoLabel.stringValue = Current.defaults().bool(forKey: DefaultsKeys.resizeFromNearestCorner.rawValue) ? "Resizing will act on the window corner nearest to the cursor." : "Resizing will act on the lower right corner of the window." versionLabel.stringValue = appVersion(short: true) } }
39.183544
118
0.644969
9171b43472dc98c9894a189a43340c09fe979358
79
asm
Assembly
build.asm
Heathcode/hellones
9a5aaad6effa11b321a97468c2d687acde3cfff3
[ "MIT" ]
null
null
null
build.asm
Heathcode/hellones
9a5aaad6effa11b321a97468c2d687acde3cfff3
[ "MIT" ]
null
null
null
build.asm
Heathcode/hellones
9a5aaad6effa11b321a97468c2d687acde3cfff3
[ "MIT" ]
null
null
null
.include "header.asm" CODE .include "code.asm" DATA .include "data.asm"
9.875
22
0.658228
a2709062f06d88fb86124034fa59395f14150d8b
539
sql
SQL
v3.1/Database/dbo/Tables/TArrivalDepartureTimes.sql
LightosLimited/RailML
df4439865ee55e828cf05b1082bf0197eb825cee
[ "Apache-2.0" ]
null
null
null
v3.1/Database/dbo/Tables/TArrivalDepartureTimes.sql
LightosLimited/RailML
df4439865ee55e828cf05b1082bf0197eb825cee
[ "Apache-2.0" ]
null
null
null
v3.1/Database/dbo/Tables/TArrivalDepartureTimes.sql
LightosLimited/RailML
df4439865ee55e828cf05b1082bf0197eb825cee
[ "Apache-2.0" ]
null
null
null
CREATE TABLE [dbo].[TArrivalDepartureTimes] ( --From MergedXSDs XSD --From 'genericRailML' Namespace [TArrivalDepartureTimesId] BIGINT NOT NULL, [Scope] NVARCHAR(MAX) NOT NULL, [ArrivalValue] DATETIME NOT NULL, [ArrivalValueSpecified] BIT NOT NULL, [ArrivalDay] NVARCHAR(MAX) NOT NULL, [DepartureValue] DATETIME NOT NULL, [DepartureValueSpecified] BIT NOT NULL, [DepartureDay] NVARCHAR(MAX) NOT NULL, CONSTRAINT [PK_TArrivalDepartureTimesId] PRIMARY KEY CLUSTERED ([TArrivalDepartureTimesId] ASC) );
33.6875
96
0.742115
97cb909477436925cd0df5604a96fd82501cf2b5
5,291
asm
Assembly
Transynther/x86/_processed/NC/_zr_/i9-9900K_12_0xa0.log_21829_424.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
9
2020-08-13T19:41:58.000Z
2022-03-30T12:22:51.000Z
Transynther/x86/_processed/NC/_zr_/i9-9900K_12_0xa0.log_21829_424.asm
ljhsiun2/medusa
67d769b8a2fb42c538f10287abaf0e6dbb463f0c
[ "MIT" ]
1
2021-04-29T06:29:35.000Z
2021-05-13T21:02:30.000Z
Transynther/x86/_processed/NC/_zr_/i9-9900K_12_0xa0.log_21829_424.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 %r12 push %r15 push %r9 push %rax push %rbx push %rdi push %rdx lea addresses_WT_ht+0x1894d, %rbx nop nop add %rdx, %rdx mov (%rbx), %r9w nop nop nop nop nop xor %rax, %rax lea addresses_WT_ht+0x6985, %r12 clflush (%r12) nop and %r15, %r15 mov (%r12), %rdx nop nop nop nop nop xor $60587, %rbx lea addresses_D_ht+0x12c9d, %r9 cmp %rdi, %rdi movw $0x6162, (%r9) add %rax, %rax lea addresses_A_ht+0x1c82d, %rdx nop nop nop sub %r9, %r9 movl $0x61626364, (%rdx) nop nop nop nop cmp $15016, %rdi pop %rdx pop %rdi pop %rbx pop %rax pop %r9 pop %r15 pop %r12 ret .global s_faulty_load s_faulty_load: push %r10 push %r13 push %r14 push %rbp push %rdi push %rdx push %rsi // Store lea addresses_PSE+0x37d5, %rdi and %r10, %r10 mov $0x5152535455565758, %rbp movq %rbp, %xmm4 vmovups %ymm4, (%rdi) nop add %r13, %r13 // Load lea addresses_A+0xa121, %rsi nop nop nop nop add $57992, %rdx movups (%rsi), %xmm0 vpextrq $1, %xmm0, %r14 cmp %r13, %r13 // Faulty Load mov $0x1cf4fe0000000a7d, %rbp nop nop nop nop inc %r14 mov (%rbp), %rdx lea oracles, %r13 and $0xff, %rdx shlq $12, %rdx mov (%r13,%rdx,1), %rdx pop %rsi pop %rdx pop %rdi pop %rbp pop %r14 pop %r13 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'NT': False, 'same': False, 'congruent': 0, 'type': 'addresses_NC', 'AVXalign': False, 'size': 32}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_PSE', 'AVXalign': False, 'size': 32}} {'src': {'NT': False, 'same': False, 'congruent': 2, 'type': 'addresses_A', 'AVXalign': False, 'size': 16}, 'OP': 'LOAD'} [Faulty Load] {'src': {'NT': False, 'same': True, 'congruent': 0, 'type': 'addresses_NC', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'} <gen_prepare_buffer> {'src': {'NT': False, 'same': False, 'congruent': 4, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 2}, 'OP': 'LOAD'} {'src': {'NT': False, 'same': False, 'congruent': 3, 'type': 'addresses_WT_ht', 'AVXalign': False, 'size': 8}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 5, 'type': 'addresses_D_ht', 'AVXalign': False, 'size': 2}} {'OP': 'STOR', 'dst': {'NT': False, 'same': False, 'congruent': 4, 'type': 'addresses_A_ht', 'AVXalign': False, 'size': 4}} {'00': 21829} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
43.01626
2,999
0.655264
1e534a0ecf8f4dac7c8c0fd154a1e525ad70ae0e
1,243
css
CSS
css/app.css
Bigalan09/AI
f653356d0e18bb7665dfc5026170803995c46cd5
[ "MIT" ]
null
null
null
css/app.css
Bigalan09/AI
f653356d0e18bb7665dfc5026170803995c46cd5
[ "MIT" ]
null
null
null
css/app.css
Bigalan09/AI
f653356d0e18bb7665dfc5026170803995c46cd5
[ "MIT" ]
null
null
null
* { margin: 0; padding: 0; box-sizing: border-box; } body { font-family: "Source Sans Pro", sans-serif; font-size: 14px; background-color: #efefef; } .handle { width: 100%; float: left; text-align: center; line-height: 2.1; font-size: 1.1em; font-weight: bold; background-color: #ffffff !important; -webkit-user-select: none; -webkit-app-region: drag; } .handle .title { float: left; width: 96%; } .handle .close { width: 4%; float: right; cursor: pointer; color: #444444; -webkit-app-region: no-drag; } .handle .close:hover { background-color: #e03b1a; color: #ffeeee; -webkit-transition: background-color 200ms linear; -moz-transition: background-color 200ms linear; -o-transition: background-color 200ms linear; -ms-transition: background-color 200ms linear; transition: background-color 200ms linear; } .container { clear: both; width: 100%; text-align: center; padding-top: 20px; } canvas { background-color: #ffffff; margin: 0px auto; display: block; border-width: 1px; border-color: #bbbbbb; border-style: solid; } footer { margin-top: 12px; text-align: center; }
18.279412
54
0.622687
0f7ca8f374e08b078841d3094735747db05b770c
11,759
hpp
C++
examples/CBuilder/Compound/Conway/ConwayClasses.hpp
LenakeTech/BoldForDelphi
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
[ "MIT" ]
121
2020-09-22T10:46:20.000Z
2021-11-17T12:33:35.000Z
examples/CBuilder/Compound/Conway/ConwayClasses.hpp
LenakeTech/BoldForDelphi
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
[ "MIT" ]
8
2020-09-23T12:32:23.000Z
2021-07-28T07:01:26.000Z
examples/CBuilder/Compound/Conway/ConwayClasses.hpp
LenakeTech/BoldForDelphi
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
[ "MIT" ]
42
2020-09-22T14:37:20.000Z
2021-10-04T10:24:12.000Z
/*****************************************/ /* This file is autogenerated */ /* Any manual changes will be LOST! */ /*****************************************/ /* Generated 2001-12-03 17:20:19 */ /*****************************************/ /* This file should be stored in the */ /* same directory as the form/datamodule */ /* with the corresponding model */ /*****************************************/ /* Copyright notice: */ /* */ /*****************************************/ #if !defined (ConwayClasses_HPP) #define ConwayClasses_HPP // interface uses #include "Windows.hpp" // interface dependancies // attribute dependancies #include "BoldAttributes.hpp" #include <Classes.hpp> #include <Controls.hpp> #include <SysUtils.hpp> #include "BoldDefs.hpp" #include "BoldSubscription.hpp" #include "BoldDeriver.hpp" #include "BoldElements.hpp" #include "BoldDomainElement.hpp" #include "BoldSystemRT.hpp" #include "BoldSystem.hpp" #include "BoldReferenceHandle.hpp" #include "BoldCheckBox.hpp" #include "Dialogs.hpp" #include "Forms.hpp" #include "BoldQueue.hpp" void unregisterCode(); // forward declarations of all classes } class TBusinessClassesRoot; class TBusinessClassesRootList; class TCell; class TCellList; class TGame; class TGameList; class DELPHICLASS TBusinessClassesRoot; class TBusinessClassesRoot : public Boldsystem::TBoldObject { typedef Boldsystem::TBoldObject inherited; private: protected: public: #pragma option push -w-inl inline __fastcall TBusinessClassesRoot(Boldsystem::TBoldSystem* aBoldSystem) : Boldsystem::TBoldObject(aBoldSystem, true) { } #pragma option pop }; class DELPHICLASS TCell; class TCell : public TBusinessClassesRoot { typedef TBusinessClassesRoot inherited; private: Boolean fIntermediate; Boolean fNeighboursEnsured; TBABoolean* __fastcall _Get_M_Active(); Boolean __fastcall _GetActive(); void __fastcall _SetActive(Boolean NewValue); TBAInteger* __fastcall _Get_M_neighbours(); Integer __fastcall _Getneighbours(); TBAInteger* __fastcall _Get_M_x(); Integer __fastcall _Getx(); void __fastcall _Setx(Integer NewValue); TBAInteger* __fastcall _Get_M_y(); Integer __fastcall _Gety(); void __fastcall _Sety(Integer NewValue); TBAInteger* __fastcall _Get_M_ActiveCount(); Integer __fastcall _GetActiveCount(); TGame* __fastcall _GetGame(); TBoldObjectReference* __fastcall _Get_M_Game(); void __fastcall _SetGame(TGame *value); TCell* __fastcall _GetcLeft(); TBoldObjectReference* __fastcall _Get_M_cLeft(); void __fastcall _SetcLeft(TCell *value); TCell* __fastcall _GetcRight(); TBoldObjectReference* __fastcall _Get_M_cRight(); void __fastcall _SetcRight(TCell *value); TCell* __fastcall _GetcDown(); TBoldObjectReference* __fastcall _Get_M_cDown(); void __fastcall _SetcDown(TCell *value); TCell* __fastcall _GetcUp(); TBoldObjectReference* __fastcall _Get_M_cUp(); void __fastcall _SetcUp(TCell *value); TCell* __fastcall _GetcDownLeft(); TBoldObjectReference* __fastcall _Get_M_cDownLeft(); void __fastcall _SetcDownLeft(TCell *value); TCell* __fastcall _GetcUpRight(); TBoldObjectReference* __fastcall _Get_M_cUpRight(); void __fastcall _SetcUpRight(TCell *value); TCell* __fastcall _GetcDownRight(); TBoldObjectReference* __fastcall _Get_M_cDownRight(); void __fastcall _SetcDownRight(TCell *value); TCell* __fastcall _GetcUpLeft(); TBoldObjectReference* __fastcall _Get_M_cUpLeft(); void __fastcall _SetcUpLeft(TCell *value); void __fastcall UnensureNeighbours(void); __property TBAInteger* M_ActiveCount = {read=_Get_M_ActiveCount}; __property Integer ActiveCount = {read=_GetActiveCount}; __property Boolean Intermediate = { read=fIntermediate, write=fIntermediate}; protected: __property TBAInteger* M_neighbours = {read=_Get_M_neighbours}; __property Integer neighbours = {read=_Getneighbours}; __property Boolean NeighboursEnsured = { read=fNeighboursEnsured, write=fNeighboursEnsured}; public: #pragma option push -w-inl inline __fastcall TCell(Boldsystem::TBoldSystem* aBoldSystem) : TBusinessClassesRoot(aBoldSystem) { } #pragma option pop void __fastcall CalculateIntermediate(void); void __fastcall UpdateActive(void); void __fastcall SetupCell(Integer x, Integer y); TCell* __fastcall EnsureCell(TCell* aCell, Integer x, Integer y); boolean __fastcall AllowRemove(void); void __fastcall PrepareDelete(void); void __fastcall NeighboursNotEnsured(void); void __fastcall UnensureCell(TCell* aCell); void __fastcall EnsureNeighbours(void); __property TBABoolean* M_Active = {read=_Get_M_Active}; __property TBAInteger* M_x = {read=_Get_M_x}; __property TBAInteger* M_y = {read=_Get_M_y}; __property TBoldObjectReference* M_Game = {read=_Get_M_Game}; __property TBoldObjectReference* M_cLeft = {read=_Get_M_cLeft}; __property TBoldObjectReference* M_cRight = {read=_Get_M_cRight}; __property TBoldObjectReference* M_cDown = {read=_Get_M_cDown}; __property TBoldObjectReference* M_cUp = {read=_Get_M_cUp}; __property TBoldObjectReference* M_cDownLeft = {read=_Get_M_cDownLeft}; __property TBoldObjectReference* M_cUpRight = {read=_Get_M_cUpRight}; __property TBoldObjectReference* M_cDownRight = {read=_Get_M_cDownRight}; __property TBoldObjectReference* M_cUpLeft = {read=_Get_M_cUpLeft}; __property Boolean Active = {read=_GetActive, write=_SetActive}; __property Integer x = {read=_Getx, write=_Setx}; __property Integer y = {read=_Gety, write=_Sety}; __property TGame* Game = {read=_GetGame, write=_SetGame}; __property TCell* cLeft = {read=_GetcLeft, write=_SetcLeft}; __property TCell* cRight = {read=_GetcRight, write=_SetcRight}; __property TCell* cDown = {read=_GetcDown, write=_SetcDown}; __property TCell* cUp = {read=_GetcUp, write=_SetcUp}; __property TCell* cDownLeft = {read=_GetcDownLeft, write=_SetcDownLeft}; __property TCell* cUpRight = {read=_GetcUpRight, write=_SetcUpRight}; __property TCell* cDownRight = {read=_GetcDownRight, write=_SetcDownRight}; __property TCell* cUpLeft = {read=_GetcUpLeft, write=_SetcUpLeft}; }; class DELPHICLASS TGame; class TGame : public TBusinessClassesRoot { typedef TBusinessClassesRoot inherited; private: Integer fInactiveCount; TBAInteger* __fastcall _Get_M_TimerTime(); Integer __fastcall _GetTimerTime(); void __fastcall _SetTimerTime(Integer NewValue); TBAInteger* __fastcall _Get_M_Generations(); Integer __fastcall _GetGenerations(); void __fastcall _SetGenerations(Integer NewValue); TBABlob* __fastcall _Get_M_board(); String __fastcall _Getboard(); void __fastcall _Setboard(String NewValue); TBAInteger* __fastcall _Get_M_xMax(); Integer __fastcall _GetxMax(); void __fastcall _SetxMax(Integer NewValue); TBAInteger* __fastcall _Get_M_xMin(); Integer __fastcall _GetxMin(); void __fastcall _SetxMin(Integer NewValue); TBAInteger* __fastcall _Get_M_yMax(); Integer __fastcall _GetyMax(); void __fastcall _SetyMax(Integer NewValue); TBAInteger* __fastcall _Get_M_yMin(); Integer __fastcall _GetyMin(); void __fastcall _SetyMin(Integer NewValue); TBAInteger* __fastcall _Get_M_xSize(); Integer __fastcall _GetxSize(); TBAInteger* __fastcall _Get_M_FontSize(); Integer __fastcall _GetFontSize(); void __fastcall _SetFontSize(Integer NewValue); TBABoolean* __fastcall _Get_M_collecting(); Boolean __fastcall _Getcollecting(); void __fastcall _Setcollecting(Boolean NewValue); TCellList* __fastcall _GetCell(); TCellList* __fastcall _Getcoord(); TCell* __fastcall _Get_Q_coord(Integer x, Integer y); void __fastcall RefreshBounds(void); TRect __fastcall GetBounds(void); protected: virtual void __fastcall _board_DeriveAndSubscribe(TObject *DerivedObject, TBoldSubscriber *Subscriber); virtual void __fastcall _board_ReverseDerive(TObject *DerivedObject); virtual TBoldDeriveAndResubscribe __fastcall GetDeriveMethodForMember(TBoldMember *Member); virtual TBoldReverseDerive __fastcall GetReverseDeriveMethodForMember(TBoldMember *Member); public: #pragma option push -w-inl inline __fastcall TGame(Boldsystem::TBoldSystem* aBoldSystem) : TBusinessClassesRoot(aBoldSystem) { } #pragma option pop void __fastcall Tick(void); void __fastcall ClearCells(void); void __fastcall UpdateBounds(Integer x, Integer y); void __fastcall GarbageCollect(void); void __fastcall ResetBounds(void); __property TBAInteger* M_TimerTime = {read=_Get_M_TimerTime}; __property TBAInteger* M_Generations = {read=_Get_M_Generations}; __property TBABlob* M_board = {read=_Get_M_board}; __property TBAInteger* M_xMax = {read=_Get_M_xMax}; __property TBAInteger* M_xMin = {read=_Get_M_xMin}; __property TBAInteger* M_yMax = {read=_Get_M_yMax}; __property TBAInteger* M_yMin = {read=_Get_M_yMin}; __property TBAInteger* M_xSize = {read=_Get_M_xSize}; __property TBAInteger* M_FontSize = {read=_Get_M_FontSize}; __property TBABoolean* M_collecting = {read=_Get_M_collecting}; __property TCellList* M_Cell = {read=_GetCell}; __property TCellList* M_coord = {read=_Getcoord}; __property Integer TimerTime = {read=_GetTimerTime, write=_SetTimerTime}; __property Integer Generations = {read=_GetGenerations, write=_SetGenerations}; __property String board = {read=_Getboard, write=_Setboard}; __property Integer xMax = {read=_GetxMax, write=_SetxMax}; __property Integer xMin = {read=_GetxMin, write=_SetxMin}; __property Integer yMax = {read=_GetyMax, write=_SetyMax}; __property Integer yMin = {read=_GetyMin, write=_SetyMin}; __property Integer xSize = {read=_GetxSize}; __property Integer FontSize = {read=_GetFontSize, write=_SetFontSize}; __property Boolean collecting = {read=_Getcollecting, write=_Setcollecting}; __property TCellList* Cell = {read=_GetCell}; __property TCell* coord[Integer x][Integer y] = {read=_Get_Q_coord}; __property Integer InactiveCount = { read=fInactiveCount, write=fInactiveCount}; }; class DELPHICLASS TBusinessClassesRootList; class TBusinessClassesRootList : public TBoldObjectList { protected: TBusinessClassesRoot* __fastcall GetBoldObject(int index); void __fastcall SetBoldObject(int index, TBusinessClassesRoot *NewObject); public: int __fastcall Includes(TBusinessClassesRoot *anObject); int __fastcall IndexOf(TBusinessClassesRoot *anObject); void __fastcall Add(TBusinessClassesRoot *NewObject); TBusinessClassesRoot* __fastcall AddNew(); void __fastcall Insert(int index, TBusinessClassesRoot *NewObject); __property TBusinessClassesRoot* BoldObjects[int index] = {read=GetBoldObject, write=SetBoldObject}; }; class DELPHICLASS TCellList; class TCellList : public TBusinessClassesRootList { protected: TCell* __fastcall GetBoldObject(int index); void __fastcall SetBoldObject(int index, TCell *NewObject); public: int __fastcall Includes(TCell *anObject); int __fastcall IndexOf(TCell *anObject); void __fastcall Add(TCell *NewObject); TCell* __fastcall AddNew(); void __fastcall Insert(int index, TCell *NewObject); __property TCell* BoldObjects[int index] = {read=GetBoldObject, write=SetBoldObject}; }; class DELPHICLASS TGameList; class TGameList : public TBusinessClassesRootList { protected: TGame* __fastcall GetBoldObject(int index); void __fastcall SetBoldObject(int index, TGame *NewObject); public: int __fastcall Includes(TGame *anObject); int __fastcall IndexOf(TGame *anObject); void __fastcall Add(TGame *NewObject); TGame* __fastcall AddNew(); void __fastcall Insert(int index, TGame *NewObject); __property TGame* BoldObjects[int index] = {read=GetBoldObject, write=SetBoldObject}; }; char* GeneratedCodeCRC(); #endif
39.996599
127
0.764691
5fa229481f348ada6d1e9cdf39b790c01fca23ee
1,639
dart
Dart
lib/domain/shared/value_objects/month.dart
KiritchoukC/power_progress
2e58821d15b6cf57a92c070337fe559bc0127364
[ "MIT" ]
4
2020-04-29T18:27:19.000Z
2020-10-12T16:02:10.000Z
lib/domain/shared/value_objects/month.dart
KiritchoukC/power_progress
2e58821d15b6cf57a92c070337fe559bc0127364
[ "MIT" ]
61
2020-04-16T19:50:58.000Z
2020-08-25T13:45:02.000Z
lib/domain/shared/value_objects/month.dart
KiritchoukC/power_progress
2e58821d15b6cf57a92c070337fe559bc0127364
[ "MIT" ]
1
2020-05-24T16:12:45.000Z
2020-05-24T16:12:45.000Z
import 'package:dartz/dartz.dart'; import 'package:power_progress/core/domain/value_failure.dart'; import 'package:power_progress/core/domain/value_object.dart'; class Month extends ValueObject<int> { @override final Either<ValueFailure<int>, int> value; factory Month(int input) { assert(input != null); return Month._( validateMonth(input), ); } factory Month.parse(String input) { assert(input != null); return Month._( parseAndvalidateMonth(input), ); } const Month._(this.value); int get moduloMonthNumber { final monthNumber = getOrCrash(); if (monthNumber <= 4) return monthNumber; final result = monthNumber % 4; if (result == 0) return 4; return result; } bool get isStartWorkout { final monthNumber = getOrCrash(); if (monthNumber == 1) return false; if ((monthNumber - 1) % 4 == 0) return true; return false; } Month get previous => Month(getOrCrash() - 1); Month get next => Month(getOrCrash() + 1); } Either<ValueFailure<int>, int> parseAndvalidateMonth(String input) { if (input.trim().isEmpty) { return left(const ValueFailure.empty()); } final parsed = int.tryParse(input); if (parsed == null) { return left(ValueFailure.notANumber(failedValue: input)); } return validateMonth(parsed); } Either<ValueFailure<int>, int> validateMonth(int input) { if (input <= 0) { return left(ValueFailure.numberUnderZero(failedValue: input)); } const max = 100; if (input > max) { return left(ValueFailure.numberTooLarge(failedValue: input, max: max)); } return right(input); }
20.746835
75
0.66626
cad6f4e0a5d15fcdd37bc69787703951bc78eb34
154
asm
Assembly
libsrc/_DEVELOPMENT/arch/ts2068/display/c/sccz80/tshc_px2bitmask.asm
jpoikela/z88dk
7108b2d7e3a98a77de99b30c9a7c9199da9c75cb
[ "ClArtistic" ]
38
2021-06-18T12:56:15.000Z
2022-03-12T20:38:40.000Z
libsrc/_DEVELOPMENT/arch/ts2068/display/c/sccz80/tshc_px2bitmask.asm
jpoikela/z88dk
7108b2d7e3a98a77de99b30c9a7c9199da9c75cb
[ "ClArtistic" ]
2
2021-06-20T16:28:12.000Z
2021-11-17T21:33:56.000Z
libsrc/_DEVELOPMENT/arch/ts2068/display/c/sccz80/tshc_px2bitmask.asm
jpoikela/z88dk
7108b2d7e3a98a77de99b30c9a7c9199da9c75cb
[ "ClArtistic" ]
6
2021-06-18T18:18:36.000Z
2021-12-22T08:01:32.000Z
; uchar tshc_px2bitmask(uchar x) SECTION code_clib SECTION code_arch PUBLIC tshc_px2bitmask EXTERN zx_px2bitmask defc tshc_px2bitmask = zx_px2bitmask
14
36
0.844156
f98d084d90bb13d118391f02ecdfeac62e69683f
1,322
go
Go
acaseSts/admunit2request.go
tmconsulting/acase-golang-sdk
22fe2ff6e573dc8fd130651d606bb61a8bfc6c93
[ "MIT" ]
4
2018-01-10T09:25:31.000Z
2018-05-16T15:15:13.000Z
acaseSts/admunit2request.go
tmconsulting/acase-golang-sdk
22fe2ff6e573dc8fd130651d606bb61a8bfc6c93
[ "MIT" ]
null
null
null
acaseSts/admunit2request.go
tmconsulting/acase-golang-sdk
22fe2ff6e573dc8fd130651d606bb61a8bfc6c93
[ "MIT" ]
null
null
null
package acaseSts import "encoding/xml" type AdmUnit2RequestType struct { Credentials XMLName xml.Name `xml:"AdmUnit2Request"` Action AdmUnit2ActionType `xml:"Action"` } type AdmUnit2ActionType struct { XMLName xml.Name `xml:"Action"` Name AdmUnitActionNameEnum `xml:"Name,attr"` Parameters AdmUnit2ActionTypeParameters `xml:"Parameters"` } type AdmUnit2ActionTypeParameters struct { CountryCode int `xml:"CountryCode,attr"` AdmUnit1Code int `xml:"AdmUnit1Code,attr,omitempty"` AdmUnit1Name string `xml:"AdmUnit1Name,attr,omitempty"` AdmUnit2Code int `xml:"AdmUnit2Code,attr,omitempty"` AdmUnit2Name string `xml:"AdmUnit2Name,attr,omitempty"` } type AdmUnit2ResponseType struct { Credentials BaseResponse XMLName xml.Name `xml:"AdmUnit2Response"` Action AdmUnit2ActionType `xml:"Action,omitempty"` AdmUnit2List AdmUnit2ListType `xml:"AdmUnit2List,omitempty"` } type AdmUnit2ListType struct { XMLName xml.Name `xml:"AdmUnit2List",json:"-"` AdmUnit2 []AdmUnit2Type `xml:"AdmUnit2",json:"adm_unit_2"` } type AdmUnit2Type struct { AdmUnit1 SimpleCodeNameType `xml:"AdmUnit1",json:"adm_unit_1"` Code int `xml:"Code,attr",json:"code"` Name string `xml:"Name,attr",json:"name"` }
30.744186
63
0.707262
72be8aad2f9795d5d464bbb45e88ebc68213a278
3,477
rs
Rust
src/widget/plot_path.rs
zummenix/conrod
0c9133757eb20e5e5e81ec7c9efeb6695f3a93b9
[ "Apache-2.0", "MIT" ]
null
null
null
src/widget/plot_path.rs
zummenix/conrod
0c9133757eb20e5e5e81ec7c9efeb6695f3a93b9
[ "Apache-2.0", "MIT" ]
null
null
null
src/widget/plot_path.rs
zummenix/conrod
0c9133757eb20e5e5e81ec7c9efeb6695f3a93b9
[ "Apache-2.0", "MIT" ]
null
null
null
use { Backend, Color, Colorable, PointPath, Positionable, Scalar, Sizeable, Widget, }; use num; use utils; use widget; /// A widget that plots a series of lines using the given function *x -> y*. /// /// The function is sampled once per pixel and the result is mapped to the widget's height. /// /// The resulting "path" is drawn using conrod's `PointPath` primitive widget. pub struct PlotPath<X, Y, F> { common: widget::CommonBuilder, style: Style, min_x: X, max_x: X, min_y: Y, max_y: Y, f: F, } /// The unique `WidgetKind` for the `PlotPath`. pub const KIND: widget::Kind = "PlotPath"; widget_style!{ KIND; /// Unique styling parameters for the `PlotPath` widget. style Style { /// The thickness of the plotted line. - thickness: Scalar { 1.0 } /// The color of the line. - color: Color { theme.shape_color } } } /// Unique state stored between updates for the `PlotPath` widget. #[derive(Debug, PartialEq)] pub struct State { point_path_idx: widget::IndexSlot, } impl<X, Y, F> PlotPath<X, Y, F> { /// Begin building a new `PlotPath` widget instance. pub fn new(min_x: X, max_x: X, min_y: Y, max_y: Y, f: F) -> Self { PlotPath { common: widget::CommonBuilder::new(), style: Style::new(), min_x: min_x, max_x: max_x, min_y: min_y, max_y: max_y, f: f, } } } impl<X, Y, F> Widget for PlotPath<X, Y, F> where X: num::NumCast + Clone, Y: num::NumCast + Clone, F: FnMut(X) -> Y, { type State = State; type Style = Style; fn common(&self) -> &widget::CommonBuilder { &self.common } fn common_mut(&mut self) -> &mut widget::CommonBuilder { &mut self.common } fn unique_kind(&self) -> widget::Kind { KIND } fn init_state(&self) -> Self::State { State { point_path_idx: widget::IndexSlot::new(), } } fn style(&self) -> Self::Style { self.style.clone() } /// Update the state of the PlotPath. fn update<B: Backend>(self, args: widget::UpdateArgs<Self, B>) { let widget::UpdateArgs { idx, state, style, rect, mut ui, .. } = args; let PlotPath { min_x, max_x, min_y, max_y, mut f, .. } = self; let y_to_scalar = |y| utils::map_range(y, min_y.clone(), max_y.clone(), rect.bottom(), rect.top()); let scalar_to_x = |s| utils::map_range(s, rect.left(), rect.right(), min_x.clone(), max_x.clone()); let point_iter = (0 .. rect.w() as usize) .map(|x_scalar| { let x_scalar = x_scalar as Scalar + rect.x.start; let x = scalar_to_x(x_scalar); let y = f(x); let y_scalar = y_to_scalar(y); [x_scalar, y_scalar] }); let point_path_idx = state.point_path_idx.get(&mut ui); let thickness = style.thickness(ui.theme()); let color = style.color(ui.theme()); PointPath::new(point_iter) .wh(rect.dim()) .xy(rect.xy()) .color(color) .thickness(thickness) .parent(idx) .graphics_for(idx) .set(point_path_idx, &mut ui); } } impl<X, Y, F> Colorable for PlotPath<X, Y, F> { builder_method!(color { style.color = Some(Color) }); }
25.379562
93
0.548749
8091e186000d49f42a12030d82957208f1ae822a
1,432
java
Java
plugins/com.ibm.socialcrm.notesintegration.utils/src/com/ibm/socialcrm/notesintegration/utils/datahub/LoadableSFADataShare.java
Bhaskers-Blu-Org1/sugarcrm-lotusnotes-connector
872cc35f224df2426a8367912b0dba34d79a3fda
[ "Apache-2.0" ]
1
2020-12-03T03:21:42.000Z
2020-12-03T03:21:42.000Z
plugins/com.ibm.socialcrm.notesintegration.utils/src/com/ibm/socialcrm/notesintegration/utils/datahub/LoadableSFADataShare.java
IBM/sugarcrm-lotusnotes-connector
5c0e41845bd280364ebf91e58f0c4be405257217
[ "Apache-2.0" ]
null
null
null
plugins/com.ibm.socialcrm.notesintegration.utils/src/com/ibm/socialcrm/notesintegration/utils/datahub/LoadableSFADataShare.java
IBM/sugarcrm-lotusnotes-connector
5c0e41845bd280364ebf91e58f0c4be405257217
[ "Apache-2.0" ]
2
2019-11-04T13:19:33.000Z
2020-06-29T14:04:20.000Z
package com.ibm.socialcrm.notesintegration.utils.datahub; /**************************************************************** * IBM OpenSource * * (C) Copyright IBM Corp. 2012 * * Licensed under the Apache License v2.0 * http://www.apache.org/licenses/LICENSE-2.0 * ***************************************************************/ /** * Adds the ability of a datashare to be loaded from an external source. * */ public class LoadableSFADataShare<KEY_TYPE extends Object, VALUE_TYPE extends Object, LOAD_TYPE extends Object> extends SFADataShare { /** * Indicates if the data share has been loaded */ private boolean loaded = false; public LoadableSFADataShare(String name) { super(name); } /** * Initiates the load of a data share from a given object. * * @param initialObject * @return */ public final boolean loadDataShare(LOAD_TYPE initialObject) { setLoaded(false); boolean success = doLoad(initialObject); setLoaded(true); return success; } /** * Loads a data share from the given object. Subclasses should override if they wish to provide an actual implementation. * * @param initialObject * @return success of the operation */ protected boolean doLoad(LOAD_TYPE initialObject) { // Subclasses should override as necessary return true; } public boolean isLoaded() { return loaded; } private void setLoaded(boolean loaded) { this.loaded = loaded; } }
23.866667
134
0.652933
807abadbac0c8612e2f9440aa9523ad191cff2d5
24,562
java
Java
applet/dp/revisedSimplex.java
unalozden/unalozden.github.io
472fe1e6e98812af266139e35721354071ca29f6
[ "MIT" ]
null
null
null
applet/dp/revisedSimplex.java
unalozden/unalozden.github.io
472fe1e6e98812af266139e35721354071ca29f6
[ "MIT" ]
null
null
null
applet/dp/revisedSimplex.java
unalozden/unalozden.github.io
472fe1e6e98812af266139e35721354071ca29f6
[ "MIT" ]
null
null
null
/* * * Revised by Yu WEI * Summer 2004 * email: weiy3@mcmaster.ca * * Written by Timothy J. Wisniewski * Summer 1996 * email: tjw@euler.bd.psu.edu * * Updated by Joe Czyzyk * September - October 1996 * * Copyright 2004 Optimization Technology Center * */ import java.awt.*; import java.lang.Math; public class revisedSimplex { public int numVariables; public int numConstraints; public int numNonbasic; public int numConstraintsSoFar = 0; public int CurrentStep = 0; public int NumIterations = 0; public int NumArtificials; private int i,j,k,l; /* Index Variables */ public float [] reducedCost; public float [] cost; public float [] x; public float [] pi; public float [] yB; public float MinRatio; public int NumMinRatio; public Matrix Bt; public Matrix B; /* littleCost is the cost of the BasicVariables */ public float [] littleCost; public float objectiveValue = 0; public float [][] A; public float [] b; public int [] constraintType; public int [] BasicVariables; public int [] NonBasicVariables; public int [] varType; public float [] colOfA; int[] perm; /* used only in AugmentBasis */ public int EnteringVariable; public int LeavingVariable; public boolean TypeMinimize; boolean ArtificialAdded = false; public final static int LessThan = 0; public final static int GreaterThan = 1; public final static int EqualTo = 2; public final static int Continue = 0; public final static int Optimal = 1; public final static int Feasible = 2; public final static int Unbounded = 3; public final static int Regular = 0; public final static int SlackOrSurplus = 1; public final static int Artificial = 2; public final static int BasicType = 1; public final static int NonBasicType = 2; /* variables for two phase part */ boolean oldOptType; float OriginalCost[]; public revisedSimplex(int nv, int nc) { numVariables = nv; numConstraints = nc; NumArtificials = 0; reducedCost = new float [nv + 2*nc]; cost = new float [nv + 2*nc]; OriginalCost = new float [nv + 2*nc]; x = new float [nc]; pi = new float [nc]; yB = new float [nc]; littleCost = new float [nc]; A = new float [nc][nv + 3*nc]; b = new float [nc]; constraintType = new int [nc]; BasicVariables = new int [nc]; NonBasicVariables = new int [nv + 2*nc]; varType = new int [nv + 2*nc]; colOfA = new float[nc]; Bt = new Matrix(nc); B = new Matrix(nc); } /* end revisedSimplex procedure */ public int iterateOneStep() { switch (CurrentStep) { case 0: /* upate B */ NumIterations++; this.makeBt(); this.makeB(); CurrentStep = 1; return Continue; case 1: /* update pi*/ Bt.solve(pi,littleCost); CurrentStep = 2; return Continue; case 2: /* calculate reduced costs */ this.calculateReducedCosts(); CurrentStep = 3; return Continue; case 3: /* test for optimality */ if(this.testForOptimality()) { CurrentStep = 12; return Optimal; } else { CurrentStep = 4; this.ChooseEnteringVariable(); return Continue; } case 4: /* Get user's input for entering variable */ CurrentStep = 5; return Continue; case 5: /* update yB */ /* make the column of A what we want */ for (int i = 0; i < numConstraints; i++) colOfA[i] = A[i][NonBasicVariables[EnteringVariable]]; B.solve(yB,colOfA); CurrentStep = 6; return Continue; case 6: /* test for unboundedness */ if (this.testUnboundedness()) { CurrentStep = 7; return Unbounded; /* The problem is unbounded. */ } else CurrentStep = 8; return Continue; case 7: /* This statement is never reached */ case 8: /* choose leaving variable */ chooseLeavingVariable(); if (NumMinRatio == 1) CurrentStep = 11; else /* tie for minimum ratio */ CurrentStep = 9; return Continue; case 9: /* get user's selection */ CurrentStep = 10; return Continue; case 10: /* do nothing -- print leaving variable in tool */ CurrentStep = 11; return Continue; case 11: /* Update solution */ this.updateSolution(); objectiveValue = this.calculateObjective(); CurrentStep = 0; /* start over */ return Continue; /* We can keep going/! */ case 12: /* found optimal solution */ objectiveValue = this.calculateObjective(); return Optimal; } return 4; /* this will never happen */ } /* end iterateOneStep procedure */ public int iterate() { /* Perform all the steps of one iteration */ NumIterations++; this.makeBt(); Bt.solve(pi,littleCost); this.calculateReducedCosts(); if (!this.testForOptimality()) { this.ChooseEnteringVariable(); } else { objectiveValue = this.calculateObjective(); return Optimal; /* We found the optimal solution!! */ } this.makeB(); /* make the column of A what we want */ for (int i = 0; i < numConstraints; i++) colOfA[i] = A[i][NonBasicVariables[EnteringVariable]]; B.solve(yB,colOfA); if (!this.testUnboundedness()) { this.chooseLeavingVariable(); this.updateSolution(); return Continue; /* We can keep going/! */ } else return Unbounded; /* The problem is unbounded. */ } /* end iterate procedure */ public float calculateObjective() { float value = 0; if (TypeMinimize == true) for (int i = 0; i < numConstraints; i++) value += (x[i] * cost[BasicVariables[i]]); else for (int i = 0; i < numConstraints; i++) value -= (x[i] * cost[BasicVariables[i]]); return value; } /* end calculateObjective procedure */ public void chooseLeavingVariable() { float Ratio; int minIndex = -1; NumMinRatio = 0; /* MinRatio = 1000000; */ for (i = 0; i < numConstraints; i++) { if (yB[i] > 0) { Ratio = x[i]/yB[i]; if (NumMinRatio == 0) { MinRatio = Ratio; minIndex = i; NumMinRatio = 1; } else if (Ratio < MinRatio) { MinRatio = Ratio; minIndex = i; NumMinRatio = 1; } else if (Ratio == MinRatio) NumMinRatio++; } } LeavingVariable = minIndex; } /* end chooseLeavingVariable procedure */ /* SJW 9/14/99: merge the former "updateSolution" with the former "changeBasis"; call the merged entity "updateSolution" */ public void updateSolution() { int tmp; for (i = 0; i < numConstraints; i++) x[i] -= (MinRatio*yB[i]); x[LeavingVariable] = MinRatio; if (varType[BasicVariables[LeavingVariable]] == Artificial) NumArtificials--; if(varType[NonBasicVariables[EnteringVariable]] == Artificial) NumArtificials++; tmp = BasicVariables[LeavingVariable]; BasicVariables[LeavingVariable] = NonBasicVariables[EnteringVariable]; NonBasicVariables[EnteringVariable] = tmp; } /* end updateSolution procedure */ public void ChooseEnteringVariable() { int minIndex = 0; float minValue = 100000; /* Actually any variable with a negative reduced cost will work. * We choose the variable with lowest reduced cost to enter. * (The user can choose a different entering variable.) */ for (i = 0; i < numNonbasic;i++) if (reducedCost[i] < 0 && reducedCost[i] < minValue) { minIndex = i; minValue = reducedCost[i]; } EnteringVariable = minIndex; } /* end pickEnteringVariable procedure */ public boolean testUnboundedness() { boolean isUnbounded = true; /* Problem is unbounded if yB > 0 in all elements */ for (i = 0; i < numConstraints; i++) if (yB[i] > 0) { isUnbounded = false; break; } return isUnbounded; } /* end testUnboundedness procedure */ public void calculateReducedCosts() { for (i = 0; i < numNonbasic; i++) { for (j = 0; j < numConstraints; j++) colOfA[j] = A[j][NonBasicVariables[i]]; reducedCost[i] = cost[NonBasicVariables[i]] - this.Dot(pi,colOfA,numConstraints); } } /* end calculateReducedCosts procedure */ public boolean testForOptimality() { boolean isOptimal = true; for (int i = 0; i < numNonbasic; i++) if (reducedCost[i] < 0) { isOptimal = false; return isOptimal; /* false */ } return isOptimal; /* true */ } /* end testForOptimality procedure */ private void makeBt() { for (i = 0; i < numConstraints; i++) { littleCost[i] = cost[BasicVariables[i]]; for (j = 0; j < numConstraints; j++) Bt.A[i][j] = A[j][BasicVariables[i]]; } } /* end makeBt procedure */ private void makeB() { for (i = 0; i < numConstraints; i++) for (j = 0; j < numConstraints; j++) B.A[i][j] = A[i][BasicVariables[j]]; } /* end makeB procedure */ public void addConstraint(float [] coefficients, float rhs, int type) { for (i = 0; i < numVariables; i++) { A[numConstraintsSoFar][i] = coefficients[i]; } x[numConstraintsSoFar] = rhs; b[numConstraintsSoFar] = rhs; constraintType[numConstraintsSoFar] = type; numConstraintsSoFar++; } /* end addConstraint procedure */ public void specifyObjective(float [] coefficients, boolean type) { for (i = 0; i < numVariables; i++) cost[i] = coefficients[i]; TypeMinimize = type; } /* end specifyObjective procedure */ public boolean preprocess(int numberOfVariables, int numberOfConstraints) { int LastCol, NextNonBasic; int[] ConstraintVariable = new int[numberOfConstraints]; int slack; int surplus; oldOptType = TypeMinimize; LastCol = numberOfVariables; if (TypeMinimize == false) /* switch sign for maximize */ for (i = 0; i < LastCol; i++) cost[i] *= -1; for (i = 0; i < LastCol; i++) NonBasicVariables[i] = i; NextNonBasic = LastCol; /* Add slacks and surplus first, this is slower but it makes * displaying a lot easier for two phase problems. * Keep track of which variable was added for each constraint. */ for (i = 0; i < numberOfConstraints; i++) switch (constraintType[i]) { case LessThan: A[i][LastCol] = 1; cost[LastCol] = 0; varType[LastCol] = SlackOrSurplus; ConstraintVariable[i] = LastCol; LastCol++; break; case GreaterThan: A[i][LastCol] = -1; cost[LastCol] = 0; varType[LastCol] = SlackOrSurplus; ConstraintVariable[i] = LastCol; LastCol++; break; case EqualTo: /* do nothing */ } /* end switch */ /* Add artificial variables if necessary, Assign basis */ for (i = 0; i < numberOfConstraints; i++) switch(constraintType[i]) { case GreaterThan: if (b[i] > 0) { /* Add artificial variable, make basic */ A[i][LastCol] = 1; x[i] = b[i]; varType[LastCol] = Artificial; ArtificialAdded = true; BasicVariables[i] = LastCol; /* surplus not basic */ surplus = ConstraintVariable[i]; NonBasicVariables[NextNonBasic] = surplus; /* increment counter */ NextNonBasic++; LastCol++; NumArtificials++; } else { /* make surplus variable basic */ BasicVariables[i] = ConstraintVariable[i]; x[i] = -b[i]; } break; case EqualTo: /* add artificial variable, make basic */ if (b[i] >= 0) { A[i][LastCol] = 1; x[i] = b[i]; } else { /* b[i] < 0 */ A[i][LastCol] = -1; x[i] = -b[i]; } varType[LastCol] = Artificial; ArtificialAdded = true; BasicVariables[i] = LastCol; LastCol++; NumArtificials++; break; case LessThan: if (b[i] >= 0) { /* make slack variable basic */ BasicVariables[i] = ConstraintVariable[i]; x[i] = b[i]; } else { /* b[i] < 0 */ /* add artificial variable, make basic */ A[i][LastCol] = -1; x[i] = -b[i]; varType[LastCol] = Artificial; ArtificialAdded = true; BasicVariables[i] = LastCol; /* slack not basic */ slack = ConstraintVariable[i]; NonBasicVariables[NextNonBasic] = slack; /* increment counter */ NextNonBasic++; LastCol++; NumArtificials++; } break; } numNonbasic = LastCol - numConstraints; numVariables = LastCol; if (NumArtificials > 0) this.SetCostForPhaseOne(); return true; } /* end preprocess procedure */ /* SetCostForPhaseOne sets feasibility cost function. * Run getRidOfArtificials after the problem has been solved. */ public void SetCostForPhaseOne() { float newCoefficients [] = new float [numVariables]; /* Set the coefficients of the objective */ for (int i = 0; i < numVariables; i++) { OriginalCost[i] = cost[i]; if (varType[i] == Artificial) newCoefficients[i] = 1; else newCoefficients[i] = 0; } this.specifyObjective(newCoefficients, true); /* minimize */ } /* end SetCostForPhaseOne procedure */ public void getRidOfArtificials() { int LastBasic = 0; int LastNonBasic = 0; int CountArtificials = 0; int ArtificialsInBasis; int[] BasisType = new int [numVariables]; float[] TempX = new float [numVariables]; int i; /* Build index of variable type */ for (i = 0; i < numNonbasic; i++) BasisType[NonBasicVariables[i]] = NonBasicType; for (i = 0; i < numConstraints; i++) { BasisType[BasicVariables[i]] = BasicType; TempX[BasicVariables[i]] = x[i]; } /* Move real BasicVariables to the beginning of the matrix. * Artificials are to the right. They will be swapped out * by a call to AugmentBasis. */ for (i = 0; i < numVariables; i++) if (varType[i] != Artificial) { switch (BasisType[i]) { case BasicType: BasicVariables[LastBasic] = i; x[LastBasic] = TempX[i]; LastBasic++; break; case NonBasicType: NonBasicVariables[LastNonBasic] = i; LastNonBasic++; break; default: System.out.println("Error:Variable must be of Basic or NonBasic type"); } } else CountArtificials++; ArtificialsInBasis = 0; for (i = 0; i < numVariables; i++) if (varType[i] == Artificial) { switch (BasisType[i]) { case BasicType: ArtificialsInBasis++; BasicVariables[LastBasic] = i; x[LastBasic] = TempX[i]; LastBasic++; break; case NonBasicType: NonBasicVariables[LastNonBasic] = i; LastNonBasic++; break; default: System.out.println("Error:Variable must be of Basic or NonBasic type"); } } /* test for artificial variables in basis */ if (ArtificialsInBasis > 0) { /*System.out.println("CALLING AugmentBasis!!");*/ AugmentBasis(numConstraints-ArtificialsInBasis); /* rebuild index, BasicVariables, NonBasicVariables, and X */ for (i = 0; i < numConstraints; i++) { BasicVariables[i] = perm[i]; } for (i = 0; i < numVariables; i++) BasisType[i] = NonBasicType; /* default */ for (i = 0; i < numConstraints; i++) BasisType[BasicVariables[i]] = BasicType; LastBasic = 0; LastNonBasic = 0; for (i = 0; i < numVariables; i++) switch (BasisType[i]) { case BasicType: if (varType[i] == Artificial) { System.out.println("Error in GetRidOfArtificials:"); System.out.println(" There are still artificials after AugmentBasis"); } BasicVariables[LastBasic] = i; x[LastBasic] = TempX[i]; LastBasic++; break; case NonBasicType: NonBasicVariables[LastNonBasic] = i; LastNonBasic++; break; default: System.out.println("Error:Variable must be of Basic or NonBasic type"); } } ArtificialAdded = false; /* The problem can now be treated as in phase II */ this.specifyObjective(OriginalCost, oldOptType); numNonbasic -= CountArtificials; numVariables -= CountArtificials; /* reset TypeMinimize */ this.TypeMinimize = oldOptType; CurrentStep = 0; } /* end getRidOfArtificials procedure */ public float Dot (float []row, float []col, int size) { float result = 0; for (int i = 0; i < size; i++) result += row[i] * col[i]; return result; } /* end Dot procedure */ public void showInfo() { for (int j = 0; j < numVariables; j++) System.out.println("cost["+j+"]:"+cost[j]); for (int i = 0; i < numConstraints; i++) for (int j = 0; j < numVariables; j++) System.out.println("A["+i+"]["+j+"]:"+A[i][j]); System.out.println("LeavingVariable:"+LeavingVariable); System.out.println("EnteringVariable:"+EnteringVariable); for (int i = 0; i < numConstraints; i++) System.out.println("littleCost["+i+"]:"+littleCost[i]); System.out.println("MinRatio:"+MinRatio); for (int i = 0; i < numConstraints; i++) System.out.println("pi["+i+"]:"+pi[i]); for (int i = 0; i < numConstraints; i++) System.out.println("yB["+i+"]:"+yB[i]); for(int i = 0; i < numConstraints; i++) System.out.println("BasicVariables["+i+"]:"+BasicVariables[i]); for(int i = 0; i < numNonbasic; i++) System.out.println("NonBasicVariables["+i+"]:" + NonBasicVariables[i]); for(int i = 0; i < numConstraints; i++) System.out.println("x["+i+"]:"+x[i]); for (int i = 0; i < numNonbasic; i++) System.out.println("reducedCost["+i+"]:"+reducedCost[i]); System.out.println("objectiveValue:"+objectiveValue); for (int i = 0; i < numVariables; i++) System.out.println("OriginalCost["+i+"]:" + OriginalCost[i]); System.out.println("TypeMinimize"+ TypeMinimize); System.out.println("oldOptType"+ oldOptType); } /* end showInfo procedure */ public int solveLP() { int status = 0; while (status == 0) status = this.iterate(); return status; } /* end solveLP procedure */ public void reset(int numberOfVariables, int numberOfConstraints) { for (int i = 0; i < numConstraints; i++) for (int j = 0; j < numVariables; j++) A[i][j] = 0; numConstraintsSoFar = 0; numVariables = numberOfVariables; objectiveValue = 0; CurrentStep = 0; ArtificialAdded = false; NumArtificials = 0; } /* end reset procedure */ public int AugmentBasis(int BasisSize) { /* on input: * BasisSize = number of elements in the partial basis * BasicVariables = the current "partial" basis in its locations * 0,1,...BasisSize-1. * Assumes that the column indices are selected * from [0,1,2,...cols-1]. * * on output: * perm = in locations BasisSize, +1,...,rows-1 contains the * additional indices needed to form a full basis. */ int i, j, k, ihi, ilo, itemp; float[][] BN; float vnorm, v1, v2, dtemp; float[] tvec; int rows, cols; /* Make local copies of variables */ rows = numConstraints; cols = numVariables; /* check that input is OK */ if (rows > cols) { System.out.println("Odd-shaped constraint matrix:"); System.out.println("rows = "+rows+" cols = "+cols); return 1; } if (BasisSize > rows) { System.out.println("Too many elements in the basis!"); System.out.println("BasisSize = "+BasisSize+" rows = "+rows); return 1; } if (BasisSize < 0 || rows <= 0 || cols <= 0) { System.out.println("Something is rotten in the State of Denmark"); return 1; } /* check that the elements of the current BasicVariables make sense */ for (i = 0; i < BasisSize; i++) { if (BasicVariables[i] < 0 || BasicVariables[i] >= cols) { System.out.println("Basis element["+i+"]= "+BasicVariables[i]+" out of range"); return 1; } } if (BasisSize == rows) { System.out.println("Basis already has the right number of elements"); return 0; } /* System.out.println("The current basis has "+BasisSize+" columns."); System.out.println("It needs "+(rows-BasisSize)+" more."); */ /* On with the job. First allocate temporary data structures */ perm = new int[cols]; BN = new float[rows][cols]; /* transfer columns of A to BN, with the current basis in the first BasisSize locations and the remaining columns in the last cols-BasisSize locations. Keep track of the permutations in perm */ ilo = 0; ihi = cols - 1; for (i = 0; i < cols; i++) { if (inbasis(i, BasisSize, BasicVariables)) { for (j = 0; j < rows; j++) BN[j][ilo] = A[j][i]; perm[ilo] = i; ilo++; } else { for (j = 0; j < rows; j++) BN[j][ihi] = A[j][i]; perm[ihi] = i; ihi--; } } tvec = new float[rows]; /* now do BasisSize stages of the QR factorization */ for (i = 0; i < BasisSize; i++) { /* find norm of the present column and calculate Householder vector */ vnorm = 0; for (j = i; j < rows; j++) vnorm += BN[j][i] * BN[j][i]; vnorm = (float) Math.sqrt(vnorm); for (j = i; j < rows; j++) tvec[j] = BN[j][i]; if (tvec[i] < 0) { BN[i][i] = vnorm; tvec[i] -= vnorm; } else { BN[i][i] = -vnorm; tvec[i] += vnorm; } /* blank out present column */ for (j = i+1; j < rows; j++) BN[j][i] = 0; /* apply the Householder to the remaining columns */ v1 = 0; for (j = i; j < rows; j++) v1 += tvec[j]*tvec[j]; v1 = 2 / v1; for (k = i+1; k < cols; k++) { v2 = 0; for (j = i; j < rows; j++) v2 += tvec[j]*BN[j][k]; v2 *= v1; for (j = i; j < rows; j++) BN[j][k] -= v2 * tvec[j]; } } /* next phase - find another m-BasisSize columns by choosing the largest pivot in each row */ for (i = BasisSize; i < rows; i++) { /* identify the column with largest pivot in row i */ v1 = Math.abs(BN[i][i]); ihi = i; for (j = i+1; j < cols; j++) { if (Math.abs(BN[i][j]) > v1) { v1 = Math.abs(BN[i][j]); ihi = j; } } /* swap column ihi with column i */ itemp = perm[i]; perm[i] = perm[ihi]; perm[ihi] = itemp; for (j = 0; j < rows; j++) { dtemp = BN[j][i]; BN[j][i] = BN[j][ihi]; BN[j][ihi] = dtemp; } /* if we're not at stage "rows" yet, proceed with Householder */ if (i < rows-1) { /* now construct the Householder vector from column i as before */ vnorm = 0; for (j = i; j < rows; j++) vnorm += BN[j][i] * BN[j][i]; vnorm = (float) Math.sqrt(vnorm); for (j = i; j < rows; j++) tvec[j] = BN[j][i]; if (tvec[i] < 0) { BN[i][i] = vnorm; tvec[i] -= vnorm; } else { BN[i][i] = -vnorm; tvec[i] += vnorm; } /* blank out present column */ for (j = i+1; j < rows; j++) BN[j][i] = 0; /* apply the Householder to the remaining columns */ v1 = 0; for (j = i; j < rows; j++) v1 += tvec[j] * tvec[j]; v1 = 2 / v1; for (k = i+1; k < cols; k++) { v2 = 0; for (j = i; j < rows; j++) v2 += tvec[j] * BN[j][k]; v2 *= v1; for (j = i; j < rows; j++) BN[j][k] -= v2 * tvec[j]; } } } /* elements BasisSize, BasisSize+1, ... "rows"-1 of perm should * now contain the columns required for a full basis; */ return 0; } boolean inbasis(int i, int BasisSize, int[] basis) { int j; for (j = 0; j < BasisSize; j++) { if (basis[j] == i) return true; } return false; } } /* end revisedSimplex class */
26.019068
82
0.567096
b9487db4463abaaa7bbcb3ea34f7584ff73c2ba9
387
h
C
src/CGnuPlotStyleDelaunay.h
colinw7/CQGnuPlot
8001b0a0d40c1fde8e5efe05ebe0c9b0541daa94
[ "MIT" ]
null
null
null
src/CGnuPlotStyleDelaunay.h
colinw7/CQGnuPlot
8001b0a0d40c1fde8e5efe05ebe0c9b0541daa94
[ "MIT" ]
null
null
null
src/CGnuPlotStyleDelaunay.h
colinw7/CQGnuPlot
8001b0a0d40c1fde8e5efe05ebe0c9b0541daa94
[ "MIT" ]
1
2019-04-01T13:08:45.000Z
2019-04-01T13:08:45.000Z
#ifndef CGnuPlotStyleDelaunay_H #define CGnuPlotStyleDelaunay_H #include <CGnuPlotStyleBase.h> class CGnuPlotStyleDelaunay : public CGnuPlotStyleBase { public: CGnuPlotStyleDelaunay(); int numUsing() const override { return 2; } void draw2D(CGnuPlotPlot *plot, CGnuPlotRenderer *renderer) override; void drawAxes(CGnuPlotPlot *, CGnuPlotRenderer *) override { } }; #endif
21.5
71
0.777778
fbf5eb34111661d09e94cd4b50cc7777267c953b
3,910
sql
SQL
sql/pgsql_tables.sql
zsvoboda/gooddata-dremio-demo
a777fba6bd090dc1cbd8a04a2e74fbbba96c93e8
[ "MIT" ]
null
null
null
sql/pgsql_tables.sql
zsvoboda/gooddata-dremio-demo
a777fba6bd090dc1cbd8a04a2e74fbbba96c93e8
[ "MIT" ]
2
2022-02-16T19:14:31.000Z
2022-02-16T19:14:48.000Z
sql/pgsql_tables.sql
AlexRogalskiy/gooddata-dremio-demo
a777fba6bd090dc1cbd8a04a2e74fbbba96c93e8
[ "MIT" ]
1
2022-02-16T14:34:19.000Z
2022-02-16T14:34:19.000Z
DROP TABLE IF EXISTS insurance.car; CREATE TABLE insurance.car ( car_id varchar(512) NOT NULL, car_make varchar(512) NULL, car_model varchar(512) NULL, car_gears varchar(512) NULL, car_fuel_type varchar(512) NULL, car_transmission_type varchar(512) NULL, CONSTRAINT car_pkey PRIMARY KEY (car_id) ); DROP TABLE IF EXISTS insurance.product; CREATE TABLE insurance.product ( product_id varchar(512) NOT NULL, product_name varchar(512) NULL, product_type varchar(512) NULL, product_fire_coverage varchar(512) NULL, product_legal_defense_coverage varchar(512) NULL, product_liability_coverage varchar(512) NULL, product_passangers_coverage varchar(512) NULL, product_damage_coverage varchar(512) NULL, product_theft_coverage varchar(512) NULL, product_windshield_coverage varchar(512) NULL, CONSTRAINT product_pkey PRIMARY KEY (product_id) ); DROP TABLE IF EXISTS insurance.customer; CREATE TABLE insurance.customer ( customer_id varchar(512) NOT NULL, customer_age_group varchar(512) NULL, customer_demographic_code varchar(512) NULL, customer_gender varchar(512) NULL, customer_name varchar(512) NULL, region_id char(2) NULL, customer_segment varchar(512) NULL, wdf__region_id char(2) NOT NULL, CONSTRAINT customer_pkey PRIMARY KEY (customer_id) ); CREATE INDEX customer_region_id_idx ON insurance.customer USING btree (region_id); CREATE INDEX customer_wdf__region_id ON insurance.customer USING btree (wdf__region_id); DROP TABLE IF EXISTS insurance.region; CREATE TABLE insurance.region ( region_id char(2) NOT NULL, region_code char(2) NULL, region_name varchar(512) NULL, region_crime_rate numeric(5, 2) NULL, region_safety_scale numeric(5, 2) NULL, wdf__region_id char(2) NOT NULL, CONSTRAINT region_pkey PRIMARY KEY (region_id) ); CREATE UNIQUE INDEX region_wdf__region_id ON insurance.region USING btree (wdf__region_id); DROP TABLE IF EXISTS insurance.claim; CREATE TABLE insurance.claim ( claim_date date NULL, claim_amount numeric NULL, claim_id varchar(512) NOT NULL, product_id varchar(512) NULL, car_id varchar(512) NULL, customer_id varchar(512) NULL, wdf__region_id char(2) NOT NULL, CONSTRAINT claim_pkey PRIMARY KEY (claim_id) ); CREATE INDEX claim_car_id_idx ON insurance.claim USING btree (car_id); CREATE INDEX claim_customer_id_idx ON insurance.claim USING btree (customer_id); CREATE INDEX claim_date_idx ON insurance.claim USING btree (claim_date); CREATE INDEX claim_product_id_idx ON insurance.claim USING btree (product_id); CREATE INDEX claim_wdf__region_id ON insurance.claim USING btree (wdf__region_id); DROP TABLE IF EXISTS insurance.coverage; CREATE TABLE insurance.coverage ( coverage_id varchar(512) NOT NULL, coverage_is_active varchar(512) NULL, coverage_payment_is_current varchar(512) NULL, coverage_agent varchar(512) NULL, coverage_status varchar(512) NULL, coverage_created_date date NULL, coverage_cancelled_date date NULL, coverage_annual_premium numeric(12, 2) NULL, coverage_deductible numeric(12, 2) NULL, coverage_estimated_car_value numeric(12, 2) NULL, coverage_lifetime numeric(12, 2) NULL, coverage_accident_probability numeric(12, 2) NULL, coverage_risk_score numeric(12, 2) NULL, product_id varchar(512) NULL, car_id varchar(512) NULL, customer_id varchar(512) NULL, wdf__region_id char(2) NOT NULL, CONSTRAINT coverage_pkey PRIMARY KEY (coverage_id) ); CREATE INDEX coverage_cancelled_date_idx ON insurance.coverage USING btree (coverage_cancelled_date); CREATE INDEX coverage_car_id_idx ON insurance.coverage USING btree (car_id); CREATE INDEX coverage_created_date_idx ON insurance.coverage USING btree (coverage_created_date); CREATE INDEX coverage_customer_id_idx ON insurance.coverage USING btree (customer_id); CREATE INDEX coverage_product_id_idx ON insurance.coverage USING btree (product_id); CREATE INDEX coverage_wdf__region_id ON insurance.coverage USING btree (wdf__region_id);
39.1
101
0.81688
754f8651523c039d8506c92c4e7ab63201a54752
176
h
C
lib/pairchecker/preprocess/PairFunctions.h
epfl-vlsc/NVMOrdering
09ca83b9efbf4eedcef9cb1f42645ae0965f291a
[ "MIT" ]
null
null
null
lib/pairchecker/preprocess/PairFunctions.h
epfl-vlsc/NVMOrdering
09ca83b9efbf4eedcef9cb1f42645ae0965f291a
[ "MIT" ]
null
null
null
lib/pairchecker/preprocess/PairFunctions.h
epfl-vlsc/NVMOrdering
09ca83b9efbf4eedcef9cb1f42645ae0965f291a
[ "MIT" ]
null
null
null
#pragma once #include "Common.h" #include "global_util/DirectFunctions.h" namespace clang::ento::nvm { using PairFunctions = DirectFunctions; } // namespace clang::ento::nvm
19.555556
40
0.755682
e60fb7556baf9694c4836ce253edafd1b152a5d2
1,431
go
Go
coinstack/permission/permission.go
coinstack/coinstackd
d4d8e682681d508bb448a33fb1148997a845df69
[ "ISC" ]
5
2018-08-01T05:38:05.000Z
2018-12-21T11:12:58.000Z
coinstack/permission/permission.go
coinstack/coinstackd
d4d8e682681d508bb448a33fb1148997a845df69
[ "ISC" ]
2
2018-09-27T09:35:59.000Z
2018-09-27T09:38:36.000Z
coinstack/permission/permission.go
coinstack/coinstackd
d4d8e682681d508bb448a33fb1148997a845df69
[ "ISC" ]
2
2018-09-13T01:58:38.000Z
2019-10-26T15:31:29.000Z
// Copyright (c) 2016 BLOCKO INC. package permission import ( "strings" "github.com/coinstack/coinstackd/chaincfg" "github.com/coinstack/coinstackd/database" ) // nolint: golint const ( AdminPermission = "ADMIN" WriterPermission = "WRITER" MinerPermission = "MINER" NodePermission = "NODE" AdminMarker byte = 1 WriterMarker byte = 2 MinerMarker byte = 4 NodeMarker byte = 8 AliasNameMaxSize = 16 AliasPublickeySize = 33 ) type Cmd uint8 // nolint: golint const ( EnablePermCmd Cmd = iota + 1 SetPermCmd SetAliasCmd ) type Marker struct { MajorVersion uint16 MinorVersion uint16 CmdType Cmd Permission byte Address string Alias string PublicKey []byte // 33 bytes } type Manager interface { CheckPermission(dbTx database.Tx, addr string, permission byte) bool IsPermissionEnabled(dbTx database.Tx, permission byte) bool GetParam() *chaincfg.Params } func ConvertToString(permissionByte byte) string { var strArray []string if (permissionByte & AdminMarker) == AdminMarker { strArray = append(strArray, AdminPermission) } if (permissionByte & WriterMarker) == WriterMarker { strArray = append(strArray, WriterPermission) } if (permissionByte & MinerMarker) == MinerMarker { strArray = append(strArray, MinerPermission) } if (permissionByte & NodeMarker) == NodeMarker { strArray = append(strArray, NodePermission) } return strings.Join(strArray, "|") }
20.15493
69
0.733753
fd7e392cbdff5e01c49b573d4ee5ec212de5dfd1
8,422
dart
Dart
lib/Screens/Home2.dart
obitors/PreArticle_Android_App
15d1063ba2b1ec9539c11c6d0b8aa94392eafb52
[ "MIT" ]
8
2020-04-01T21:15:34.000Z
2021-05-26T10:08:33.000Z
lib/Screens/Home2.dart
obitors/PreArticle_Android_App
15d1063ba2b1ec9539c11c6d0b8aa94392eafb52
[ "MIT" ]
null
null
null
lib/Screens/Home2.dart
obitors/PreArticle_Android_App
15d1063ba2b1ec9539c11c6d0b8aa94392eafb52
[ "MIT" ]
3
2020-10-22T11:11:39.000Z
2021-02-26T09:39:28.000Z
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:prearticle/Configuration/app_config.dart'; import 'package:prearticle/Providers/search_Provider.dart'; import 'package:prearticle/Screens/Book_Details.dart'; import 'package:prearticle/Widgets/Book_Series_Widget.dart'; import 'package:bubble_bottom_bar/bubble_bottom_bar.dart'; import 'package:prearticle/Widgets/Card_Swipe.dart'; class HomePage extends StatefulWidget { HomePage({@required this.onPressed}); final GestureTapCallback onPressed; @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { var queryResultSet = []; var tempSearchStore = []; initiateSearch(value) { if (value.length == 0) { setState(() { queryResultSet = []; tempSearchStore = []; }); } var capitalizedValue = value.substring(0, 1).toUpperCase() + value.substring(1); if (queryResultSet.length == 0 && value.length == 1) { SearchService().searchByName(value).then((QuerySnapshot docs) { for (int i = 0; i < docs.documents.length; ++i) { queryResultSet.add(docs.documents[i].data); } }); } else { tempSearchStore = []; queryResultSet.forEach((element) { if (element['Name'].startsWith(capitalizedValue)) { setState(() { tempSearchStore.add(element); }); } }); } } int currentIndex; @override void initState() { super.initState(); currentIndex = 0; } void changePage(int index) { setState(() { currentIndex = index; }); } Widget build(BuildContext context) { SizeConfig().init(context); int index = 0; return Scaffold( resizeToAvoidBottomInset: false, backgroundColor: Color(0xff6e9bdf), appBar: AppBar ( leading: Icon(Icons.menu), centerTitle: true, title: Text( 'PreArticle', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, ), ), actions: <Widget>[ IconButton( icon: Icon(Icons.search), iconSize: 30.0, color: Colors.white, onPressed: () {}, ), ], elevation: 0, ), body: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding( padding: EdgeInsets.only(left: 20, right: 20, top: 10, bottom: 30), child: Container( height: 50, decoration: BoxDecoration( color: Color(0xffe7f0ff), borderRadius: BorderRadius.circular(10), ), child: Row( mainAxisSize: MainAxisSize.max, children: <Widget>[ Container( padding: EdgeInsets.only(left: 20, right: 20), width: SizeConfig.blockSizeHorizontal * 100 - 40, child: TextField( onChanged: (val) { initiateSearch(val); }, decoration: InputDecoration( hintText: 'Search Here', border: InputBorder.none, suffixIcon: Icon(Icons.search), ), ), ), ], ), ), ), Expanded( flex: 0, child: Container( color: Colors.white, child: ListView( padding: EdgeInsets.only(left: 10.0, right: 10.0), primary: false, shrinkWrap: true, children: tempSearchStore.map((element) { return GestureDetector( onTap: () { Navigator.of(context).push( MaterialPageRoute( builder: (BuildContext context) => BookDetails(), settings: RouteSettings(arguments: element['Name'])), ); }, child: Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10.0)), elevation: 2.0, child: Container( child: Center( child: Text( element['Name'], textAlign: TextAlign.center, style: TextStyle( color: Colors.black, fontSize: 20.0, ), )))), ); }).toList()), ), ), Expanded( flex: 1, child: Container( width: double.infinity, decoration: BoxDecoration( borderRadius: BorderRadius.only( topLeft: Radius.circular(25), topRight: Radius.circular(25)), color: Colors.white, ), child: Padding( padding: EdgeInsets.only(left: 0, right: 0, top: 20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Padding( padding: EdgeInsets.only(left: 20), child: Text( 'Book Series', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, color: Colors.grey[600], ), ), ), Padding( padding: EdgeInsets.only( top: 20, ), child: Container( height: 150, child: BookSeriesWidget(), ), ), Padding( padding: EdgeInsets.only(top: 15, bottom: 15, left: 20), child: Text( 'Recently Added', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, color: Colors.grey[600], ), ), ), Expanded(child: CardSwipe()) ], ), ), ), ), ], ), /* bottomNavigationBar: BubbleBottomBar( opacity: .2, borderRadius: BorderRadius.vertical(top: Radius.circular(16)), elevation: 10, hasNotch: true, hasInk: true, currentIndex: currentIndex, onTap: changePage, //inkColor: Colors.black12, //optional, uses theme color if not specified items: <BubbleBottomBarItem> [ BubbleBottomBarItem(backgroundColor: Color(0xff6e9bdf), icon: Icon(Icons.dashboard, color: Colors.black,), activeIcon: Icon(Icons.home, color: Color(0xff6e9bdf),), title: Text("Home")), BubbleBottomBarItem(backgroundColor: Color(0xff6e9bdf), icon: Icon(Icons.local_library, color: Colors.black,), activeIcon: Icon(Icons.local_library, color: Color(0xff6e9bdf),), title: Text("Library")), BubbleBottomBarItem(backgroundColor: Color(0xff6e9bdf), icon: Icon(Icons.settings, color: Colors.black,), activeIcon: Icon(Icons.settings, color: Color(0xff6e9bdf),), title: Text("Settings")), ], ), */ ); } }
35.238494
212
0.454643
04cf1492e06e3a200375384d0b5b2610c469e3cc
2,216
java
Java
src/main/java/frc/robot/Constants.java
CentralCatholic2641/tshirt-cannon
0526d4ef38ad747feef9682916ca0bdaa6140797
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/Constants.java
CentralCatholic2641/tshirt-cannon
0526d4ef38ad747feef9682916ca0bdaa6140797
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/Constants.java
CentralCatholic2641/tshirt-cannon
0526d4ef38ad747feef9682916ca0bdaa6140797
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. package frc.robot; /** * The Constants class provides a convenient place for teams to hold robot-wide * numerical or boolean constants. This class should not be used for any other * purpose. All constants should be declared globally (i.e. public static). Do * not put anything functional in this class. * * <p> * It is advised to statically import this clas s (or one of its inner classes) * wherever the constants are needed, to reduce verbosity. */ public final class Constants { // A button public static final int aButton = 1; // B button public static final int bButton = 2; // X button public static final int xButton = 3; // Y button public static final int yButton = 4; // Joysticks public static final int joystick1 = 1; public static final int joystick2 = 2; public static final int shooterSpeed = 3; // Joystick controller public static final int oneButton = 1; public static final int twoButton = 2; public static final int threeButton = 3; public static final int fourButton = 4; public static final int fiveButton = 5; // Controllers public static final int gamepad1 = 0; public static final int gamepad2 = 1; // Drivetrain motors public static final int leftmotor1 = 2; public static final int leftmotor2 = 3; //public static final int leftmotor3 = 3; public static final int rightmotor1 = 1; public static final int rightmotor2 = 4; //public static final int rightmotor3 = 6; // Miscellaneous motors // public static final int intakeMotor = 5; public static final int beltMotor = 9; public static final int shooterMotor = 7; public static final int intakeMotor = 8; // Encoders public static final int leftEncoder = 2; public static final int rightEncoder = 4; // PID-related public static final double kP = 0.6; public static final double kI = 0.002; public static final double kD = 0.2; public static final double wheelDiameter = 0.5; public static final double driftCompensation = 0.04; public static final int oneRotation = 4096; }
30.356164
79
0.737816
8704945ddc4d2c5dc43efa49aaae95cfb6caa9f6
484
rs
Rust
lambda/src/core/runnable.rs
C3NZ/lambda
0d14064a610833920801c7667532cfc1444dc915
[ "MIT" ]
4
2020-08-20T00:48:53.000Z
2020-11-20T22:05:54.000Z
lambda/src/core/runnable.rs
C3NZ/lambda
0d14064a610833920801c7667532cfc1444dc915
[ "MIT" ]
null
null
null
lambda/src/core/runnable.rs
C3NZ/lambda
0d14064a610833920801c7667532cfc1444dc915
[ "MIT" ]
null
null
null
pub trait Runnable { fn setup(&mut self); fn run(self); } /// Builds & executes a Runnable all in one good. This is useful for when you /// don't need to execute any code in between the building & execution stage of /// the runnable pub fn build_and_start_runnable<T: Default + Runnable>() { let app = T::default(); start_runnable(app); } /// Simple function for starting any prebuilt Runnable. pub fn start_runnable<T: Runnable>(mut app: T) { app.setup(); app.run(); }
25.473684
79
0.694215
b1a4863f31b643b5b0df820c33958492c5d288ec
10,112
asm
Assembly
v2.0/source/msdos/fat.asm
neozeed/MS-DOS
1cb8b96cd347b7eb150922eeb4924ec92911dc31
[ "MIT" ]
7
2018-09-29T16:03:48.000Z
2021-04-06T20:08:57.000Z
v2.0/source/msdos/fat.asm
neozeed/MS-DOS
1cb8b96cd347b7eb150922eeb4924ec92911dc31
[ "MIT" ]
null
null
null
v2.0/source/msdos/fat.asm
neozeed/MS-DOS
1cb8b96cd347b7eb150922eeb4924ec92911dc31
[ "MIT" ]
null
null
null
; ; FAT operations for MSDOS ; INCLUDE DOSSEG.ASM CODE SEGMENT BYTE PUBLIC 'CODE' ASSUME SS:DOSGROUP,CS:DOSGROUP .xlist .xcref INCLUDE DOSSYM.ASM INCLUDE DEVSYM.ASM .cref .list TITLE FAT - FAT maintenance routines NAME FAT i_need CURBUF,DWORD i_need CLUSSPLIT,BYTE i_need CLUSSAVE,WORD i_need CLUSSEC,WORD i_need THISDRV,BYTE i_need DEVCALL,BYTE i_need CALLMED,BYTE i_need CALLRBYT,BYTE i_need BUFFHEAD,DWORD i_need CALLXAD,DWORD i_need CALLBPB,DWORD SUBTTL UNPACK -- UNPACK FAT ENTRIES PAGE ASSUME SS:DOSGROUP procedure UNPACK,NEAR ASSUME DS:DOSGROUP,ES:NOTHING ; Inputs: ; BX = Cluster number ; ES:BP = Base of drive parameters ; Outputs: ; DI = Contents of FAT for given cluster ; Zero set means DI=0 (free cluster) ; SI Destroyed, No other registers affected. Fatal error if cluster too big. CMP BX,ES:[BP.dpb_max_cluster] JA HURTFAT CALL MAPCLUSTER ASSUME DS:NOTHING MOV DI,[DI] JNC HAVCLUS PUSH CX MOV CL,4 SHR DI,CL POP CX STC HAVCLUS: AND DI,0FFFH PUSH SS POP DS return HURTFAT: PUSH AX MOV AH,80H ; Signal Bad FAT to INT int_fatal_abort handler MOV DI,0FFFH ; In case INT int_fatal_abort returns (it shouldn't) invoke FATAL POP AX ; Try to ignore bad FAT return UNPACK ENDP SUBTTL PACK -- PACK FAT ENTRIES PAGE procedure PACK,NEAR ASSUME DS:DOSGROUP,ES:NOTHING ; Inputs: ; BX = Cluster number ; DX = Data ; ES:BP = Pointer to drive DPB ; Outputs: ; The data is stored in the FAT at the given cluster. ; SI,DX,DI all destroyed ; No other registers affected CALL MAPCLUSTER ASSUME DS:NOTHING MOV SI,[DI] JNC ALIGNED PUSH CX MOV CL,4 SHL DX,CL POP CX AND SI,0FH JMP SHORT PACKIN ALIGNED: AND SI,0F000H PACKIN: OR SI,DX MOV [DI],SI LDS SI,[CURBUF] MOV [SI.BUFDIRTY],1 CMP BYTE PTR [CLUSSPLIT],0 PUSH SS POP DS ASSUME DS:DOSGROUP retz PUSH AX PUSH BX PUSH CX MOV AX,[CLUSSAVE] MOV DS,WORD PTR [CURBUF+2] ASSUME DS:NOTHING ADD SI,BUFINSIZ MOV [SI],AH PUSH SS POP DS ASSUME DS:DOSGROUP PUSH AX MOV DX,[CLUSSEC] MOV SI,1 XOR AL,AL invoke GETBUFFRB LDS DI,[CURBUF] ASSUME DS:NOTHING MOV [DI.BUFDIRTY],1 ADD DI,BUFINSIZ DEC DI ADD DI,ES:[BP.dpb_sector_size] POP AX MOV [DI],AL PUSH SS POP DS POP CX POP BX POP AX return PACK ENDP SUBTTL MAPCLUSTER - BUFFER A FAT SECTOR PAGE procedure MAPCLUSTER,NEAR ASSUME DS:DOSGROUP,ES:NOTHING ; Inputs: ; ES:BP Points to DPB ; BX Is cluster number ; Function: ; Get a pointer to the cluster ; Outputs: ; DS:DI Points to contents of FAT for given cluster ; DS:SI Points to start of buffer ; Carry set if cluster data is in high 12 bits of word ; No other registers effected MOV BYTE PTR [CLUSSPLIT],0 PUSH AX PUSH BX PUSH CX PUSH DX MOV AX,BX SHR AX,1 ADD AX,BX XOR DX,DX MOV CX,ES:[BP.dpb_sector_size] DIV CX ; AX is FAT sector # DX is sector index ADD AX,ES:[BP.dpb_first_FAT] DEC CX PUSH AX PUSH DX PUSH CX MOV DX,AX XOR AL,AL MOV SI,1 invoke GETBUFFRB LDS SI,[CURBUF] ASSUME DS:NOTHING LEA DI,[SI.BufInSiz] POP CX POP AX POP DX ADD DI,AX CMP AX,CX JNZ MAPRET MOV AL,[DI] PUSH SS POP DS ASSUME DS:DOSGROUP INC BYTE PTR [CLUSSPLIT] MOV BYTE PTR [CLUSSAVE],AL MOV [CLUSSEC],DX INC DX XOR AL,AL MOV SI,1 invoke GETBUFFRB LDS SI,[CURBUF] ASSUME DS:NOTHING LEA DI,[SI.BufInSiz] MOV AL,[DI] PUSH SS POP DS ASSUME DS:DOSGROUP MOV BYTE PTR [CLUSSAVE+1],AL MOV DI,OFFSET DOSGROUP:CLUSSAVE MAPRET: POP DX POP CX POP BX MOV AX,BX SHR AX,1 POP AX return MAPCLUSTER ENDP SUBTTL FATREAD -- CHECK DRIVE GET FAT PAGE ASSUME DS:DOSGROUP,ES:NOTHING procedure FAT_operation,NEAR FATERR: AND DI,STECODE ; Put error code in DI MOV AH,2 ; While trying to read FAT MOV AL,BYTE PTR [THISDRV] ; Tell which drive invoke FATAL1 entry FATREAD ASSUME DS:DOSGROUP,ES:NOTHING ; Function: ; If disk may have been changed, FAT is read in and buffers are ; flagged invalid. If not, no action is taken. ; Outputs: ; ES:BP = Base of drive parameters ; All other registers destroyed MOV AL,BYTE PTR [THISDRV] invoke GETBP MOV AL,DMEDHL MOV AH,ES:[BP.dpb_UNIT] MOV WORD PTR [DEVCALL],AX MOV BYTE PTR [DEVCALL.REQFUNC],DEVMDCH MOV [DEVCALL.REQSTAT],0 MOV AL,ES:[BP.dpb_media] MOV BYTE PTR [CALLMED],AL PUSH ES PUSH DS MOV BX,OFFSET DOSGROUP:DEVCALL LDS SI,ES:[BP.dpb_driver_addr] ; DS:SI Points to device header ASSUME DS:NOTHING POP ES ; ES:BX Points to call header invoke DEVIOCALL2 PUSH SS POP DS ASSUME DS:DOSGROUP POP ES ; Restore ES:BP MOV DI,[DEVCALL.REQSTAT] TEST DI,STERR JNZ FATERR XOR AH,AH XCHG AH,ES:[BP.dpb_first_access] ; Reset dpb_first_access MOV AL,BYTE PTR [THISDRV] ; Use physical unit number OR AH,BYTE PTR [CALLRBYT] JS NEWDSK ; new disk or first access? JZ CHKBUFFDIRT return ; If Media not changed CHKBUFFDIRT: INC AH ; Here if ?Media..Check buffers LDS DI,[BUFFHEAD] ASSUME DS:NOTHING NBUFFER: ; Look for dirty buffers CMP AX,WORD PTR [DI.BUFDRV] retz ; There is a dirty buffer, assume Media OK LDS DI,[DI.NEXTBUF] CMP DI,-1 JNZ NBUFFER ; If no dirty buffers, assume Media changed NEWDSK: invoke SETVISIT NXBUFFER: MOV [DI.VISIT],1 CMP AL,[DI.BUFDRV] ; For this drive? JNZ SKPBUFF MOV WORD PTR [DI.BUFDRV],00FFH ; Free up buffer invoke SCANPLACE SKPBUFF: invoke SKIPVISIT JNZ NXBUFFER LDS DI,ES:[BP.dpb_driver_addr] TEST [DI.SDEVATT],ISFATBYDEV JNZ GETFREEBUF context DS MOV BX,2 CALL UNPACK ; Read the first FAT sector into CURBUF LDS DI,[CURBUF] JMP SHORT GOTGETBUF GETFREEBUF: ASSUME DS:NOTHING PUSH ES ; Get a free buffer for BIOS to use PUSH BP LDS DI,[BUFFHEAD] invoke BUFWRITE POP BP POP ES GOTGETBUF: ADD DI,BUFINSIZ MOV WORD PTR [CALLXAD+2],DS PUSH SS POP DS ASSUME DS:DOSGROUP MOV WORD PTR [CALLXAD],DI MOV AL,DBPBHL MOV AH,BYTE PTR ES:[BP.dpb_UNIT] MOV WORD PTR [DEVCALL],AX MOV BYTE PTR [DEVCALL.REQFUNC],DEVBPB MOV [DEVCALL.REQSTAT],0 MOV AL,BYTE PTR ES:[BP.dpb_media] MOV [CALLMED],AL PUSH ES PUSH DS PUSH WORD PTR ES:[BP.dpb_driver_addr+2] PUSH WORD PTR ES:[BP.dpb_driver_addr] MOV BX,OFFSET DOSGROUP:DEVCALL POP SI POP DS ; DS:SI Points to device header ASSUME DS:NOTHING POP ES ; ES:BX Points to call header invoke DEVIOCALL2 POP ES ; Restore ES:BP PUSH SS POP DS ASSUME DS:DOSGROUP MOV DI,[DEVCALL.REQSTAT] TEST DI,STERR JNZ FATERRJ MOV AL,BYTE PTR ES:[BP.dpb_media] LDS SI,[CALLBPB] ASSUME DS:NOTHING CMP AL,BYTE PTR [SI.BPMEDIA] JZ DPBOK invoke $SETDPB LDS DI,[CALLXAD] ; Get back buffer pointer MOV AL,BYTE PTR ES:[BP.dpb_FAT_count] MOV AH,BYTE PTR ES:[BP.dpb_FAT_size] MOV WORD PTR [DI.BUFWRTCNT-BUFINSIZ],AX ;Correct buffer info DPBOK: context ds MOV AX,-1 TEST ES:[BP.dpb_current_dir],AX retz ; If root, leave as root MOV ES:[BP.dpb_current_dir],AX ; Path may be bad, mark invalid return FATERRJ: JMP FATERR FAT_operation ENDP do_ext CODE ENDS END
27.933702
85
0.491001
23d7aa424091d3e41a2692631b131415b42e31fb
3,095
dart
Dart
fitness_health_test_app/lib/ui/pages/login/forgot_password/forgot_password_page.dart
tran-haison/Fitness-Health-Test-App
b9f940a404a1d4110dc04ecf1b373249a82ab5a4
[ "Apache-2.0" ]
1
2021-11-18T05:26:01.000Z
2021-11-18T05:26:01.000Z
fitness_health_test_app/lib/ui/pages/login/forgot_password/forgot_password_page.dart
tran-haison/Fitness-Health-Test-App
b9f940a404a1d4110dc04ecf1b373249a82ab5a4
[ "Apache-2.0" ]
null
null
null
fitness_health_test_app/lib/ui/pages/login/forgot_password/forgot_password_page.dart
tran-haison/Fitness-Health-Test-App
b9f940a404a1d4110dc04ecf1b373249a82ab5a4
[ "Apache-2.0" ]
null
null
null
import 'package:fitness_health_test_app/generated/l10n.dart'; import 'package:fitness_health_test_app/ui/common_widgets/login_pages/login_rounded_elevated_button.dart'; import 'package:fitness_health_test_app/ui/common_widgets/login_pages/login_text_content.dart'; import 'package:fitness_health_test_app/ui/common_widgets/login_pages/login_text_form_field.dart'; import 'package:fitness_health_test_app/ui/common_widgets/login_pages/login_text_input_error.dart'; import 'package:fitness_health_test_app/ui/common_widgets/login_pages/login_text_title.dart'; import 'package:fitness_health_test_app/ui/pages/login/forgot_password/forgot_password_form.dart'; import 'package:fitness_health_test_app/ui/pages/login/login_page_item.dart'; import 'package:fitness_health_test_app/values/dimens.dart'; import 'package:fitness_health_test_app/view_models/login_view_model.dart'; import 'package:flutter/material.dart'; import 'package:provider/provider.dart'; class ForgotPasswordPage extends StatefulWidget { const ForgotPasswordPage({Key? key}) : super(key: key); @override _ForgotPasswordPageState createState() => _ForgotPasswordPageState(); } class _ForgotPasswordPageState extends State<ForgotPasswordPage> { late ForgotPasswordForm _forgotPasswordForm; late LoginViewModel _viewModel; @override void initState() { // Init instances _forgotPasswordForm = ForgotPasswordForm(); _viewModel = Provider.of<LoginViewModel>(context, listen: false); super.initState(); } @override void dispose() { _forgotPasswordForm.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return WillPopScope( onWillPop: () => _viewModel.onBackPressed(LoginPageItem.signIn), child: Column( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ Expanded( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ LoginTextTitle(title: S.of(context).login_forgot_password_title), LoginTextContent(content: S.of(context).login_forgot_password_prompt), const SizedBox(height: Dimens.dimen20), _buildEmailTextFormField(), LoginTextInputError( streamInput: _forgotPasswordForm.emailStream, errorText: S.of(context).error_email_invalid, ), ], ), ), _buildConfirmButton(), ], ), ); } Widget _buildEmailTextFormField() { return LoginTextFormField( hintText: S.of(context).login_email, icon: const Icon(Icons.email), isPassword: false, onChanged: _forgotPasswordForm.onEmailChanged, ); } Widget _buildConfirmButton() { return LoginRoundedElevatedButton( text: S.of(context).login_forgot_password_confirm, formStream: _forgotPasswordForm.formStream, onClick: () { // TODO: confirm }, ); } }
35.574713
106
0.713086
fd5d690c5584b816856382323deae7b787e29946
5,351
h
C
Libs/bullet/LinearMath/btConvexHullComputer.h
stinvi/dava.engine
2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e
[ "BSD-3-Clause" ]
26
2018-09-03T08:48:22.000Z
2022-02-14T05:14:50.000Z
Libs/bullet/LinearMath/btConvexHullComputer.h
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
null
null
null
Libs/bullet/LinearMath/btConvexHullComputer.h
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
45
2018-05-11T06:47:17.000Z
2022-02-03T11:30:55.000Z
/*================================================================================== Copyright (c) 2008, binaryzebra All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the binaryzebra nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE binaryzebra AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL binaryzebra BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =====================================================================================*/ /* Copyright (c) 2011 Ole Kniemeyer, MAXON, www.maxon.net This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #ifndef BT_CONVEX_HULL_COMPUTER_H #define BT_CONVEX_HULL_COMPUTER_H #include "btVector3.h" #include "btAlignedObjectArray.h" /// Convex hull implementation based on Preparata and Hong /// See http://code.google.com/p/bullet/issues/detail?id=275 /// Ole Kniemeyer, MAXON Computer GmbH class btConvexHullComputer { private: btScalar compute(const void* coords, bool doubleCoords, int stride, int count, btScalar shrink, btScalar shrinkClamp); public: class Edge { private: int next; int reverse; int targetVertex; friend class btConvexHullComputer; public: int getSourceVertex() const { return (this + reverse)->targetVertex; } int getTargetVertex() const { return targetVertex; } const Edge* getNextEdgeOfVertex() const // clockwise list of all edges of a vertex { return this + next; } const Edge* getNextEdgeOfFace() const // counter-clockwise list of all edges of a face { return (this + reverse)->getNextEdgeOfVertex(); } const Edge* getReverseEdge() const { return this + reverse; } }; // Vertices of the output hull btAlignedObjectArray<btVector3> vertices; // Edges of the output hull btAlignedObjectArray<Edge> edges; // Faces of the convex hull. Each entry is an index into the "edges" array pointing to an edge of the face. Faces are planar n-gons btAlignedObjectArray<int> faces; /* Compute convex hull of "count" vertices stored in "coords". "stride" is the difference in bytes between the addresses of consecutive vertices. If "shrink" is positive, the convex hull is shrunken by that amount (each face is moved by "shrink" length units towards the center along its normal). If "shrinkClamp" is positive, "shrink" is clamped to not exceed "shrinkClamp * innerRadius", where "innerRadius" is the minimum distance of a face to the center of the convex hull. The returned value is the amount by which the hull has been shrunken. If it is negative, the amount was so large that the resulting convex hull is empty. The output convex hull can be found in the member variables "vertices", "edges", "faces". */ btScalar compute(const float* coords, int stride, int count, btScalar shrink, btScalar shrinkClamp) { return compute(coords, false, stride, count, shrink, shrinkClamp); } // same as above, but double precision btScalar compute(const double* coords, int stride, int count, btScalar shrink, btScalar shrinkClamp) { return compute(coords, true, stride, count, shrink, shrinkClamp); } }; #endif //BT_CONVEX_HULL_COMPUTER_H
41.48062
243
0.702859
8db1563e1545a1ede1b106ca80ee3bd1fedf95f2
2,908
sql
SQL
Mercury.Database/Mercury.Database.Environment/Schema Objects/Schemas/dbo/Programmability/Stored Procedures/WorkTeamMembership_InsertUpdate.proc.sql
Quebe/Mercury-Care-Management
a3cd0cb9dbc6b88dfd3f7514593b31e717c12491
[ "MIT" ]
null
null
null
Mercury.Database/Mercury.Database.Environment/Schema Objects/Schemas/dbo/Programmability/Stored Procedures/WorkTeamMembership_InsertUpdate.proc.sql
Quebe/Mercury-Care-Management
a3cd0cb9dbc6b88dfd3f7514593b31e717c12491
[ "MIT" ]
null
null
null
Mercury.Database/Mercury.Database.Environment/Schema Objects/Schemas/dbo/Programmability/Stored Procedures/WorkTeamMembership_InsertUpdate.proc.sql
Quebe/Mercury-Care-Management
a3cd0cb9dbc6b88dfd3f7514593b31e717c12491
[ "MIT" ]
1
2021-07-31T06:10:44.000Z
2021-07-31T06:10:44.000Z
/* IF EXISTS (SELECT name FROM sysobjects WHERE (name = 'WorkTeamMembership_InsertUpdate' AND type = 'P')) DROP PROCEDURE dbo.WorkTeamMembership_InsertUpdate GO */ CREATE PROCEDURE dbo.WorkTeamMembership_InsertUpdate /* STORED PROCEDURE - INPUTS (BEGIN) */ @workTeamId BIGINT, @securityAuthorityId BIGINT, @userAccountId VARCHAR (060), @userAccountName VARCHAR (060), @userDisplayName VARCHAR (060), @workTeamRole INT, @modifiedAuthorityName VARCHAR (060), @modifiedAccountId VARCHAR (060), @modifiedAccountName VARCHAR (060) /* STORED PROCEDURE - INPUTS ( END ) */ /* STORED PROCEDURE - OUTPUTS (BEGIN) */ -- EXAMPLE: @MYOUTPUT VARCHAR (20) OUTPUT -- A VARIABLE DECLARATION FOR RETURN VALUE /* STORED PROCEDURE - OUTPUTS ( END ) */ AS BEGIN /* STORED PROCEDURE (BEGIN) */ /* LOCAL VARIABLES (BEGIN) */ /* LOCAL VARIABLES ( END ) */ IF EXISTS (SELECT * FROM dbo.WorkTeamMembership WHERE WorkTeamId = @workTeamId AND SecurityAuthorityId = @securityAuthorityId AND UserAccountId = @userAccountId) BEGIN -- EXISTING RECORD, UPDATE UPDATE dbo.WorkTeamMembership SET UserAccountName = @userAccountName, UserDisplayName = @userDisplayName, WorkTeamRole = @workTeamRole, ModifiedAuthorityName = @modifiedAuthorityName, ModifiedAccountId = @modifiedAccountId, ModifiedAccountName = @modifiedAccountName, ModifiedDate = GETDATE () WHERE WorkTeamId = @workTeamId AND SecurityAuthorityId = @securityAuthorityId AND UserAccountId = @userAccountId END ELSE -- NO EXISTING RECORD, INSERT NEW BEGIN INSERT INTO WorkTeamMembership ( WorkTeamId, SecurityAuthorityId, UserAccountId, UserAccountName, UserDisplayName, WorkTeamRole, CreateAuthorityName, CreateAccountId, CreateAccountName, CreateDate, ModifiedAuthorityName, ModifiedAccountId, ModifiedAccountName, ModifiedDate) VALUES ( @workTeamId, @securityAuthorityId, @userAccountId, @userAccountName, @userDisplayName, @workTeamRole, @modifiedAuthorityName, @modifiedAccountId, @modifiedAccountName, GETDATE (), @modifiedAuthorityName, @modifiedAccountId, @modifiedAccountName, GETDATE ()) END /* STORED PROCEDURE ( END ) */ END GO /* GRANT EXECUTE ON dbo.WorkTeamMembership_InsertUpdate TO PUBLIC GO */
36.35
169
0.586314
6651281b6c77c985bca4bb8810387e9883390621
2,588
cpp
C++
test/gui/comctl32/comctl32_test.cpp
ShigotoShoujin/shigoto.shoujin
165bac0703ffdec544ab275af25dd3504529a565
[ "MIT" ]
1
2021-10-31T04:29:16.000Z
2021-10-31T04:29:16.000Z
test/gui/comctl32/comctl32_test.cpp
ShigotoShoujin/shigoto.shoujin
165bac0703ffdec544ab275af25dd3504529a565
[ "MIT" ]
null
null
null
test/gui/comctl32/comctl32_test.cpp
ShigotoShoujin/shigoto.shoujin
165bac0703ffdec544ab275af25dd3504529a565
[ "MIT" ]
null
null
null
#include "CppUnitTest.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; #include <shoujin/assert.hpp> #include <shoujin/gui.hpp> using namespace shoujin; using namespace shoujin::gui; using namespace shoujin::gui::comctl32; static bool OnCreatePostCloseMsg(Window const& window, CREATESTRUCT const& createparam, void* userdata); static bool OnErrorOutput(tstring message, void* userdata); class TestControl : public Comctl32 { public: TestControl(LayoutParam const& layout_param = {}) : Comctl32{TEXT("EDIT"), BuildLayout(layout_param)} {} virtual ~TestControl() = default; virtual void OnInitialize() override { ++_on_initialize_call_count; } int OnInitializeCallCount() const { return _on_initialize_call_count; } private: LayoutParam BuildLayout(LayoutParam layout_param) { layout_param.text = TEXT("Control Window"); return layout_param; } virtual Window* Clone() const override { return new TestControl(*this); } int _on_initialize_call_count{}; }; class TestWindow : public Window { public: explicit TestWindow(LayoutParam const& layout_param = {}) : Window(BuildLayout(layout_param)) { _control = new TestControl(LayoutParam{.anchor = Anchor::Top | Anchor::Left, .window_size{200, 23}, .exstyle{WS_EX_CLIENTEDGE}}); AddChild(_control); } virtual ~TestWindow() = default; TestControl& EditControl() { return *_control; } private: LayoutParam BuildLayout(LayoutParam layout_param) { layout_param.text = TEXT("Main Window"); return layout_param; } TestControl* _control; }; TEST_CLASS(Comctl32Test) { public: TEST_METHOD_INITIALIZE(TestInitialize) { shoujin::assert::OnErrorOutputEvent = OnErrorOutput; shoujin::gui::logging::_activate_wndproc_messagelog_ = true; } TEST_METHOD_CLEANUP(TestCleanup) { shoujin::assert::OnErrorOutputEvent = nullptr; shoujin::gui::logging::_activate_wndproc_messagelog_ = false; } TEST_METHOD(GivenAWindowWithAControl_WhenWindowIsCreated_ControlOnInitializeIsCalledOnce) { TestWindow window{LayoutParam{.layout_mode = LayoutMode::CenterParent}}; window.OnCreateEvent = OnCreatePostCloseMsg; window.ShowModal(); Assert::AreEqual(1, window.EditControl().OnInitializeCallCount()); } }; static bool OnCreatePostCloseMsg(Window const& window, CREATESTRUCT const& createparam, void* userdata) { SHOUJIN_ASSERT(window.handle()); PostMessage(window.handle()->hwnd(), WM_CLOSE, 0, 0); return false; } static bool OnErrorOutput(tstring message, void* userdata) { Logger::WriteMessage(message.c_str()); Assert::Fail(string::ToWideString(message).c_str()); }
25.88
131
0.765842
83e68ed9be28739d70a6f12aac185999f4d9cd94
7,299
java
Java
android/app/src/main/java/com/texasgamer/zephyr/ZephyrApplication.java
ThomasGaubert/zephyr
37d2e5b13538dfeeb98e20878968ebea2c1b9dfc
[ "MIT" ]
85
2016-06-21T15:00:04.000Z
2022-02-25T20:31:10.000Z
android/app/src/main/java/com/texasgamer/zephyr/ZephyrApplication.java
ThomasGaubert/openvr-notifications
37d2e5b13538dfeeb98e20878968ebea2c1b9dfc
[ "MIT" ]
644
2016-06-21T23:23:19.000Z
2022-03-24T13:04:11.000Z
android/app/src/main/java/com/texasgamer/zephyr/ZephyrApplication.java
ThomasGaubert/openvr-notifications
37d2e5b13538dfeeb98e20878968ebea2c1b9dfc
[ "MIT" ]
13
2016-06-21T23:07:02.000Z
2022-01-27T23:30:03.000Z
package com.texasgamer.zephyr; import android.app.Activity; import android.app.Application; import android.os.Build; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.lifecycle.Lifecycle; import androidx.lifecycle.LifecycleObserver; import androidx.lifecycle.OnLifecycleEvent; import androidx.lifecycle.ProcessLifecycleOwner; import com.google.firebase.FirebaseApp; import com.google.firebase.crashlytics.FirebaseCrashlytics; import com.texasgamer.zephyr.injection.components.ApplicationComponent; import com.texasgamer.zephyr.injection.components.DaggerApplicationComponent; import com.texasgamer.zephyr.injection.modules.ApplicationModule; import com.texasgamer.zephyr.model.ConnectionStatus; import com.texasgamer.zephyr.network.IDiscoveryManager; import com.texasgamer.zephyr.service.QuickSettingService; import com.texasgamer.zephyr.service.SocketService; import com.texasgamer.zephyr.util.BuildConfigUtils; import com.texasgamer.zephyr.util.config.IConfigManager; import com.texasgamer.zephyr.util.distribution.IDistributionManager; import com.texasgamer.zephyr.util.lifecycle.ZephyrLifecycleLogger; import com.texasgamer.zephyr.util.log.ILogger; import com.texasgamer.zephyr.util.log.LogLevel; import com.texasgamer.zephyr.util.preference.IPreferenceManager; import com.texasgamer.zephyr.util.preference.PreferenceKeys; import com.texasgamer.zephyr.util.privacy.IPrivacyManager; import com.texasgamer.zephyr.util.theme.IThemeManager; import com.texasgamer.zephyr.worker.IWorkManager; import org.greenrobot.eventbus.EventBus; import java.lang.ref.WeakReference; import javax.inject.Inject; /** * Zephyr application. */ public class ZephyrApplication extends Application implements LifecycleObserver, Application.ActivityLifecycleCallbacks { private static final String LOG_TAG = "ZephyrApplication"; private static ZephyrApplication sInstance; private static ApplicationComponent sApplicationComponent; private static boolean sCrashReportingInitialized = false; @Inject ILogger logger; @Inject IConfigManager configManager; @Inject IWorkManager workManager; @Inject IPreferenceManager preferenceManager; @Inject IPrivacyManager privacyManager; @Inject IDiscoveryManager discoveryManager; @Inject IThemeManager themeManager; @Inject IDistributionManager distributionManager; private WeakReference<Activity> mCurrentActivity; private boolean mIsInForeground; public static ApplicationComponent getApplicationComponent() { return sApplicationComponent; } public static ZephyrApplication getInstance() { return sInstance; } public static boolean isCrashReportingInitialized() { return sCrashReportingInitialized; } @Override public void onCreate() { super.onCreate(); sInstance = this; sApplicationComponent = DaggerApplicationComponent.builder() .applicationModule(new ApplicationModule(this)) .build(); sApplicationComponent.inject(ZephyrApplication.this); sApplicationComponent.init(); registerActivityLifecycleCallbacks(new ZephyrLifecycleLogger(logger)); registerActivityLifecycleCallbacks(this); ProcessLifecycleOwner.get().getLifecycle().addObserver(this); EventBus.builder().logNoSubscriberMessages(false).installDefaultEventBus(); if (configManager.isFirebaseEnabled()) { FirebaseApp.initializeApp(this); } else { logger.log(LogLevel.WARNING, LOG_TAG, "Firebase disabled, some features will be limited or disabled."); } FirebaseCrashlytics firebaseCrashlytics = FirebaseCrashlytics.getInstance(); if (privacyManager.isCrashReportingEnabled()) { firebaseCrashlytics.setCrashlyticsCollectionEnabled(true); firebaseCrashlytics.setUserId(privacyManager.getUuid()); sCrashReportingInitialized = true; } else { firebaseCrashlytics.setCrashlyticsCollectionEnabled(false); logger.log(LogLevel.WARNING, LOG_TAG, "Crashlytics disabled."); } if (!BuildConfig.PROPS_SET) { logger.log(LogLevel.WARNING, LOG_TAG, "Secret properties not set! Some features will be limited or disabled."); } logger.log(LogLevel.DEBUG, LOG_TAG, "Zephyr %s (%s - %s) started.", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE, BuildConfig.GIT_HASH); themeManager.setDefaultNightMode(); sApplicationComponent.notificationsManager().createNotificationChannels(); workManager.initWork(); verifyConnectionStatus(); distributionManager.start(); // Track version code preferenceManager.getInt(PreferenceKeys.PREF_LAST_KNOWN_APP_VERSION, BuildConfigUtils.getVersionCode()); } @Override public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) { } @Override public void onActivityStarted(@NonNull Activity activity) { } @Override public void onActivityResumed(@NonNull Activity activity) { mCurrentActivity = new WeakReference<>(activity); } @Override public void onActivityPaused(@NonNull Activity activity) { } @Override public void onActivityStopped(@NonNull Activity activity) { } @Override public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) { } @Override public void onActivityDestroyed(@NonNull Activity activity) { } public boolean isInForeground() { return mIsInForeground; } @Nullable public Activity getCurrentActivity() { return mCurrentActivity != null ? mCurrentActivity.get() : null; } @SuppressWarnings("PMD.UnusedPrivateMethod") @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) private void onAppForegrounded() { logger.log(LogLevel.VERBOSE, LOG_TAG, "App is in the foreground."); mIsInForeground = true; if (configManager.isDiscoveryEnabled()) { discoveryManager.start(); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { QuickSettingService.updateQuickSettingTile(this); } } @SuppressWarnings("PMD.UnusedPrivateMethod") @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) private void onAppBackgrounded() { logger.log(LogLevel.VERBOSE, LOG_TAG, "App is in the background."); mIsInForeground = false; discoveryManager.stop(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { QuickSettingService.updateQuickSettingTile(this); } } private void verifyConnectionStatus() { if (!preferenceManager.getBoolean(PreferenceKeys.PREF_IS_SOCKET_SERVICE_RUNNING)) { preferenceManager.putInt(PreferenceKeys.PREF_CONNECTION_STATUS, ConnectionStatus.DISCONNECTED); } else if (!SocketService.instanceCreated) { preferenceManager.putBoolean(PreferenceKeys.PREF_IS_SOCKET_SERVICE_RUNNING, false); preferenceManager.putInt(PreferenceKeys.PREF_CONNECTION_STATUS, ConnectionStatus.DISCONNECTED); } } }
33.635945
150
0.73695
a5e8d831a45bf0defc1f0c3e3808787e8a0716c3
4,310
swift
Swift
MyProposalGame/Libraries/SG-Controllers/TileMapBuilder.swift
cabarique/TheProposalGame
59e96b4b824f0d32cc56a6d36fddad67e6918785
[ "MIT" ]
1
2016-11-28T03:27:14.000Z
2016-11-28T03:27:14.000Z
MyProposalGame/Libraries/SG-Controllers/TileMapBuilder.swift
cabarique/TheProposalGame
59e96b4b824f0d32cc56a6d36fddad67e6918785
[ "MIT" ]
null
null
null
MyProposalGame/Libraries/SG-Controllers/TileMapBuilder.swift
cabarique/TheProposalGame
59e96b4b824f0d32cc56a6d36fddad67e6918785
[ "MIT" ]
null
null
null
/* * Copyright (c) 2015 Neil North. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import SpriteKit import GameplayKit enum tileType: Int { case tileNotifier = -1 case tileAir = 0 case tileGroundLeft = 1 case tileGround = 2 case tileGroundRight = 3 case tileWallLeft = 4 case tileGroundMiddle = 5 case tileWallRight = 6 case tileGroundCornerR = 7 case tileGroundCornerRU = 8 case tileCeiling = 9 case tileGroundCornerLU = 10 case tileGroundCornerL = 11 case tileCeilingLeft = 12 case tileCeilingRight = 13 case tilePlatformLeft = 14 case tilePlatform = 15 case tilePlatformRight = 16 case tileWaterSurface = 17 case tileWater = 18 case tileRandomScenery = 19 case tileSignPost = 20 case tileSignArrow = 21 case tileCrate = 22 case tileStartLevel = 23 case tileEndLevel = 24 case tileDiamond = 25 case tileCoin = 26 case tileZombie = 27 case tileZombie2 = 28 case tileMage1 = 29 case tileMage2 = 30 case tileBoss = 31 case tilePrincess = 32 case tileEndDialog = 33 } protocol tileMapDelegate { func createNodeOf(type type:tileType, location:CGPoint, level: Int) } struct tileMapBuilder { var delegate: tileMapDelegate? var tileSize = CGSize(width: 32, height: 32) var tileLayer: [[Int]] = Array() var mapSize:CGPoint { get { return CGPoint(x: tileLayer[0].count, y: tileLayer.count) } } //MARK: Setters and getters for the tile map mutating func setTile(position position:CGPoint, toValue:Int) { tileLayer[Int(position.y)][Int(position.x)] = toValue } func getTile(position position:CGPoint) -> Int { return tileLayer[Int(position.y)][Int(position.x)] } //MARK: Level creation mutating func loadLevel(level:Int, fromSet set:setType) { switch set { case .setMain: tileLayer = tileMapLevels.MainSet[level] break case .setBuilder: tileLayer = tileMapLevels.BuilderSet[level] break } } //MARK: Presenting the layer func presentLayerViaDelegate(level: Int) { for (indexr, row) in tileLayer.enumerate() { for (indexc, cvalue) in row.enumerate() { if (delegate != nil) { delegate!.createNodeOf(type: tileType(rawValue: cvalue)!, location: CGPoint( x: tileSize.width * CGFloat(indexc), y: tileSize.height * CGFloat(-indexr)), level: level) } } } } //MARK: Builder function func printLayer() { print("Tile Layer:") for row in tileLayer { print(row) } } }
31.459854
97
0.578422
f2230ee5e47742dfb7d567bd89ad3847d43e4f4a
799
sql
SQL
SongDatabaseScript.sql
Dashanan-Visharava-Kaikasi/AmpleRepository
444b7016f7f2313a6a029e4820097c920a8a0247
[ "MIT" ]
null
null
null
SongDatabaseScript.sql
Dashanan-Visharava-Kaikasi/AmpleRepository
444b7016f7f2313a6a029e4820097c920a8a0247
[ "MIT" ]
null
null
null
SongDatabaseScript.sql
Dashanan-Visharava-Kaikasi/AmpleRepository
444b7016f7f2313a6a029e4820097c920a8a0247
[ "MIT" ]
null
null
null
create table LanguageTable ( Id int primary key identity(1,1) not null, LanguageName nvarchar(100) NOT NULL UNIQUE ); create table Songs ( Id int primary key Identity(1,1) NOT NULL, SongName nvarchar(100) NOT NULL, SongLanguage int foreign key references LanguageTable(Id) ); create table SongArtist ( Id int primary key identity(1,1) not null, FName nvarchar(100) Not NULL, LName nvarchar(100) NOT NULL ); create table ArtistDetails ( Id int primary key identity(1,1) not null, Age int not null, ArtistImage nvarchar(255) Not null, ArtistId int foreign key references SongArtist(Id) ); create table ArtistSongRelation ( Id int primary key identity(1,1) not null, SongId int foreign key references Songs(Id), ArtistId int foreign key references SongArtist(Id) );
23.5
58
0.745932
80a5b8500fe24b96fc22af8ba0c0cdb2f949355d
990
java
Java
command-router-libary/src/com/imasson/commandrouter/annotation/ParamAlias.java
Masson/command-router
a4bee43f01999b2ec7a1967c4c2bc67b74ea3b21
[ "Apache-2.0" ]
2
2015-05-21T03:15:36.000Z
2015-09-17T06:55:29.000Z
command-router-libary/src/com/imasson/commandrouter/annotation/ParamAlias.java
Masson/command-router
a4bee43f01999b2ec7a1967c4c2bc67b74ea3b21
[ "Apache-2.0" ]
null
null
null
command-router-libary/src/com/imasson/commandrouter/annotation/ParamAlias.java
Masson/command-router
a4bee43f01999b2ec7a1967c4c2bc67b74ea3b21
[ "Apache-2.0" ]
null
null
null
package com.imasson.commandrouter.annotation; import com.imasson.commandrouter.converter.StringConverter; import com.imasson.commandrouter.converter.ValueConverter; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation used to define a parameter alias. * * @author Masson */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface ParamAlias { /** * The name (use as key) of the parameter that will be used in raw command. */ public String value(); /** * The class of converter that used to convert value. * If null, default converter for the target type will be used. */ public Class<? extends ValueConverter> converter() default StringConverter.class; /** * The default value of the parameter in raw String. * @return */ public String defaultRaw() default ""; }
27.5
85
0.724242
c7e1193f2e377729f59793d2067ea56af658d24b
1,412
java
Java
src/main/java/com/barreeyentos/catface/dto/CatFaceList.java
barreeyentos/catface
418ac68a7c7ed90b72694ea3e8d6bbd732298996
[ "MIT" ]
null
null
null
src/main/java/com/barreeyentos/catface/dto/CatFaceList.java
barreeyentos/catface
418ac68a7c7ed90b72694ea3e8d6bbd732298996
[ "MIT" ]
null
null
null
src/main/java/com/barreeyentos/catface/dto/CatFaceList.java
barreeyentos/catface
418ac68a7c7ed90b72694ea3e8d6bbd732298996
[ "MIT" ]
null
null
null
package com.barreeyentos.catface.dto; import java.util.List; /* * Wrapper DTO used to respond with multiple cat face solutions * Json response looks like: * { * "catFaces": [ {...}, {...}, ...] * } */ public class CatFaceList { List<CatFace> catFaces; // Default constructor for jackson serialization public CatFaceList() { }; public CatFaceList(List<CatFace> catFaces) { this.catFaces = catFaces; } public List<CatFace> getCatFaces() { return catFaces; } public void setCatFaces(List<CatFace> catFaces) { this.catFaces = catFaces; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((catFaces == null) ? 0 : catFaces.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CatFaceList other = (CatFaceList) obj; if (catFaces == null) { if (other.catFaces != null) return false; } else if (!catFaces.equals(other.catFaces)) return false; return true; } @Override public String toString() { return "CatFaceList [catFaces=" + catFaces + "]"; } }
23.147541
81
0.560198
800131c382dd9b1a453dc430b9483df956a6fb62
14,848
java
Java
DemoPrint/printcom/src/main/java/es/rcti/printerplus/printcom/models/StructReport.java
rcties/PrinterPlusCOMM
5bc992757f7cb97cb4c4ac78cc8516c32de4b28b
[ "Apache-2.0" ]
10
2019-11-11T13:03:28.000Z
2022-03-31T21:37:10.000Z
DemoPrint/printcom/src/main/java/es/rcti/printerplus/printcom/models/StructReport.java
rcties/PrinterPlusCOMM
5bc992757f7cb97cb4c4ac78cc8516c32de4b28b
[ "Apache-2.0" ]
null
null
null
DemoPrint/printcom/src/main/java/es/rcti/printerplus/printcom/models/StructReport.java
rcties/PrinterPlusCOMM
5bc992757f7cb97cb4c4ac78cc8516c32de4b28b
[ "Apache-2.0" ]
2
2020-01-17T11:56:46.000Z
2020-02-18T22:52:19.000Z
package es.rcti.printerplus.printcom.models; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Parcel; import android.os.Parcelable; import java.io.ByteArrayOutputStream; import java.io.Serializable; import java.util.ArrayList; import es.rcti.printerplus.printcom.models.util.ImgTools; import es.rcti.printerplus.printcom.models.util.SReportItem; /** * Created by www.rcti.es on 26/08/2015. */ public class StructReport implements Parcelable, Serializable { private final static int IMAGE_MAX_WIDTH = 380; public final static int KEY_ALIGNMENT = 30301; public final static int KEY_SIZE_FONT_W = 30302; public final static int KEY_SIZE_FONT_H = 30303; public final static int KEY_LINE_SPACE = 30304; public final static int KEY_TEXT_STYLE_UNDERLINE = 30305; public final static int KEY_TEXT_STYLE_BOLD = 30306; public final static int KEY_TEXT = 30307; public final static int KEY_TEXT_REVERSE_MODE = 30308; public final static int KEY_TEXT_X_POSITION = 30309; public final static int KEY_FEED_UNIT = 30310; public final static int KEY_IMAGE_PATH = 30311; public final static int KEY_IMAGE_MODE = 30312; public final static int KEY_IMAGE_HALFTONE = 30313; public final static int KEY_IMAGE_BRIGHTNESS = 30314; public final static int KEY_CUT_TYPE = 30315; public final static int KEY_CUT = 30316; public final static int KEY_BARCODE_DATA = 30317; public final static int KEY_BARCODE_TYPE = 30318; public final static int KEY_BARCODE_HRI = 30319; public final static int KEY_BARCODE_WIDTH = 30320; public final static int KEY_BARCODE_HEIGHT = 30321; public final static int KEY_OPEN_DRAWER = 30322; public final static int KEY_FONT = 30323; public final static int KEY_COLOR = 30324; public final static int KEY_TEXT_LANG = 30325; private ArrayList<SReportItem> items; public StructReport() { this.items = new ArrayList<SReportItem>(); } public ArrayList<SReportItem> getItems() { return items; } public void freeMem() { items.clear(); items = null; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int i) { parcel.writeTypedList(items); } public static final Creator<StructReport> CREATOR = new Creator<StructReport>() { public StructReport createFromParcel(Parcel in) { return new StructReport(in); } public StructReport[] newArray(int size) { return new StructReport[size]; } }; private StructReport(Parcel in) { items = new ArrayList<SReportItem>(); in.readTypedList(items, SReportItem.CREATOR); } /** * This method lets you to set the ALIGNMENT for Image, Text and Barcode. * @param alignmentType ALIGNMENT_LEFT, ALIGNMENT_CENTER, ALIGNMENT_RIGHT */ public void addItemAlignment(int alignmentType) { String auxArray[] = {String.valueOf(alignmentType)}; items.add(new SReportItem(KEY_ALIGNMENT, auxArray)); } /** * This method lets you to set the FONT SIZE, it contains the width and height. * @param charWidth SIZE_FONT_1 to SIZE_FONT_8 */ public void addItemSizeFont(int charWidth) { String auxArray[] = {String.valueOf(charWidth)}; items.add(new SReportItem(KEY_SIZE_FONT_W, auxArray)); } /** * This method lets you to set LINE SPACING, by default is 30. * @param dpSize 0 .. 30 .. X */ public void addLineSpace(int dpSize) { String auxArray[] = {String.valueOf(dpSize)}; items.add(new SReportItem(KEY_LINE_SPACE, auxArray)); } /** * This method lets you to enable or disable UNDERLINE for text. * @param enabled true to enable */ public void addTextUnderlined(boolean enabled) { String auxArray[] = {String.valueOf(enabled)}; items.add(new SReportItem(KEY_TEXT_STYLE_UNDERLINE, auxArray)); } /** * This method lets you to enable or disable BOLD for text. * @param enabled true to enable */ public void addTextBold(boolean enabled) { String auxArray[] = {String.valueOf(enabled)}; items.add(new SReportItem(KEY_TEXT_STYLE_BOLD, auxArray)); } /** * This method lets you to enable or disable REVERSE MODE for text. * @param reverse true to enable */ public void addTextReverseMode(boolean reverse) { String auxArray[] = {String.valueOf(reverse)}; items.add(new SReportItem(KEY_TEXT_REVERSE_MODE, auxArray)); } /** * This method lets you to set (AXIS X) horizontal starting position to print. * @param xposition 0 .. x .. n column to start to print */ public void addTextPosition(int xposition) { String auxArray[] = {String.valueOf(xposition)}; items.add(new SReportItem(KEY_TEXT_X_POSITION, auxArray)); } /** * This method lets you to add a TEXT MESSAGE to be printed. * @param text message to print */ public void addText(String text) { String auxArray[] = {text}; items.add(new SReportItem(KEY_TEXT, auxArray)); } /** * This method lets you to set (AXIS Y) FEED unit, by default is 30. * @param dpSize 0 .. 30 .. X */ public void addFeedUnit(int dpSize) { String auxArray[] = {String.valueOf(dpSize)}; items.add(new SReportItem(KEY_FEED_UNIT, auxArray)); } /** * This method lets you to add an IMAGE to be printed. * @param mbmp a Bitmap object */ public void addImageBitmap(Bitmap mbmp) { Bitmap bmp = ImgTools.getResizedBitmap(mbmp, IMAGE_MAX_WIDTH); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray(); String auxArray[] = {"nopath", String.valueOf(bmp.getWidth()), String.valueOf(bmp.getHeight())}; items.add(new SReportItem(KEY_IMAGE_PATH, auxArray, byteArray)); } /** * This method lets you to add an IMAGE to be sent to print. * @param path public full path location from a image file */ public void addImagePath(String path) { Bitmap bmp = BitmapFactory.decodeFile(path); bmp = ImgTools.getResizedBitmap(bmp, IMAGE_MAX_WIDTH); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bmp.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] byteArray = stream.toByteArray(); String auxArray[] = {path, String.valueOf(bmp.getWidth()), String.valueOf(bmp.getHeight())}; items.add(new SReportItem(KEY_IMAGE_PATH, auxArray, byteArray)); } /** * This method lets you to set IMAGE MODE for color. * @param mode IMAGE_MODE_MONO or IMAGE_MODE_GRAY16 */ public void addImageMode(int mode) { String auxArray[] = {String.valueOf(mode)}; items.add(new SReportItem(KEY_IMAGE_MODE, auxArray)); } /** * This method lets you to set IMAGE HALFTONE or texture. * @param halftone IMAGE_HALFTONE_DITHER or IMAGE_HALFTONE_ERROR_DIFUSION or IMAGE_HALFTONE_THRESHOLD */ public void addImageHalftone(int halftone) { String auxArray[] = {String.valueOf(halftone)}; items.add(new SReportItem(KEY_IMAGE_HALFTONE, auxArray)); } /** * This method lets you to enable MODE CUT AND FEED or by disabling only applies CUT. * @param cutAndFeed true if cut and feed. */ public void addCutType(boolean cutAndFeed) { String auxArray[] = {String.valueOf(cutAndFeed)}; items.add(new SReportItem(KEY_CUT_TYPE, auxArray)); } /** * This method lets you to add an order for CUT to be executed. * Sends order to cut paper */ public void addCut() { String auxArray[] = {"0"}; items.add(new SReportItem(KEY_CUT, auxArray)); } /** * This method lets you to add FONT, it could be: * FONT_A, FONT_B, FONT_C, FONT_D, FONT_E * @param typeFont FONT_X */ public void addFont(int typeFont) { String auxArray[] = {String.valueOf(typeFont)}; items.add(new SReportItem(KEY_FONT, auxArray)); } /** * USELESS METHOD (DEPRECATED) * Now it is not necessary, because the printer receives the unicode text format and * draws on their respective char map. * * This method lets you to set lang or code page to print, it could be: * LANG_EN, LANG_JA, LANG_KO, LANG_TH, LANG_VI, LANG_ZH_CN or LANG_ZH_TW. * @param typeLang LANG_XX */ public void addTextLang(int typeLang) { String auxArray[] = {String.valueOf(typeLang)}; items.add(new SReportItem(KEY_TEXT_LANG, auxArray)); } /** * This method lets you to set the color to be selected to print * it could be: * COLOR_1, COLOR_2, COLOR_3, COLOR_4 * depends on printer colors allowed. * @param typeColor COLOR_X */ public void addColor(int typeColor) { String auxArray[] = {String.valueOf(typeColor)}; items.add(new SReportItem(KEY_COLOR, auxArray)); } /** * This method lets you to set BARCODE TYPE * it coudl be: * BARCODE_UPC_A, BARCODE_UPC_E, BARCODE_EAN13, BARCODE_JAN13, BARCODE_EAN8, * BARCODE_JAN8, BARCODE_CODE39, BARCODE_ITF, BARCODE_CODABAR, BARCODE_CODE93, * BARCODE_CODE128, BARCODE_GS1_128, BARCODE_GS1_DATABAR_OMNIDIRECTIONAL, * BARCODE_GS1_DATABAR_TRUNCATED, BARCODE_GS1_DATABAR_LIMITED or * BARCODE_GS1_DATABAR_EXPANDED. * @param typeBarcode BARCODE_XXXX */ public void addBarcodeType(int typeBarcode) { String auxArray[] = {String.valueOf(typeBarcode)}; items.add(new SReportItem(KEY_BARCODE_TYPE, auxArray)); } /** * This method lets you to set BARCODE HUMAN READABLE INFORMATION * it could be: * BARCODE_HRI_ABOVE to enable write the information above of barcode * BARCODE_HRI_BELOW to enable write the information below of barcode * BARCODE_HRI_BOTH to enable write the information above and below of barcode * BARCODE_HRI_NONE to disable write the information of barcode * @param typeHRI BARCODE_HRI_XXXX */ public void addBarcodeHRI(int typeHRI) { String auxArray[] = {String.valueOf(typeHRI)}; items.add(new SReportItem(KEY_BARCODE_HRI, auxArray)); } /** * This method lets you to set a BARCODE WIDTH, by default is 2. * @param width [2 .. 5] */ public void addBarcodeWidth(int width){ String auxArray[] = {String.valueOf(width)}; items.add(new SReportItem(KEY_BARCODE_WIDTH, auxArray)); } /** * This method lets you to set a BARCODE HEIGHT, by default is 50. * @param height [30 .. 300] */ public void addBarcodeHeight(int height) { String auxArray[] = {String.valueOf(height)}; items.add(new SReportItem(KEY_BARCODE_HEIGHT, auxArray)); } /** * This method lets you to add a text BARCODE to be printed. * @param data info[data] to generate a barcode */ public void addBarcodeData(String data) { String auxArray[] = {String.valueOf(data)}; items.add(new SReportItem(KEY_BARCODE_DATA, auxArray)); } /** * This method lets you to add a OPEN DRAWER order to be executed. */ public void addOpenDrawer() { String auxArray[] = {String.valueOf("")}; items.add(new SReportItem(KEY_OPEN_DRAWER, auxArray)); } /* Customized keys */ public final static int ALIGNMENT_LEFT = 90001; public final static int ALIGNMENT_CENTER = 90002; public final static int ALIGNMENT_RIGHT = 90003; public final static int FONT_A = 0; public final static int FONT_B = 1; public final static int FONT_C = 2; public final static int FONT_D = 3; public final static int FONT_E = 4; public final static int COLOR_1 = 0; public final static int COLOR_2 = 1; public final static int COLOR_3 = 2; public final static int COLOR_4 = 3; public final static int SIZE_FONT_1 = 1; public final static int SIZE_FONT_2 = 2; public final static int SIZE_FONT_3 = 3; public final static int SIZE_FONT_4 = 4; public final static int SIZE_FONT_5 = 5; public final static int SIZE_FONT_6 = 6; public final static int SIZE_FONT_7 = 7; public final static int SIZE_FONT_8 = 8; public static final int BARCODE_HRI_ABOVE =1; public static final int BARCODE_HRI_BELOW =2; public static final int BARCODE_HRI_BOTH =3; public static final int BARCODE_HRI_NONE =0; public static final int BARCODE_UPC_A = 70000; public static final int BARCODE_UPC_E = 70001; public static final int BARCODE_EAN13 = 70002; public static final int BARCODE_JAN13 = 70003; public static final int BARCODE_EAN8 = 70004; public static final int BARCODE_JAN8 = 70005; public static final int BARCODE_CODE39 = 70006; public static final int BARCODE_ITF = 70007; public static final int BARCODE_CODABAR = 70008; public static final int BARCODE_CODE93 = 70009; public static final int BARCODE_CODE128 = 70010; public static final int BARCODE_GS1_128 = 70011; public static final int BARCODE_GS1_DATABAR_OMNIDIRECTIONAL = 70012; public static final int BARCODE_GS1_DATABAR_TRUNCATED = 70013; public static final int BARCODE_GS1_DATABAR_LIMITED = 70014; public static final int BARCODE_GS1_DATABAR_EXPANDED = 70015; public static final int IMAGE_MODE_MONO = 1; public static final int IMAGE_MODE_GRAY16 = 0; public static final int IMAGE_HALFTONE_DITHER = 0; public static final int IMAGE_HALFTONE_ERROR_DIFUSION = 1; public static final int IMAGE_HALFTONE_THRESHOLD = 2; public static final int LANG_EN = 0; public static final int LANG_JA = 1; public static final int LANG_KO = 2; public static final int LANG_TH = 3; public static final int LANG_VI = 4; public static final int LANG_ZH_CN = 5; public static final int LANG_ZH_TW = 6; }
36.935323
105
0.650054
8f52f55c9d9df0e9687bf4be9e5b52e892bf4696
384
ps1
PowerShell
scripts/publish.packages.remote.ps1
JustMeGaaRa/Silent.Practices
8e82e2ecda9e757ef30aaefafdbdb8e8ea4929c4
[ "Apache-2.0" ]
1
2017-04-14T15:25:29.000Z
2017-04-14T15:25:29.000Z
scripts/publish.packages.remote.ps1
JustMeGaaRa/Silent.Practices
8e82e2ecda9e757ef30aaefafdbdb8e8ea4929c4
[ "Apache-2.0" ]
null
null
null
scripts/publish.packages.remote.ps1
JustMeGaaRa/Silent.Practices
8e82e2ecda9e757ef30aaefafdbdb8e8ea4929c4
[ "Apache-2.0" ]
null
null
null
$rootPath = (Resolve-Path ".\").Path $nupkgsPath = Join-Path $rootPath "artifacts\packages" $remotePath = "https://www.nuget.org/api/v2/package" # Publish all *.nupkg files to nuget gallery $nupkgs = dir -File $nupkgsPath | Select -ExpandProperty FullName foreach ($nupkg in $nupkgs) { Write-Host "Publish $nupkg" -Foreground Green dotnet nuget push $nupkg --source $remotePath }
32
65
0.731771
5cbf8ff7e1a2bbbf739e504f04276f35e14f5e62
5,571
swift
Swift
submodules/Camera/Sources/CameraDevice.swift
Sergey70/Telegram-iOS
331b51ee204b92bb4c3aa8d4006a5070d4644770
[ "AML" ]
null
null
null
submodules/Camera/Sources/CameraDevice.swift
Sergey70/Telegram-iOS
331b51ee204b92bb4c3aa8d4006a5070d4644770
[ "AML" ]
null
null
null
submodules/Camera/Sources/CameraDevice.swift
Sergey70/Telegram-iOS
331b51ee204b92bb4c3aa8d4006a5070d4644770
[ "AML" ]
null
null
null
import Foundation import AVFoundation import SwiftSignalKit private let defaultFPS: Double = 30.0 final class CameraDevice { public private(set) var videoDevice: AVCaptureDevice? = nil public private(set) var audioDevice: AVCaptureDevice? = nil private var videoDevicePromise = Promise<AVCaptureDevice>() init() { } var position: Camera.Position = .back func configure(for session: AVCaptureSession, position: Camera.Position) { self.position = position if #available(iOSApplicationExtension 10.0, iOS 10.0, *) { self.videoDevice = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInDuoCamera, .builtInWideAngleCamera, .builtInTelephotoCamera], mediaType: .video, position: position).devices.first } else { self.videoDevice = AVCaptureDevice.devices(for: .video).filter { $0.position == position }.first } if let videoDevice = self.videoDevice { self.videoDevicePromise.set(.single(videoDevice)) } self.audioDevice = AVCaptureDevice.default(for: .audio) } func transaction(_ device: AVCaptureDevice, update: (AVCaptureDevice) -> Void) { if let _ = try? device.lockForConfiguration() { update(device) device.unlockForConfiguration() } } private func subscribeForChanges() { NotificationCenter.default.addObserver(self, selector: #selector(self.subjectAreaChanged), name: Notification.Name.AVCaptureDeviceSubjectAreaDidChange, object: self.videoDevice) } private func unsubscribeFromChanges() { NotificationCenter.default.removeObserver(self, name: Notification.Name.AVCaptureDeviceSubjectAreaDidChange, object: self.videoDevice) } @objc private func subjectAreaChanged() { } var fps: Double = defaultFPS { didSet { guard let device = self.videoDevice, let targetFPS = device.actualFPS(Double(self.fps)) else { return } self.fps = targetFPS.fps self.transaction(device) { device in device.activeVideoMinFrameDuration = targetFPS.duration device.activeVideoMaxFrameDuration = targetFPS.duration } } } var isFlashActive: Signal<Bool, NoError> { return self.videoDevicePromise.get() |> mapToSignal { device -> Signal<Bool, NoError> in return Signal { subscriber in subscriber.putNext(device.isFlashActive) let observer = device.observe(\.isFlashActive, options: [.new], changeHandler: { device, _ in subscriber.putNext(device.isFlashActive) }) return ActionDisposable { observer.invalidate() } } |> distinctUntilChanged } } var isFlashAvailable: Signal<Bool, NoError> { return self.videoDevicePromise.get() |> mapToSignal { device -> Signal<Bool, NoError> in return Signal { subscriber in subscriber.putNext(device.isFlashAvailable) let observer = device.observe(\.isFlashAvailable, options: [.new], changeHandler: { device, _ in subscriber.putNext(device.isFlashAvailable) }) return ActionDisposable { observer.invalidate() } } |> distinctUntilChanged } } var isAdjustingFocus: Signal<Bool, NoError> { return self.videoDevicePromise.get() |> mapToSignal { device -> Signal<Bool, NoError> in return Signal { subscriber in subscriber.putNext(device.isAdjustingFocus) let observer = device.observe(\.isAdjustingFocus, options: [.new], changeHandler: { device, _ in subscriber.putNext(device.isAdjustingFocus) }) return ActionDisposable { observer.invalidate() } } |> distinctUntilChanged } } func setFocusPoint(_ point: CGPoint, focusMode: Camera.FocusMode, exposureMode: Camera.ExposureMode, monitorSubjectAreaChange: Bool) { guard let device = self.videoDevice else { return } self.transaction(device) { device in if device.isExposurePointOfInterestSupported && device.isExposureModeSupported(exposureMode) { device.exposurePointOfInterest = point device.exposureMode = exposureMode } if device.isFocusPointOfInterestSupported && device.isFocusModeSupported(focusMode) { device.focusPointOfInterest = point device.focusMode = focusMode } } } func setExposureTargetBias(_ bias: Float) { guard let device = self.videoDevice else { return } self.transaction(device) { device in let extremum = (bias >= 0) ? device.maxExposureTargetBias : device.minExposureTargetBias; let value = abs(bias) * extremum * 0.85 device.setExposureTargetBias(value, completionHandler: nil) } } func setTorchActive(_ active: Bool) { guard let device = self.videoDevice else { return } self.transaction(device) { device in device.torchMode = active ? .on : .off } } }
37.641892
200
0.601687
621a7ee92aedbe55e2d303b0a0a05f7c1cfaae81
158
swift
Swift
assets/media/snippets/posts/2016-06-30/swift-5.swift
nguabatkham/nguabatkham.github.io
4ce94ae0f78f0961c4709557eb1a19b5f9bb9eb8
[ "MIT" ]
null
null
null
assets/media/snippets/posts/2016-06-30/swift-5.swift
nguabatkham/nguabatkham.github.io
4ce94ae0f78f0961c4709557eb1a19b5f9bb9eb8
[ "MIT" ]
null
null
null
assets/media/snippets/posts/2016-06-30/swift-5.swift
nguabatkham/nguabatkham.github.io
4ce94ae0f78f0961c4709557eb1a19b5f9bb9eb8
[ "MIT" ]
null
null
null
optionalInt = nil if let checkedInt = optionalInt { print(checkedInt) "checkedInt = \(checkedInt)" } else { print("nil") "no value for checkedInt" }
15.8
33
0.677215